【机器学习】最简单易懂的行人检测功能实现
生活随笔
收集整理的這篇文章主要介紹了
【机器学习】最简单易懂的行人检测功能实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
加載訓(xùn)練好的行人分類器,實(shí)現(xiàn)行人檢測功能。
代碼中用到的訓(xùn)練好的行人分類器"pedestrianDetect.xml"下載路徑:https://download.csdn.net/download/lyq_12/10742144
一、效果如下:
1、輸入原圖
2、輸出結(jié)果
二、代碼實(shí)現(xiàn)如下:
#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的決策函數(shù)中的alpha數(shù)組double * get_alpha_vector(){return this->decision_func->alpha;}//獲得SVM的決策函數(shù)中的rho參數(shù),即偏移量float get_rho(){return this->decision_func->rho;} };int main() {MySVM svm; //SVM分類器svm.load("pedestrianDetect.xml"); //加載訓(xùn)練好的行人分類器int DescriptorDim = svm.get_var_count(); //特征向量的維數(shù),即HOG描述子的維數(shù)int supportVectorNum = svm.get_support_vector_count(); //支持向量的個(gè)數(shù)//cout<<"支持向量個(gè)數(shù):"<<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<<"檢測子維數(shù):"<<myDetector.size()<<endl;HOGDescriptor myHOG;myHOG.setSVMDetector(myDetector); //設(shè)置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; //保存檢測結(jié)果Mat dstImg = srcImg.clone();myHOG.detectMultiScale(dstImg, detectRects, 0, Size(8,8), Size(32,32), 1.05, 2); //對(duì)輸入圖片進(jìn)行行人檢測//對(duì)detectRects進(jìn)行非極大值抑制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之后的行人檢測結(jié)果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.csdn.net/masibuaa/article/details/16105073?utm_source=tuicool&utm_medium=referral
總結(jié)
以上是生活随笔為你收集整理的【机器学习】最简单易懂的行人检测功能实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【机器学习】基于opencv实现目标检测
- 下一篇: Python简介、安装、更新、基本语法及