您的位置:首页 > 编程语言 > C语言/C++

OpenCV视频分析与对象跟踪C++(四)视频中移动对象统计

2018-08-17 15:29 1421 查看
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
#include<opencv2/face.hpp>
#include<iostream>
#include<math.h>
#include <string>
#include<fstream>

using namespace cv::face;
using namespace cv;
using namespace std;
using namespace cv::xfeatures2d;

int main() {
VideoCapture capture;
capture.open("C:/Users/Administrator/Desktop/pic/3.avi");
Ptr<BackgroundSubtractor>pMOG2 = createBackgroundSubtractorMOG2();
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
vector<vector<Point>>contours;
vector<Vec4i> hireachy;
Mat frame, gray, mogmask;
while (capture.read(frame)) {
imshow("src", frame);
pMOG2->apply(frame, mogmask);
threshold(mogmask, mogmask, 100, 255, THRESH_BINARY);//二值化
morphologyEx(mogmask, mogmask, MORPH_OPEN, kernel);
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) contours;
count++;
rectangle(mogmask, selection, Scalar(0, 0, 255), 2);
sprintf_s(numText, "%d", count);
putText(mogmask, numText, Point(selection.x, selection.y), CV_FONT_NORMAL, FONT_HERSHEY_PLAIN, Scalar(255, 0, 0));
}
cout << "nini";
imshow("mogmask", mogmask);
}
capture.release();
waitKey(0);
}

结果:

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: