参考http://www.xxkb.com.cn/?action=show&id=69所提出得步骤,依葫芦画瓢,果然好用!
代码奉上:
#include <cv.h> #include <highgui.h> #include <fstream> #include <iostream> #include <algorithm> using namespace std; void print_cvmat(CvMat* M) { for (int i = 0; i < M->rows;++i) for(int j = 0;j < M->cols; ++j) cout << cvmGet(M,i,j) << " "; } int main() { ifstream myfile( "E:\\feature_size.txt "); if (!myfile.is_open()) cout << "Unable to open file"; int rows = 0,cols = 0; myfile >> rows >> cols; myfile.close(); //初始化数据 //每一行表示一个样本 CvMat *pData = cvCreateMat(rows,cols,CV_32FC1);; ifstream fin("E:\\features.txt ",ifstream::in); for(int i = 0;i < rows; ++i) for(int j = 0;j < cols; ++j) { fin >> pData->data.fl[i*cols+j]; } fin.close(); CvMat* pMean = cvCreateMat(1, cols, CV_32FC1); //pEigVals中的每个数表示一个特征值 CvMat* pEigVals = cvCreateMat(1, min(rows,cols), CV_32FC1); //每一行表示一个特征向量 CvMat* pEigVecs = cvCreateMat( min(rows,cols), cols, CV_32FC1); //PCA处理,计算出平均向量pMean,特征值pEigVals和特征向量pEigVecs cvCalcPCA( pData, pMean, pEigVals, pEigVecs, CV_PCA_DATA_AS_ROW ); print_cvmat(pEigVals); //选出前P个特征向量(主成份),然后投影,结果保存在pResult中,pResult中包含了P个系数 CvMat* pResult = cvCreateMat( rows, 20, CV_32FC1 ); cvProjectPCA( pData, pMean, pEigVecs, pResult ); //重构,结果保存在pRecon中,这步貌似对我没必要 //CvMat* pRecon = cvCreateMat( rows, cols, CV_32FC1 ); //cvBackProjectPCA( pResult, pMean, pEigVecs, pRecon ); //存储起来 ofstream file( "E:\\feature_pca.txt "); for (int i = 0; i < pResult->rows;++i) { for(int j = 0;j < pResult->cols; ++j) { file << cvmGet(pResult,i,j) << " "; } file << "\n"; } }