1. 程式人生 > >PCA降維demo

PCA降維demo

效果 cti 代碼 push jpg per ims whitening get

PCA(Principal Components Analysis)主成分分析法是一種常用的減小數據維度的算法。

能力有限在這裏就不做過多的數學分析了,具體原理可參見http://ufldl.stanford.edu/tutorial/unsupervised/PCAWhitening/ 以及更具體的CS229

這裏結合網上代碼做個簡單的示例

static Mat formatImagesForPCA(const vector<Mat> &data)
{
    Mat dst(static_cast<int>(data.size()), data[0].rows*data[0
].cols, CV_32F); for (unsigned int i = 0; i < data.size(); i++) { Mat image_row = data[i].clone().reshape(1, 1); Mat row_i = dst.row(i); image_row.convertTo(row_i, CV_32F); } return dst; } static Mat toGrayscale(InputArray _src) { Mat src = _src.getMat();
// only allow one channel if (src.channels() != 1) { CV_Error(CV_StsBadArg, "Only Matrices with one channel are supported"); } // create and return normalized image Mat dst; cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1); return dst; } void main(int argc, char** argv) { Mat src1
= imread("F:\\cha_classification\\train\\c0.jpg"); Mat src2 = imread("F:\\cha_classification\\train\\c1.jpg"); Mat src3 = imread("F:\\cha_classification\\train\\c2.jpg"); Mat g1, g2, g3; vector<Mat> gray; cvtColor(src1, g1, CV_RGB2GRAY); gray.push_back(g1); cvtColor(src2, g2, CV_RGB2GRAY); gray.push_back(g2); cvtColor(src3, g3, CV_RGB2GRAY); gray.push_back(g3); imshow("g1", g1); //waitKey(0); Mat data = formatImagesForPCA(gray);//data矩陣大小為:3*(18*18)// cout << pcaSet << endl; PCA pca(data, cv::Mat(), CV_PCA_DATA_AS_ROW, 0.99); //PCA pca(data, Mat(), 200 ); cout << pca.eigenvalues << endl; cout << endl; //cout << pca.eigenvectors << endl; // 將PCA降維的效果用第一張圖片來顯示出來。 Mat point = pca.project(data.row(0)); // project into the eigenspace, thus the image becomes a "point" Mat reconstruction = pca.backProject(point); // re-create the image from the "point" reconstruction = reconstruction.reshape(gray[0].channels(), gray[0].rows); // reshape from a row vector into image shape reconstruction = toGrayscale(reconstruction); // re-scale for displaying purposes namedWindow("r", WINDOW_NORMAL); imshow("r", reconstruction); waitKey(0); //return 0; }

技術分享

技術分享

技術分享

簡單的讀取三張漢字的圖片轉換為灰度圖像後將圖片轉為行的形式儲存。利用opencv中pca進行分析後取技術分享

顯示第一張圖技術分享只降了一個維度看起來跟原圖一樣

PCA降維demo