opencv移动物体检测(自动更新背景)

#include "pch.h"
#include 
#include 
#include 

using namespace cv;
using namespace std;

int main()
{
	VideoCapture capture(0);//capture("D:\\项目资料\\车载AR\\夜视录屏\\20190103_200614.mp4");
	if (!capture.isOpened())//如果视频不能正常打开则返回
		return 0;

	Ptr pMOG2 = createBackgroundSubtractorMOG2();
	Mat kernel = getStructuringElement(MORPH_RECT,Size(3, 3), Point(-1, -1));

	vector> contours;
	vector hireachy;

	Mat frame, gray, mogMask;

	while (capture.read(frame))
	{
		imshow("src6-16", frame);
		pMOG2->apply(frame, mogMask, 0.8f);
		
		threshold(mogMask, mogMask, 100, 255, THRESH_BINARY);
		
		morphologyEx(mogMask, mogMask, MORPH_OPEN, kernel, Point(-1, -1));
		findContours(mogMask, contours, hireachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
		cvtColor(mogMask, mogMask, COLOR_GRAY2BGR);
		
		int count = 0;
		char numText[8];
		for (size_t t = 0; t < contours.size(); t++)
		{
			double area = contourArea(contours[t]);
			if (area < 100)
				continue;

			Rect selection = boundingRect(contours[t]);
			if (selection.width < 10 || selection.height < 10)
				continue;
			count++;
			rectangle(mogMask, selection, Scalar(0, 0, 255), 2, 8);

			sprintf_s(numText, "%d", count);
			putText(mogMask, numText, Point(selection.x, selection.y), CV_FONT_NORMAL, FONT_HERSHEY_PLAIN, Scalar(255, 0, 0), 1, 8);
		}

		imshow("num6-16", mogMask);
		if (waitKey(50) == 27)
			break;

	}

	capture.release();//释放资源
	waitKey(0);
	return 0;
}

opencv移动物体检测(自动更新背景)_第1张图片

 

 

 

你可能感兴趣的:(C++,opencv,移动检测)