利用SVM训练一个分类器,用训练好的分类器对测试集里的数据进行检测。
这里是数据下载地址:INRIA行人数据集
点击页面下方的蓝色here即可下载。
下载完成之后,解压缩(为方便操作,建议放于项目目录下或者是根目录下,我这里是放在了D盘下面),进入文件夹,打开Train,有neg负样本,pos正样本。负样本的尺寸是437X292的,所以需要先处理一下,才能够进行训练。下面是处理代码(这里默认你已经配置好了opencv环境)。
#include <iostream>
#include <fstream>
#include <stdlib.h> //srand()和rand()函数
#include <time.h> //time()函数
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/ml/ml.hpp>
using namespace std;
using namespace cv;
int CropImageCount = 0; //裁剪出来的负样本图片个数
int main()
{
Mat src;
string ImgName;
char saveName[256];//裁剪出来的负样本图片文件名
ifstream fin("D:/INRIAPerson/Train/neg.lst");//打开原始负样本图片文件列表
//一行一行读取文件列表
while(getline(fin,ImgName))
{
cout<<"处理:"<<ImgName<<endl;
ImgName = "D:/INRIAPerson" + ImgName;
src = imread(ImgName,1);//读取图片
//cout<<"宽:"<<src.cols<<",高:"<<src.rows<<endl;
//图片大小应该能能至少包含一个64*128的窗口
if(src.cols >= 64 && src.rows >= 128)
{
srand(time(NULL));//设置随机数种子 time(NULL)表示当前系统时间
//从每张图片中随机采样10个64*128大小的不包含人的负样本
for(int i=0; i<10; i++)
{
int x = ( rand() % (src.cols-64) ); //左上角x坐标
int y = ( rand() % (src.rows-128) ); //左上角y坐标
//cout<<x<<","<<y<<endl;
Mat imgROI = src(Rect(x,y,64,128));
sprintf(saveName,"D:/INRIAPerson/negphoto/noperson%06d.jpg",++CropImageCount);//生成裁剪出的负样本图片的文件名
imwrite(saveName, imgROI);//保存文件
}
}
}
system("pause");
}
大概经过几十秒就能生成12000多张负样本的图片了。
接下来就是训练分类器以及对测试样本进行测试了。
#include "opencv2/core/core.hpp"
#include "opencv2/objdetect.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/video/video.hpp"
#include "opencv2/ml.hpp"
#include "opencv2/opencv.hpp"
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgcodecs.hpp>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <math.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <cstdlib>
using namespace std;
using namespace cv;
using namespace cv::ml;
//函数声明
void get_svm_detector(const Ptr< SVM > & svm, vector< float > & hog_detector);
void convert_to_ml(const std::vector< Mat > & train_samples, Mat& trainData);
void load_images(const String & dirname, vector< Mat > & img_lst, bool showIma