#include<iostream>
#include<opencv\cv.hpp>
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
//通过帧差法确定动态目标并标定
using namespace std;
using namespace cv;
int main() {
VideoCapture video("F:\\file\\video\\car.avi");//opencv the camera of the computer
if (!video.isOpened())
return -1;//judge whether the camera is opened
Mat CurrentBGRFrame;//the current colorful frame
Mat PreviousFirstGrayFrame;//the previous gray frame
Mat PreviousSecondGrayFrame;//???????
Mat CurrentGrayFrame;//
Mat DiffFramePre;//the difference between
Mat DiffFrameCurrent;//??????
Mat AbsFrameDiff;//
Mat PreviousSegmentation;//
Mat CurrentSegmentation;//
Mat Segmentation;//
int thresh = 8;
int NumFrame = 0;//record the current frame
Mat Kernel = getStructuringElement(MORPH_RECT,Size(21,21),Point(-1,-1));
for (;;)
{
video >> CurrentBGRFrame;
if (!CurrentBGRFrame.data)
break;
NumFrame++;
cvtColor(CurrentBGRFrame,CurrentGrayFrame,COLOR_BGR2GRAY);
if (NumFrame == 1)
{
PreviousFirstGrayFrame = CurrentGrayFrame.clone();
imshow("video", CurrentBGRFrame);
continue;
}
else if (NumFrame == 2)
{
PreviousSecondGrayFrame = CurrentGrayFrame.clone();
absdiff(PreviousSecondGrayFrame, PreviousFirstGrayFrame, AbsFrameDiff);
threshold(AbsFrameDiff,PreviousSegmentation,10,255,CV_THRESH_BINARY);
imshow("video",CurrentBGRFrame);
continue;
}
else
{
absdiff(CurrentGrayFrame,PreviousFirstGrayFrame,AbsFrameDiff);
threshold(AbsFrameDiff, CurrentSegmentation, 30, 255, CV_THRESH_BINARY);
bitwise_and(PreviousSegmentation, CurrentSegmentation,Segmentation);
medianBlur(Segmentation, Segmentation, 3);
//dilate the image
dilate(Segmentation, Segmentation, Kernel);
//find the edge
vector<vector<Point>>contours;
vector<Vec4i>hierarchy;
Mat tempSegmentation = Segmentation.clone();
findContours(Segmentation, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
vector<Moments> mu(contours.size());
for (int i = 0; i < contours.size(); i++)
{
mu[i] = moments(contours[i], false);
}
//计算轮廓的质心
vector<Point2f> mc(contours.size());
for (int i = 0; i < contours.size(); i++)
{
mc[i] = Point2d(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
}
//
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(255, 0, 0);
drawContours(CurrentBGRFrame, contours, i, color, 2, 8, hierarchy, 0, Point());
circle(CurrentBGRFrame, mc[i], 5, Scalar(0, 0, 255), -1, 8, 0);
rectangle(CurrentBGRFrame, boundingRect(contours.at(i)), cvScalar(0, 255, 0));
char tam[100];
sprintf_s(tam, "(%0.0f,%0.0f)", mc[i].x, mc[i].y);
putText(CurrentBGRFrame, tam, Point(mc[i].x, mc[i].y), FONT_HERSHEY_SIMPLEX, 0.4, cvScalar(255, 0, 255), 1);
}
imshow("video", CurrentBGRFrame);
imshow("segmentation", Segmentation);
PreviousFirstGrayFrame = CurrentGrayFrame.clone();
PreviousSegmentation = CurrentSegmentation.clone();
}
if (waitKey(30) == 'q')
break;
}
return 0;
}
动态目标获取并标定+提取质心
最新推荐文章于 2022-05-12 17:27:35 发布