技术栈

主页 > 其他 >

OpenCV3.3中主成分分析(Principal Components Analysis, PCA)接口简介及使用

技术栈 - 中国领先的IT技术门户

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
", 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);

	// Demonstration of the effect of retainedVariance on the first image
	cv::Mat point = pca.project(data.row(0)); // 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[0].channels(), images[0].rows); // reshape from a row vector into image shape
	cv::normalize(reconstruction, reconstruction, 0, 255, cv::NORM_MINMAX, CV_8UC1);

	// 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

责任编辑:admin  二维码分享:
本文标签:
点击我更换图片

评论列表