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

本文介绍了一种基于视频的人数统计方法,通过对视频帧与背景帧的差分处理,结合图像处理技术,识别并统计视频中的人数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

(转自http://blog.youkuaiyun.com/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)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值