(1)第一个工程是用来训练分类器和检测正样本检测率的
// PeopleDetectHog.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <opencv2/opencv.hpp>
#include <iostream>
#include <ctype.h>
#include "cv.h"
#include "highgui.h"
#include "stdafx.h"
#include <ml.h>
#include <fstream>
#include <math.h>
#include <string>
#include <vector>
#include <stdio.h>
using namespace cv;
using namespace std;
class Mysvm: public CvSVM
{
public:
int get_alpha_count()
{
return this->sv_total;
}
int get_sv_dim()
{
return this->var_all;
}
int get_sv_count()
{
return this->decision_func->sv_count;
}
double* get_alpha()
{
return this->decision_func->alpha;
}
float** get_sv()
{
return this->sv;
}
float get_rho()
{
return this->decision_func->rho;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int positiveSampleCount = 2416; //正样本数
int negativeSampleCount = 18185; //负样本数
int totalSampleCount = positiveSampleCount + negativeSampleCount;
FILE* fp = fopen("PeopleDetectResult_INRIA2416.txt","w");
if(fp==NULL)
{
int n = GetLastError();
exit(1);
}
CvMat *sampleFeaturesMat = cvCreateMat(totalSampleCount , 3780, CV_32FC1); //这里第二个参数1764是hog维数,即矩阵的列是由下面的featureVec的大小决定的,可以由descriptors.size()得到,
//64*64的训练样本,该矩阵将是totalSample*1764;若是64*128,则对应3780维
cvSetZero(sampleFeaturesMat);
CvMat *sampleLabelMat = cvCreateMat(totalSampleCount, 1, CV_32FC1); //存储样本图片类型 ,正样本1,负样本-1
cvSetZero(sampleLabelMat);
// fprintf(fp, "%s\n","Hog描述算子:\n SVM参数:");
cout<<"waiting......"<<endl;
cout<<"start to training positive samples..."<<endl;
string buf;
char line[512];
vector<string> img_path;//输入文件名变量
ifstream svm_data( "D:\\program\\matlabprojects\\PeopleSample\\pos1\\train_list.txt");
while (svm_data)
{
if (getline( svm_data, buf ))
{
img_path.push_back( buf );
}
}
svm_data.close();//关闭文件
IplImage* src;
IplImage* img=cvCreateImage(cvSize(64,128),8,3);//需要分析的图片,这里默认设定图片是64*128大小,所以上面定义了3780,如果要更改图片大小,可以先用debug查看一下descriptors是多少,然后设定好再运行
long t1 = GetTickCount();
for(int i=0; i<positiveSampleCount; i++)
{
src=cvLoadImage(img_path[i].c_str(),1);
cvResize(src,img); //读取正样本图片
if( img == NULL )
{
cout<<" can not load the image:"<<img_path[i].c_str()<<endl;
continue;
}
cout<<" processing "<<img_path[i].c_str()<<endl;
cv::HOGDescriptor hog(cv::Size(64,128), cv::Size(16,16), cv::Size(8,8),cv::Size(8,8), 9);
//HOG的描述函数。如果是64*128的训练样本,需要把第一个参数改为cv::Size(64,128)
vector<float> featureVec;
hog.compute(img, featureVec, cv::Size(8,8)); //featureVec--存储每个样本图片的HOG特征向量
for (int j=0; j<featureVec.size(); j++)
{
CV_MAT_ELEM( *sampleFeaturesMat, float, i, j ) = featureVec[j];
}
s