在opencv中保存pca对象 [英] Saving pca object in opencv

查看:192
本文介绍了在opencv中保存pca对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个人脸识别项目,其中我们使用PCA来减少图像的特征向量大小.问题是,在训练过程中,我通过合并所有训练图像来创建PCA对象.现在,在测试过程中,我需要之前获得的PCA对象.

I'm working on a face recognition project in which we are using PCA to reduce feature vector size of an image. The trouble is, during training, I create the PCA object by incorporating all the training images. Now, during testing, I need the PCA object obtained earlier.

我似乎无法弄清楚如何将PCA对象写入文件,以便可以在测试期间使用它.一种选择是,将其特征向量写入文件.但是编写对象本身会方便得多.有办法吗?

I cannot seem to figure out how to write the PCA object to a file, so that I can use it during testing. One alternative is that I write it's eigenvectors to the file. But it would be so much more convenient to write the object itself. Is there a way to do this?

推荐答案

据我所知,没有将PCA对象保存到文件的通用方法.您将需要将特征向量,特征值和均值保存到文件中,然后在加载后将它们放入新的PCA中.您必须记住使用不会丢失精度的格式,尤其是对于平均值而言.

As far as I know, there is no generic way of saving PCA objects to a file. You will need to save eigenvectors, eigenvalues and mean to a file, and then put them into a new PCA after loading. You have to remember to use a format that doesn't lose precision, especially for mean.

这是一些示例代码:

#include "opencv2/core/core.hpp"
#include <iostream>

...

cv::PCA pca1;
cv::PCA pca2;

cv::Mat eigenval,eigenvec,mean;
cv::Mat inputData;
cv::Mat outputData1,outputData2;

//input data has been populated with data to be used
pca1(inputData,Mat()/*dont have previously computed mean*/,
CV_PCA_DATA_AS_ROW /*depends of your data layout*/);//pca is computed
pca1.project(inputData,outputData1);

//here is how to extract matrices from pca
mean=pca1.mean.clone();
eigenval=pca1.eigenvalues.clone();
eigenvec=pca1.eigenvectors.clone();

//here You can save mean,eigenval and eigenvec matrices

//and here is how to use them to make another pca
pca2.eigenvalues=eigenval;
pca2.eigenvectors=eigenvec;
pca2.mean=mean;

pca2.project(inputData,outputData2);

cv::Mat diff;//here some proof that it works
cv::absdiff(outputData1,outputData2,diff);

std::cerr<<sum(diff)[0]<<std::endl; //assuming Youre using one channel data, there
                                    //is data only in first cell of the returned scalar

// if zero was printed, both output data matrices are identical

这篇关于在opencv中保存pca对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆