【机器学习】最简单易懂的行人检测功能实现
加载训练好的行人分类器,实现行人检测功能。
代码中用到的训练好的行人分类器"pedestrianDetect.xml"下载路径:https://download.****.net/download/lyq_12/10742144
一、效果如下:
1、输入原图
2、输出结果
二、代码实现如下:
#include <iostream>
#include <fstream>
#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;
class MySVM : public CvSVM
{
public:
//获得SVM的决策函数中的alpha数组
double * get_alpha_vector()
{
return this->decision_func->alpha;
}
//获得SVM的决策函数中的rho参数,即偏移量
float get_rho()
{
return this->decision_func->rho;
}
};
int main()
{
MySVM svm; //SVM分类器
svm.load("pedestrianDetect.xml"); //加载训练好的行人分类器
int DescriptorDim = svm.get_var_count(); //特征向量的维数,即HOG描述子的维数
int supportVectorNum = svm.get_support_vector_count(); //支持向量的个数
//cout<<"支持向量个数:"<<supportVectorNum<<endl;
Mat alphaMat = Mat::zeros(1, supportVectorNum, CV_32FC1);
Mat supportVectorMat = Mat::zeros(supportVectorNum, DescriptorDim, CV_32FC1);
Mat resultMat = Mat::zeros(1, DescriptorDim, CV_32FC1);
for(int i=0; i<supportVectorNum; i++)
{
const float * pSVData = svm.get_support_vector(i);
for(int j=0; j<DescriptorDim; j++)
{
supportVectorMat.at<float>(i,j) = pSVData[j];
}
}
double * pAlphaData = svm.get_alpha_vector();
for(int i=0; i<supportVectorNum; i++)
{
alphaMat.at<float>(0,i) = pAlphaData[i];
}
resultMat = -1 * alphaMat * supportVectorMat;
vector<float> myDetector;
for(int i=0; i<DescriptorDim; i++)
{
myDetector.push_back(resultMat.at<float>(0,i));
}
myDetector.push_back(svm.get_rho());
//cout<<"检测子维数:"<<myDetector.size()<<endl;
HOGDescriptor myHOG;
myHOG.setSVMDetector(myDetector); //设置HOGDescriptor的检测子
Mat srcImg = imread("..\\srcImg.jpg");
if (srcImg.empty())
{
cout<<"Failed to read image.";
return -1;
}
//resize(srcImg, srcImg, Size(288,216));
imshow("srcImg", srcImg);
vector<Rect> detectRects, detectRectsAfterNMS; //保存检测结果
Mat dstImg = srcImg.clone();
myHOG.detectMultiScale(dstImg, detectRects, 0, Size(8,8), Size(32,32), 1.05, 2); //对输入图片进行行人检测
//对detectRects进行非极大值抑制
for(int i=0; i < detectRects.size(); i++)
{
Rect r = detectRects[i];
int j=0;
for(; j < detectRects.size(); j++)
{
if(j != i && (r & detectRects[j]) == r)
{
break;
}
}
if( j == detectRects.size())
{
detectRectsAfterNMS.push_back(r);
}
}
//画出NMS之后的行人检测结果
for(int i=0; i<detectRectsAfterNMS.size(); i++)
{
Rect r = detectRectsAfterNMS[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(dstImg, r.tl(), r.br(), Scalar(0,255,0), 3);
}
imshow("dstImg",dstImg);
waitKey(0);
}
参考资料:https://blog.****.net/masibuaa/article/details/16105073?utm_source=tuicool&utm_medium=referral