思想:
使用createBackgroundSubtractorMOG2()使用运动物体背景分割
使用findContours()查找轮廓并画出
实现一定感官上的跟踪功能
代码如下:
#include<opencv2\opencv.hpp>
#include<iostream>
#include<sstream>
using namespace cv;
using namespace std;
Mat frame;
Mat fgMaskMOG2;
Mat maskContour;
Ptr<BackgroundSubtractor> pMOG2;
char keyboard;
int FRAME = 0;
string b = ".jpg";
void processVideo(char* videoFilename);
void drawRect(Mat MOG2, Mat frame);
int main()
{
namedWindow("Frame");
namedWindow("移动目标跟踪");
namedWindow("FG Mask MOG 2");
pMOG2 = createBackgroundSubtractorMOG2();
char* videoFilename = "vtest.avi";
processVideo(videoFilename);
destroyAllWindows();
return 0;
}
void processVideo(char* videoFilename)
{
VideoCapture capture(videoFilename);
keyboard = 0;
while (keyboard != 'q' && keyboard != 27)
{
if (!capture.read(frame)) {
cerr << "Unable to read next frame." << endl;
cerr << "Exiting..." << endl;
exit(EXIT_FAILURE);
}
pMOG2->apply(frame, fgMaskMOG2);
stringstream ss;
rectangle(frame, cv::Point(10, 2), cv::Point(100, 20),
cv::Scalar(255, 255, 255), -1);
ss << capture.get(CAP_PROP_POS_FRAMES);
string frameNumberString = ss.str();
putText(frame, frameNumberString.c_str(), cv::Point(15, 15),
FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
imshow("Frame", frame);
imshow("FG Mask MOG 2", fgMaskMOG2);
drawRect(fgMaskMOG2, frame);
keyboard = (char)waitKey(30);
}
capture.release();
}
void drawRect(Mat MOG2, Mat frame)
{
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(MOG2, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point());
Mat imageContours = Mat::zeros(MOG2.size(), CV_8UC1);
Mat Contours = Mat::zeros(MOG2.size(), CV_8UC1);
vector<vector<Point>> approxPoint(contours.size());
for (int i = 0;i < contours.size();i++)
{
if (contourArea(contours[i])>500) {
RotatedRect rectPoint = minAreaRect(contours[i]);
//cout << contourArea(contours[i]) << endl;
Point2f fourPoint2f[4];
rectPoint.points(fourPoint2f);
for (int i = 0;i < 3;i++)
{
line(frame, fourPoint2f[i], fourPoint2f[i + 1], Scalar(0, 0, 255), 0);
}
line(frame, fourPoint2f[0], fourPoint2f[3]
, Scalar(0, 0, 255), 0);
}
}
imshow("移动目标跟踪", frame);
FRAME++;
stringstream ss;
ss << FRAME << b;
imwrite(ss.str(), frame);
}
前8张跟踪结果图像如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)