OpenCV操作PCA+SVM代码

// 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;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值