对运动物体的侦测以及在摄像头下的运动物体数量实时显示以及记录
通过背景建模进行前景的提取并对移动物体进行侦测
当前opencv版本4.3
//移动物体的侦测与统计
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
VideoCapture capture;
capture.open("xxxxxxxxxxxxxx");
if (!capture.isOpened()) {
printf("could not load video data...\n");
return -1;
}
namedWindow("input video");
namedWindow("motion objects");
// 初始BS模型 背景建模取背景或前景图
//Ptr<BackgroundSubtractor> pMOG2 = createBackgroundSubtractorMOG2();
//Ptr<BackgroundSubtractorMOG2> pMOG2 = createBackgroundSubtractorMOG2();
Ptr<BackgroundSubtractorKNN> pMOG2 = createBackgroundSubtractorKNN();
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1));
vector<vector<Point>> contours;
//vector<Vec4i> hireachy;
int count = 0;
int maxcount = 0;
int mincount = 100;
Mat frame, gray, mogMask, backImage;
while (capture.read(frame)) {
imshow("input video", frame);
pMOG2->apply(frame, mogMask); //背景建模取前景图
pMOG2->getBackgroundImage(backImage); //提取背景图,基本没什么用
GaussianBlur(mogMask, mogMask, Size(3, 3), 0);
threshold(mogMask, mogMask, 100, 255, THRESH_BINARY); //THRESH_OTSU 表示取自适应中最合适的阈值范围
//threshold(mogMask, mogMask, 100, 255, THRESH_BINARY | THRESH_OTSU);
morphologyEx(mogMask, mogMask, MORPH_OPEN, kernel, Point(-1, -1));
imshow("mogMask", mogMask);
imshow("backImage", backImage);
findContours(mogMask, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point(0, 0));
count = 0;
char numText[8];
for (size_t t = 0; t < contours.size(); t++) {
double area = contourArea(contours[t]);
if (area < 40) continue;
Rect selection = boundingRect(contours[t]);
if (selection.width < 5 || selection.height < 8) continue;
count++;
rectangle(frame, selection, Scalar(0, 0, 255), 2, 8);
sprintf(numText, "%d", count);
putText(frame, numText, Point(selection.x, selection.y), FONT_HERSHEY_SIMPLEX, FONT_HERSHEY_PLAIN, Scalar(255, 0, 0), 1, 8);
if (count > maxcount)
{
maxcount = count;
cout << "maxcount=" << maxcount << endl;
}
if (count < mincount)
{
mincount = count;
cout << "mincount=" << mincount << endl;
}
}
resize(frame, frame, Size(frame.cols / 2, frame.rows / 2), 0, 0, INTER_LINEAR_EXACT);
imshow("motion objects", frame);
char c = waitKey(50);
if (c == 27) { // ESC
break;
}
}
capture.release();
waitKey(0);
return 0;
}