2011-11-09 49 views
1

我正在使用PCA來減少圖像的特徵向量大小的人臉識別項目。麻煩的是,在訓練期間,我通過合併所有訓練圖像來創建PCA對象。現在,在測試過程中,我需要先前獲得的PCA對象。在opencv中保存pca對象

我似乎無法弄清楚如何將PCA對象寫入文件,以便在測試過程中使用它。另一種選擇是我將它寫入文件的特徵向量。但是寫對象本身會更方便。有沒有辦法做到這一點?

+0

查看您的其他問題並接受一些答案! – karlphillip

回答

11

據我所知,沒有將PCA對象保存到文件的通用方法。您需要將特徵向量,特徵值和均值保存到文件中,然後在加載後將它們放入新的PCA中。你必須記住使用不會失去精度的格式,特別是對於平均值。

下面是一些示例代碼:

#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 
+0

您可以提到從特徵向量和特徵值生成pca對象的方法嗎?我似乎只能在文檔中看到一種方式:傳遞原始數據和maxcomponents來創建一個pca pbject – Karan

0

你可以試試這個。

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是源。