1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #include <opencv2\opencv.hpp> #include <opencv2\highgui\highgui.hpp> #include <opencv2\ml\ml.hpp> using namespace cv; using namespace std; void DoPca(const Mat &_data, int dim, Mat &eigenvalues, Mat &eigenvectors); void printMat( Mat _data ) { Mat data = cv::Mat_<double>(_data); for ( int i=0; i<data.rows; i++ ) { for ( int j=0; j< data.cols; j++ ) { cout << data.at<double>(i,j) << " "; } cout << endl; } } int main(int argc, char* argv[]) { float A[ 60 ]={ 1.5 , 2.3 , 1.5 , 2.3 , 1.5 , 2.3 , 3.0 , 1.7 , 3.0 , 1.7 , 3.0 , 1.7 , 1.2 , 2.9 , 1.2 , 2.9 , 1.2 , 2.9 , 2.1 , 2.2 , 2.1 , 2.2 , 2.1 , 2.2 , 3.1 , 3.1 , 3.1 , 3.1 , 3.1 , 3.1 , 1.3 , 2.7 , 1.3 , 2.7 , 1.3 , 2.7 , 2.0 , 1.7 , 2.0 , 1.7 , 2.0 , 1.7 , 1.0 , 2.0 , 1.0 , 2.0 , 1.0 , 2.0 , 0.5 , 0.6 , 0.5 , 0.6 , 0.5 , 0.6 , 1.0 , 0.9 , 1.0 , 0.9 , 1.0 , 0.9 }; Mat DataMat = Mat::zeros( 10, 6, CV_32F ); for ( int i=0; i<10; i++ ) { for ( int j=0; j<6; j++ ) { DataMat.at<float>(i, j) = A[i * 6 + j]; } } PCA pca(DataMat, noArray(), CV_PCA_DATA_AS_ROW); Mat eigenvalues; Mat eigenvectors; DoPca(DataMat, 3, eigenvalues, eigenvectors); cout << "eigenvalues:" << endl; printMat( eigenvalues ); cout << "\n" << endl; cout << "eigenvectors:" << endl; printMat( eigenvectors ); system("pause"); return 0; } void DoPca(const Mat &_data, int dim, Mat &eigenvalues, Mat &eigenvectors) { assert( dim>0 ); Mat data = cv::Mat_<double>(_data); int R = data.rows; int C = data.cols; if ( dim>C ) dim = C; Mat m = Mat::zeros( 1, C, data.type() ); for ( int j=0; j<C; j++ ) { for ( int i=0; i<R; i++ ) { m.at<double>(0,j) += data.at<double>(i,j); } } m = m/R; Mat S = Mat::zeros( R, C, data.type() ); for ( int i=0; i<R; i++ ) { for ( int j=0; j<C; j++ ) { S.at<double>(i,j) = data.at<double>(i,j) - m.at<double>(0,j); } } Mat Average = S.t() * S /(R); eigen(Average, eigenvalues, eigenvectors); }
|