我需要将一组训练图像的OpenCV PCA对象(特征值、特征向量)存储到持久存储中,以便稍后重新加载以进行测试。我使用OpenCV 2.4特性XML/YAML文件存储将我的特征向量和特征值矩阵写入YAML文件。然而,当重新加载文件并将相同的输入图像投影到重新加载的PCA空间中时,我不会得到0?我相信我在某种程度上失去了准确性,但似乎不明白为什么?我的代码基于@Link在他的解决方案"在opencv中保存pca对象"中给出的答案
int numPrincipalComponents = db.size()-1;
Mat output1, output2;
PCA pca(matrix, global_mean_vec, CV_PCA_DATA_AS_ROW, numPrincipalComponents);
pca.project(matrix.row(0), output1); //Project first image into orig. PCA
Mat eigenvalues = pca.eigenvalues.clone();
Mat eigenvectors = pca.eigenvectors.clone();
//Write matrices to pca_happy.yml
FileStorage fs("./Train/FileStore/pca_happy.yml", FileStorage::WRITE);
fs << "Eigenvalues" << eigenvalues;
fs << "Eigenvector" << eigenvectors;
fs.release();
//Load matrices from pca_happy.yml
FileStorage fs1("./Train/FileStore/pca_happy.yml", FileStorage::READ);
Mat loadeigenvectors, loadeigenvalues;
fs1["Eigenvalues"] >> eigenvalues;
fs1["Eigenvector"] >> eigenvectors;
fs1.release();
PCA pca2;
pca2.mean = global_mean_vec;
pca2.eigenvalues = loadeigenvalues;
pca2.eigenvectors = loadeigenvectors;
pca2.project(matrix.row(0), output2);
Mat diff;
absdiff(output1, output2, diff);
cout<<sum(diff)[0]<<endl;
然而,差异是88.4,应该是0,因为我投影的是完全相同的图像。我需要存储特征向量矩阵的每一行吗?非常感谢您的任何建议!
我在设置特征值、特征向量和均值或pca2时犯了一个非常愚蠢的错误!
PCA pca2;
pca2.mean = global_mean_vec;
pca2.eigenvalues = loadeigenvalues;
pca2.eigenvectors = loadeigenvectors;
应为:
PCA pca2;
pca2.mean = global_mean_vec.clone();
pca2.eigenvalues = loadeigenvalues.clone();
pca2.eigenvectors = loadeigenvectors.clone();
希望这也能帮助其他人!
您是否正确计算了平均向量?我只做了两个小修改:(用我自己的matrix
)
PCA pca(matrix, Mat(), CV_PCA_DATA_AS_ROW, numPrincipalComponents);//compute mean automatically
pca2.mean = pca.mean;
并且CCD_ 2为零。
我想,PCA2应该是:
Mat eigenvalues1,eigenvectors1;
FileStorage fs1("fileName.yml", FileStorage::READ);
//Mat loadeigenvectors, loadeigenvalues;
fs1["Eigenvalues"] >> eigenvalues1;
fs1["Eigenvector"] >> eigenvectors1;
fs1.release();
PCA pca2;
pca2.mean = pca.mean;
pca2.eigenvalues = eigenvalues1;
pca2.eigenvectors = eigenvectors1;