OpenCV3.3中主成分分析(Principal Components Analysis, PCA)介面簡介及使用

fengbingchun發表於2018-01-13

OpenCV3.3中給出了主成分分析(Principal Components Analysis, PCA)的實現,即cv::PCA類,類的宣告在include/opencv2/core.hpp檔案中,實現在modules/core/src/pca.cpp檔案中,其中:

(1)、cv::PCA::PCA:建構函式;

(2)、cv::PCA::operator():函式呼叫運算子;

(3)、cv::PCA::project:將輸入資料投影到PCA主成分空間;

(4)、cv::PCA::backProject:重建原始資料;

(5)、cv::PCA::write:將特徵值、特徵向量、均值寫入指定的檔案;

(6)、cv::PCA::read:從指定檔案讀入特徵值、特徵向量、均值;

(7)、cv::PCA::eigenvectors:協方差矩陣的特徵向量;

(8)、cv::PCA::eigenvalues:協方差矩陣的特徵值;

(9)、cv::PCA::mean:均值。

關於PCA的介紹可以參考: http://blog.csdn.net/fengbingchun/article/details/78977202 

以下是使用ORL Faces Database作為測試影像。關於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.cpp
	const 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 image
		cv::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 shape
		cv::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 file
	const std::string save_file{ "E:/GitCode/NN_Test/data/pca.xml" }; // .xml, .yaml, .jsons
	cv::FileStorage fs(save_file, cv::FileStorage::WRITE);
	pca.write(fs);
	fs.release();

	// read file
	const 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;
}

        結果影像如下:



GitHub: https://github.com/fengbingchun/NN_Test 

相關文章