框出动态特定物体

完成三个部分:

场景背景、动态物体、提取车辆。

代码如下:

// 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值