早在一年前,就玩过PCA了,那个时候使用PCA做了一个人脸识别的作业。所以对于PCA的理论这里不再介绍了,直接上一个基于Opencv的PCA吧。
在Opencv中,有一个PCA类,如下:
class CV_EXPORTS PCA
{
public:
//! default constructor
PCA();
//! the constructor that performs PCA
PCA(InputArray data, InputArray mean, int flags, int maxComponents=0);
PCA(InputArray data, InputArray mean, int flags, double retainedVariance);
//! operator that performs PCA. The previously stored data, if any, is released
PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents=0);
PCA& computeVar(InputArray data, InputArray mean, int flags, double retainedVariance);
//! projects vector from the original space to the principal components subspace
Mat project(InputArray vec) const;
//! projects vector from the original space to the principal components subspace
void project(InputArray vec, OutputArray result) const;
//! reconstructs the original vector from the projection
Mat backProject(InputArray vec) const;
//! reconstructs the original vector from the projection
void backProject(InputArray vec, OutputArray result) const;
Mat eigenvectors; //!< eigenvectors of the covariation matrix
Mat eigenvalues; //!< eigenvalues of the covariation matrix
Mat mean; //!< mean value subtracted before the projection and added after the back projection
};
同时,在opencv2.4.6安装目录D:\opencv\opencv246\samples\cpp下有一个PCA的实例,下面我们直接给出:
// PCA.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
/*
* pca.cpp
*
* Author:
* Kevin Hughes <kevinhughes27[at]gmail[dot]com>
*
* Special Thanks to:
* Philipp Wagner <bytefish[at]gmx[dot]de>
*
* This program demonstrates how to use OpenCV PCA with a
* specified amount of variance to retain. The effect
* is illustrated further by using a trackbar to
* change the value for retained varaince.
*
* The program takes as input a text file with each line
* begin the full path to an image. PCA will be performed
* on this list of images. The author recommends using
* the first 15 faces of the AT&T face data set:
* http://www.cl.cam.ac.uk/research/dtg/attarchive/facedatabase.html
*
* so for example your input text file would look like this:
*
* <path_to_at&t_faces>/orl_faces/s1/1.pgm
* <path_to_at&t_faces>/orl_faces/s2/1.pgm
* <path_to_at&t_faces>/orl_faces/s3/1.pgm
* <path_to_at&t_faces>/orl_faces/s4/1.pgm
* <path_to_at&t_faces>/orl_faces/s5/1.pgm
* <path_to_at&t_faces>/orl_faces/s6/1.pgm
* <path_to_at&t_faces>/orl_faces/s7/1.pgm
* <path_to_at&t_faces>/orl_faces/s8/1.pgm
* <path_to_at&t