帮我写出用c++对一张图片进行主成分分析得到方向和均值点,并在图中画出方向的代码
时间: 2023-03-26 15:00:31 浏览: 114
主成分分析PCA源代码(C++,matlab).zip_matlab)_neighbor1rt_wheatgva_主成分分析pc
以下是用 C 语言对一张图片进行主成分分析得到方向和均值点,并在图中画出方向的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define WIDTH 256
#define HEIGHT 256
typedef struct {
double x;
double y;
} Point;
int main() {
FILE *fp;
unsigned char img[WIDTH][HEIGHT];
Point points[WIDTH * HEIGHT];
int num_points = ;
double sum_x = ., sum_y = .;
double cov_xx = ., cov_xy = ., cov_yy = .;
double eigenvalue1, eigenvalue2;
Point eigenvector1, eigenvector2;
Point mean_point;
int i, j;
// 读取图片
fp = fopen("image.bmp", "rb");
fseek(fp, 54, SEEK_SET);
fread(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
// 提取点集
for (i = ; i < WIDTH; i++) {
for (j = ; j < HEIGHT; j++) {
if (img[i][j] > 128) {
points[num_points].x = i;
points[num_points].y = j;
num_points++;
sum_x += i;
sum_y += j;
}
}
}
// 计算均值点
mean_point.x = sum_x / num_points;
mean_point.y = sum_y / num_points;
// 计算协方差矩阵
for (i = ; i < num_points; i++) {
cov_xx += (points[i].x - mean_point.x) * (points[i].x - mean_point.x);
cov_xy += (points[i].x - mean_point.x) * (points[i].y - mean_point.y);
cov_yy += (points[i].y - mean_point.y) * (points[i].y - mean_point.y);
}
// 计算特征值和特征向量
eigenvalue1 = (cov_xx + cov_yy + sqrt((cov_xx - cov_yy) * (cov_xx - cov_yy) + 4 * cov_xy * cov_xy)) / 2;
eigenvalue2 = (cov_xx + cov_yy - sqrt((cov_xx - cov_yy) * (cov_xx - cov_yy) + 4 * cov_xy * cov_xy)) / 2;
eigenvector1.x = eigenvalue1 - cov_yy;
eigenvector1.y = cov_xy;
eigenvector2.x = eigenvalue2 - cov_yy;
eigenvector2.y = cov_xy;
// 画出方向
fp = fopen("image_direction.bmp", "wb");
fseek(fp, , SEEK_SET);
fwrite(img, sizeof(unsigned char), 54, fp);
for (i = ; i < WIDTH; i++) {
for (j = ; j < HEIGHT; j++) {
if (img[i][j] > 128) {
double dx1 = i - mean_point.x + eigenvector1.x;
double dy1 = j - mean_point.y + eigenvector1.y;
double dx2 = i - mean_point.x + eigenvector2.x;
double dy2 = j - mean_point.y + eigenvector2.y;
if (dx1 * dx1 + dy1 * dy1 > dx2 * dx2 + dy2 * dy2) {
img[i][j] = ;
} else {
img[i][j] = 255;
}
}
}
}
fwrite(img, sizeof(unsigned char), WIDTH * HEIGHT, fp);
fclose(fp);
return ;
}
```
阅读全文