两个程序,第一个用于训练,第二个用于决策,输入需为2值图像
//============================================================================
// Name : my_svm.cpp
// Author : guo
// Version : 0.0
// Copyright : njupt zynq
// Description : svm train
// date : 2013.5.26
//============================================================================
#include
#include
#include
#include
#include
using namespace std;
#define N1 50
#define N2 50
//float *wheight,float empty*,float * disper
/// float data[N1*3];
void feature(IplImage *img,float *data,int i)
{
IplImage *edge;
float total=(img->width)*(img->height);//图像总面积
// cvNamedWindow("image3",1);
// cvShowImage("image3",edge);
cout<<i<<" : 高宽比="<<data[i*3]<<" 占空比="<<data[i*3+1]<<" 分散度="<<data[i*3+2]<<endl;
cvReleaseImage(&img);
}
int main(int argc,char** argv)
{
IplImage * img;
float data[(N1+N2)*3];
// float data2[N2*3];
//svm变量
CvSVM svm = CvSVM ();
CvSVMParams param;
CvTermCriteria criteria;//停止迭代的标准
int res[N1+N2];
CvMat data_mat, res_mat;
char path[30]="/home/guo/pic_car/0000000.jpg";
for(int i=0;i
{
path[24]=i+'0';
path[23]=i0/10+'0';
path[22]=i00/100+'0';
path[21]=i000/1000+'0';
img=cvLoadImage(path,0);
feature(img,data,i);
res[i]=0;
}
//读取文件
path[14]='p';
path[15]='e';
path[16]='o';
for(int j=0;j
{
path[24]=j+'0';
path[23]=j0/10+'0';
path[22]=j00/100+'0';
path[21]=j000/1000+'0';
img=cvLoadImage(path,0);
feature(img,data,j+N1);
res[N1+j]=1;
}
//数据准备
cvInitMatHeader (&data_mat, (N1+N2), 3, CV_32FC1, data);//Initializes a pre-allocated matrix header.s行2列的cvMAT矩阵
cvInitMatHeader (&res_mat, (N1+N2), 1, CV_32SC1, res);//将各组数据所属分类拍成1列
// 学習参数的生成
criteria = cvTermCriteria (CV_TERMCRIT_EPS, 1000, FLT_EPSILON);//迭代终止条件
param = CvSVMParams (CvSVM::C_SVC, CvSVM::RBF, 10.0, 8.0, 1.0, 10.0, 0.5, 0.1, NULL, criteria);
// SVMの学習
svm.train (&data_mat, &res_mat, NULL, NULL, param);
svm.save ("svm_image.xml");
// cvWaitKey (0);
return 0;
}
//============================================================================
// Name : svm.cpp
// Author : guo
// Version : 0.0
// Copyright : njupt
// Description : svm predict
// date : 2013.5.27
//============================================================================
#include
#include
#include
#include
#include
using namespace std;
void getfeature(IplImage *img,float *data,int i)
{
IplImage *edge;
float total=(img->width)*(img->height);//图像总面积
//这里写你自己获取图像特征的代码,此程序框架采用三个特征
cout<<i<<" : 高宽比="<<data[i*3]<<" 占空比="<<data[i*3+1]<<" 分散度="<<data[i*3+2]<<endl;
cvReleaseImage(&img);
}
int main (int argc, char **argv)
{
CvSVM svm = CvSVM ();
IplImage *img;
svm.load("svm_image.xml");
float *a=new float[3];
img=cvLoadImage("/home/guo/pic_peo/0000034.jpg",0);
CvMat m;
getfeature(img,a,0);
cvInitMatHeader (&m, 1, 3, CV_32FC1, a);
float r = svm.predict (&m);
cout<<"分类"<<r<<endl;
cvWaitKey (0);
return 0;
}