行人检测是视觉领域很热也很有用的一个主题,特别是在无人驾驶中,行人检测的重要性不言而喻。
在之前进行了人脸检测之后,行人检测就显得简单多了。过程大致与人脸检测一样,都是先加载分类器,然后进行多尺度检测。就偷懒不再赘述。感兴趣的可以看人脸检测的这一篇文章:OpenCV实践之路——人脸检测(C++/Python)
图片检测
#include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include<opencv2/objdetect.hpp> #include<iostream> using namespace std; using namespace cv; int main(int argc, char **argv) { Mat img; vector<Rect> found; /*if (argc != 2) { printf("can't find picture\n"); return -1; }*/ img = imread("F:\\1.jpg",1); HOGDescriptor defaultHog; defaultHog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector()); //默认模型,这个模型数据在OpenCV源码中是一堆常量数字, //这些数字是通过原作者提供的行人样本INRIAPerson.tar训练得到的 defaultHog.detectMultiScale(img, found); // 画出长方形,框出人 for (int i = 0; i < found.size(); i++) { Rect r = found[i]; rectangle(img, r.tl(), r.br(), Scalar(0, 0, 255), 3); } namedWindow("Detect pedestrain", WINDOW_AUTOSIZE); imshow("Detect pedestrain", img); char c = waitKey(0); return 0; }结果:
视频检测代码
#include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include<opencv2/objdetect.hpp> #include<iostream> using namespace std; using namespace cv; int main(int argc, char **argv) { Mat img; VideoCapture cap; vector<Rect> found; if(argc != 2) { printf("can't find picture\n"); return -1; } cap.open(argv[1]); //img = cv::imread(argv[1]); while(1) { cap >> img; if (img.empty()) break; HOGDescriptor defaultHog; defaultHog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector()); //默认模型,这个模型数据在OpenCV源码中是一堆常量数字, //这些数字是通过原作者提供的行人样本INRIAPerson.tar训练得到的 defaultHog.detectMultiScale(img, found); // 画出长方形,框出人 for (int i = 0; i < found.size(); i++) { Rect r = found[i]; rectangle(img, r.tl(), r.br(), Scalar(0, 0, 255), 3); } namedWindow("Detect pedestrain", WINDOW_AUTOSIZE); imshow("Detect pedestrain", img); char c = waitKey(33); if (c == 27) break; } return 0; }