Saving pca object in opencv

流过昼夜 提交于 2019-12-11 04:24:33

问题


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.

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?


回答1:


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.

Here is some example code:

#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



回答2:


You may try this.

void save(const string &file_name,cv::PCA pca_)
{
    FileStorage fs(file_name,FileStorage::WRITE);
    fs << "mean" << pca_.mean;
    fs << "e_vectors" << pca_.eigenvectors;
    fs << "e_values" << pca_.eigenvalues;
    fs.release();
}

int load(const string &file_name,cv::PCA pca_)
{
    FileStorage fs(file_name,FileStorage::READ);
    fs["mean"] >> pca_.mean ;
    fs["e_vectors"] >> pca_.eigenvectors ;
    fs["e_values"] >> pca_.eigenvalues ;
    fs.release();

}

Here is the source.



来源:https://stackoverflow.com/questions/8066370/saving-pca-object-in-opencv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!