openCv特征值 特征向量(行向量)

#include <iostream>
#include <vector>
#include <highgui.h>
#include <cv.h>


using namespace std;
typedef vector<vector<double>> martix;


//template<class T>
martix GetEigenMat( martix &k )
{
CvMat* M = cvCreateMat(k.size(),k.size(),CV_32FC1);
cvZero(M);
for(int i = 0; i < k.size(); i++)
for(int j = 0; j < k.size(); j++)
cvmSet(M, i, j, k[i][j]);


CvMat* E = cvCreateMat(k.size(), k.size(), CV_32FC1);
cvZero(E);


CvMat* I = cvCreateMat(k.size(), 1, CV_32FC1);
cvZero(I);


//从矩阵M中获取特征向量存入E(降序排列),特征值存入I
cvEigenVV(M, E, I, DBL_EPSILON);


vector<double> a(k.size(),0);
vector< vector<double> > eigenMat(3,a);
vector<double> eigenValueMat(a);


//取前两个最大的特征向量
for(int i = 0; i < 3; i++)
for(int j = 0; j < k.size(); j++)
eigenMat[i][j] = cvmGet(E,i,j);


for(int i = 0; i < 3; i++)
eigenValueMat[i] = cvmGet(I, i, 0);


FILE *fp1 = NULL;
fp1 = fopen("eigenValues.txt", "w");
for (int i = 0; i < 3; i++)
{
fprintf_s(fp1,"%lf ", eigenValueMat[i]);
}
fclose(fp1);


cvReleaseMat(&M);
cvReleaseMat(&E);
cvReleaseMat(&I);


return eigenMat;
}


int main(void)
{
vector<vector<double>> Matr;
vector<vector<double>> eigen;
FILE * fp = fopen("./m.txt", "r");
int w, h;
fscanf(fp, "%d %d\n", &w, &h);
if(w != h){
printf("martix width != height\n");
return 1;
}
double _value;
vector<double> _line;
for (int i = 0; i < h; i++){
for(int j = 0; j < w; j++)
{
fscanf(fp, "%lf ", &_value);
_line.push_back(_value);
}
Matr.push_back(_line);
_line.clear();
}
fclose(fp);


eigen = GetEigenMat(Matr);
FILE *fp1 = NULL;
fp1 = fopen("eigen.txt", "w");
for (int i = 0; i < 3; i++){
for(int j = 0; j < w; j++)
{
fprintf_s(fp1,"%lf ", eigen[i][j]);
}
fputc('\n', fp1);
}
fclose(fp1);
int temp = 10;
}

你可能感兴趣的:(openCv特征值 特征向量(行向量))