[opencv]利用每帧图像减去第一帧无人的图像来检测视频人数

来源:互联网 发布:腾讯数据分析师面经 编辑:程序博客网 时间:2024/05/16 15:18

该博客记录的是利用读取视频的每帧图像(从第二帧开始)减去第一帧无人的图像,获得前景图像,然后将前景的块利用方框框出,通过统计块数来计算人数。这个想法还是很粗糙的,但可以作为一种思路,故本博客转载了这篇文章。

(转自http://blog.csdn.net/u013812682/article/details/51980765)

步骤: 
1.视频图像灰度化img 
2,选取第一帧图像first_img,视频每帧和第一帧相减,得到src 
3,对src图片进行 阈值,滤波处理 
4,查找处理好图片的边界findContours; 
5,对边界区域进行统计,满足条件的进行计数

代码实现:

#include <opencv2/core/core.hpp>  #include <opencv2/highgui/highgui.hpp>  #include <opencv2/imgproc/imgproc.hpp>  #include <opencv2/objdetect/objdetect.hpp> using namespace std;using namespace cv;int main() {Mat img, src, frame, frame_gray, first_frame, threshold_src, gass_src, dilate_src;VideoCapture cap("E:\\data\\hog_svm\\pedestrian.avi");cap >> first_frame;cvtColor(first_frame, first_frame, CV_BGR2GRAY);int num = 0;int zz = 1;while (1) {cap >> frame;if (frame.empty())break;vector<Vec4i> hierarchy;vector<vector<Point> > contour;cvtColor(frame, frame_gray, CV_BGR2GRAY);absdiff(frame_gray, first_frame, src);threshold(src, threshold_src, 50, 255, THRESH_BINARY);GaussianBlur(threshold_src, gass_src, Size(5, 5), 1.5);//blur(threshold_src, gass_src, Size(5, 5));//  medianBlur(threshold_src, gass_src,1);dilate(gass_src, dilate_src, Mat());findContours(dilate_src, contour, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);//drawContours(frame, contour, -1, Scalar(0, 0, 255),2);for (int i = 0; i < contour.size();i++) {Rect bndRect = boundingRect(contour.at(i));Point p1, p2;p1.x = bndRect.x;p1.y = bndRect.y;p2.x = bndRect.x + bndRect.width;p2.y = bndRect.y + bndRect.height;if (bndRect.area()>3000) {rectangle(frame, p1, p2, Scalar(0, 0, 255));num++;}}string font = "Current number:";putText(frame, font + to_string(num), Point(100, 50), FONT_HERSHEY_COMPLEX_SMALL, 1, Scalar(0, 0, 255));//  cout << "人数统计:" << num<<endl;num = 0;imshow("dilate_src", dilate_src);imshow("frame", frame);imshow("first_frame", first_frame);waitKey(20);}return 0;}
下面讲一下配置环境的问题:我用的是VS2015+opencv2.4.13,刚开始运行上述代码时,总是报错,逐行运行后发现是findContours的问题,进行了如下的配置:

1.在项目属性->配置属性->平台工具集中选择Visual Studio 2013(v12)选项 

2.在项目属性->C/C++->代码生成->运行库中选择多线程调试DLL(/MDd)

之后,代码便可正常运行。