OpenCV3.3中主成分分析(Principal Components Analysis, PCA)接口简介及使用
OpenCV3.3中給出了主成分分析(Principal Components Analysis, PCA)的實現(xiàn),即cv::PCA類,類的聲明在include/opencv2/core.hpp文件中,實現(xiàn)在modules/core/src/pca.cpp文件中,其中:
(1)、cv::PCA::PCA:構(gòu)造函數(shù);
(2)、cv::PCA::operator():函數(shù)調(diào)用運算符;
(3)、cv::PCA::project:將輸入數(shù)據(jù)投影到PCA主成分空間;
(4)、cv::PCA::backProject:重建原始數(shù)據(jù);
(5)、cv::PCA::write:將特征值、特征向量、均值寫入指定的文件;
(6)、cv::PCA::read:從指定文件讀入特征值、特征向量、均值;
(7)、cv::PCA::eigenvectors:協(xié)方差矩陣的特征向量;
(8)、cv::PCA::eigenvalues:協(xié)方差矩陣的特征值;
(9)、cv::PCA::mean:均值。
關(guān)于PCA的介紹可以參考:?http://blog.csdn.net/fengbingchun/article/details/78977202?
以下是使用ORL Faces Database作為測試圖像。關(guān)于ORL Faces Database的介紹可以參考:?http://blog.csdn.net/fengbingchun/article/details/79008891?
測試代碼如下:
#include "opencv.hpp"
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
#include <opencv2/opencv.hpp>
#include <opencv2/ml.hpp>
#include "common.hpp"// PCA(Principal Component Analysis) ///
int test_opencv_pca()
{// reference: opencv-3.3.0/samples/cpp/pca.cppconst std::string image_path{ "E:/GitCode/NN_Test/data/database/ORL_Faces/" };const std::string image_name{ "1.pgm" };std::vector<cv::Mat> images;for (int i = 1; i <= 15; ++i) {std::string name = image_path + "s" + std::to_string(i) + "/" + image_name;cv::Mat mat = cv::imread(name, 0);if (!mat.data) {fprintf(stderr, "read image fail: %s\n", name.c_str());return -1;}images.emplace_back(mat);}cv::Mat data(images.size(), images[0].rows * images[0].cols, CV_32FC1);for (int i = 0; i < images.size(); ++i) {cv::Mat image_row = images[i].clone().reshape(1, 1);cv::Mat row_i = data.row(i);image_row.convertTo(row_i, CV_32F);}cv::PCA pca(data, cv::Mat(), cv::PCA::DATA_AS_ROW, 0.95f);std::vector<cv::Mat> result(images.size());for (int i = 0; i < images.size(); ++i) {// Demonstration of the effect of retainedVariance on the first imagecv::Mat point = pca.project(data.row(i)); // project into the eigenspace, thus the image becomes a "point"cv::Mat reconstruction = pca.backProject(point); // re-create the image from the "point"reconstruction = reconstruction.reshape(images[i].channels(), images[i].rows); // reshape from a row vector into image shapecv::normalize(reconstruction, reconstruction, 0, 255, cv::NORM_MINMAX, CV_8UC1);reconstruction.copyTo(result[i]);}save_images(result, "E:/GitCode/NN_Test/data/pca_result_.jpg", 5);// save fileconst std::string save_file{ "E:/GitCode/NN_Test/data/pca.xml" }; // .xml, .yaml, .jsonscv::FileStorage fs(save_file, cv::FileStorage::WRITE);pca.write(fs);fs.release();// read fileconst std::string& read_file = save_file;cv::FileStorage fs2(read_file, cv::FileStorage::READ);cv::PCA pca2;pca2.read(fs2.root());fs2.release();return 0;
}
????? ? 結(jié)果圖像如下:
GitHub:? https://github.com/fengbingchun/NN_Test?
總結(jié)
以上是生活随笔為你收集整理的OpenCV3.3中主成分分析(Principal Components Analysis, PCA)接口简介及使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ORL Faces Database介绍
- 下一篇: 主成分分析(PCA)Python代码实现