完成三个部分:
场景背景、动态物体、提取车辆。
代码如下:
// opencv_try.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <opencv245.h>
using namespace std;
using namespace cv;
Mat paintRect(Mat &src, Rect &rect)
{
float LTopX = static_cast<float>(rect.x);
float LTopY = static_cast<float>(rect.y);
float RBtmX = static_cast<float>(rect.x + rect.width - 1);
float RBtmY = static_cast<float>(rect.y + rect.height - 1);
Point LTopPonit(LTopX, LTopY);
Point RBtmPoint(RBtmX, RBtmY);
rectangle( src, LTopPonit, RBtmPoint, Scalar(0, 0, 255), 1, 8);
return src;
}
void imgProc(Mat &image, vector<Rect> &vecRect)
{
for (auto it = vecRect.begin();it != vecRect.end(); ++it)
{
image = paintRect(image, *it);
}
}
vector<Rect> returnRect(Mat &src )
{
Mat img;
src.copyTo(img);
/*cvtColor(src,img,CV_GRAY2BGR);
cvtColor(img,img,CV_RGB2GRAY);*/
vector<Rect> rects;
int area;
Rect rect;
/*src.copyTo(img);*/
int nRows = img.rows;
int nCols = img.cols;
for (int j = 0; j < nRows; ++j)
{
uchar* p =img.ptr<uchar>(j);
for (int i = 0; i < nCols; ++i)
{
if (p[i] < 250)
{
p[i] = 0;
}
}
}
/*erode(img,img,Mat(),Point(-1,-1),3);*/
dilate(img,img,Mat(),Point(-1,-1),4);
for (int i=0;i<nRows ;i++)
for(int j=0;j<nCols ;j++)
{
if(img.at<uchar>(i,j) == 255)
{
area = floodFill(img, Point(j,i),Scalar::all(0),&rect);//返回面积和矩形坐标
if (area > 3000)
{
rects.push_back(rect);
}
}
}
return rects;
}
int _tmain(int argc, _TCHAR* argv[])
{
string videoFile = "C:\\Users\\sony\\Desktop\\video\\停车场出入口.flv";
VideoCapture capture;
capture.open(videoFile);
if (!capture.isOpened())
{
cout << "read video failure "<<endl;
return -1;
}
BackgroundSubtractorMOG2 mog;
Mat foreground;
Mat background;
Mat moveobject;
Mat srcproc;
vector<Rect> rectVec;
Mat frame;
long frameNo = 0;
while (capture.read(frame))
{
++frameNo;
cout<<frameNo<<endl;
mog(frame, foreground, 0.001);
//腐蚀
erode(foreground, foreground, Mat());
//膨胀
dilate(foreground,foreground,Mat());
mog.getBackgroundImage(background);
rectVec = returnRect(foreground);
imgProc(frame, rectVec);
imshow("foreground", foreground);
imshow("background", background);
imshow("video", frame);
if (waitKey(25) == 99 )
{
imwrite("C:\\Users\\sony\\Desktop\\forground.jpg", foreground);
imwrite("C:\\Users\\sony\\Desktop\\src.jpg", frame);
}
if (waitKey(25) == 97)
{
break;
}
rectVec.clear();
}
return 0;
}