// pca_svm.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include "cvaux.h"
#include "ml.h"
using namespace cv;
using namespace std;
#pragma comment(lib, "cv.lib")
#pragma comment(lib, "cvaux.lib")
#pragma comment(lib, "cxcore.lib")
#pragma comment(lib, "highgui.lib")
int _tmain(int argc, _TCHAR* argv[])
{
vector<Mat> images; //This variable will be loaded with a set of images to perform PCA on.
char filename[100];
int imageFaceNum = 100;
int imageNonFaceNum = 25;
int num = 0;
Mat src;
Mat values(imageFaceNum+imageNonFaceNum, 1, CV_32SC1); //Values are the corresponding values to each of my images.
for(int i=1; i<=imageFaceNum; i++) {
sprintf(filename,"E:/图片数据库/MIT人脸库/train_face/%d.bmp",i);
values.at<int>(i-1,0) = 1;
src=cvLoadImage(filename,0);
images.push_back(src);
num++;
}
for(int i=1; i<=imageNonFaceNum; i++) {
sprintf(filename,"E:/图片数据库/MIT人脸库/train_nonface/%d.bmp",i);
values.at<int>(num-1,0) = 0;
src=cvLoadImage(filename,0);
images.push_back(src);
num++;
}
int nEigens = images.size() - 1; //Number of Eigen Vectors.
//Load the images into a Matrix
Mat desc_mat(images.size(), images[0].rows * images[0].cols, CV_8UC1);
for (int i=0; i<images.size(); i++) {
desc_mat.row(i) = images[i].reshape(1, 1) + 0;
}
Mat average;
PCA pca(desc_mat, average, CV_PCA_DATA_AS_ROW, nEigens);
Mat data(desc_mat.rows, nEigens, CV_32FC1); //This Mat will contain all the Eigenfaces that will be used later with SVM for detection
//Project the images onto the PCA subspace
for(int i=0; i<images.size(); i++) {
Mat projectedMat(1, nEigens, CV_32FC1);
pca.project(desc_mat.row(i), projectedMat);
data.row(i) = projectedMat.row(0) + 0;
}
CvMat d1 = (CvMat)data;
CvMat d2 = (CvMat)values;
CvSVM svm = CvSVM();
CvSVMParams param;
CvTermCriteria criteria;
criteria = cvTermCriteria( CV_TERMCRIT_EPS, 1000, FLT_EPSILON );
param = CvSVMParams( CvSVM::C_SVC, CvSVM::RBF, 10.0, 0.09, 1.0, 10.0, 0.5, 1.0, NULL, criteria );
//☆☆☆☆☆☆☆☆☆(5)SVM学习☆☆☆☆☆☆☆☆☆☆☆☆
svm.train( &d1, &d2, NULL, NULL, param );
svm.save("svmdata.xml");
//
PCA pca();
Mat cs;
Mat cs1(1,400,CV_32FC1);
for(int i=1; i<=100; i++) {
sprintf(filename,"E:/图片数据库/MIT人脸库/train_face/%d.bmp",i);
src=cvLoadImage(filename,0);
cs = src.reshape(1, 1) + 0;
Mat projectedMat(1, nEigens, CV_32FC1);
pca.project(cs, projectedMat);
CvMat d3 = (CvMat)projectedMat;
int ret = svm.predict(&d3);
cout<<ret<<endl;
}
return 0;
}
OpenCV操作PCA+SVM代码
最新推荐文章于 2023-02-18 10:04:20 发布