//三帧差
#include "stdafx.h"
#include "highgui.h"
#include "cxcore.h"
#include "ml.h"
#include "cv.h"
using namespace std;
using namespace cv;
#define thresholded 15 //设置简单帧差法阈值
int main(int argc,unsigned char* argv[])
{
Mat img,img1,img2,img3;//3帧法需要3帧图片
Mat imgGray;
Mat result1,result2,result;//存储2次相减的图片
VideoCapture vido_file("C:/Users/acer/Desktop/cut/车辆.avi");//在这里改相应的文件名
int frameCount = vido_file.get(CV_CAP_PROP_FRAME_COUNT);//获取帧数
cout<>img;
cvtColor(img,img,CV_BGR2GRAY);
++count;
if(count%3==1)
{
if(count==1)
goto L;
img1=img;
result1=abs(img1-img3);
threshold(result1,result1,thresholded,255,cv::THRESH_BINARY);
imshow("result1",result1);
}
if(count%3==2)
{
img2=img;
result2=abs(img2-img1);
threshold(result2,result2,thresholded,255,cv::THRESH_BINARY);
imshow("result2",result2);
}
if(count%3==0)
{
img3=img;
if(count==3)
goto L;
bitwise_and(result1,result2,result);
//threshold(result,result,thresholded,255,cv::THRESH_BINARY);
Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(6, 6));
dilate(result, result, kernel_dilate);
//dilate(gray,gray,Mat());
//erode(gray,gray,Mat());
imshow("foreground",result);
}
}
if( cvWaitKey(33) >= 0 )
break;
}
return 0;
}
//帧差
while(1)
{
if (img.empty())//对帧进行异常检测
{
cout << "frame is empty!" << endl;
break;
}
if (i == 0)//
{
result = MoveDetect(img, img);
}
else//若不是第一帧(temp有值了)
{
result = MoveDetect(temp, img);
}
imshow("result", result);
if (waitKey(1000.0 / FPS) == 27)//按原FPS显示
{ cout << "ESC退出!" << endl;
break;}
temp = img.clone();
}
Mat MoveDetect(Mat temp, Mat frame)
{
Mat result = frame.clone();
//1.将background和frame转为灰度图
Mat gray1, gray2;
cvtColor(temp, gray1, CV_BGR2GRAY);
cvtColor(frame, gray2, CV_BGR2GRAY);
//2.将background和frame做差
Mat diff;
absdiff(gray1, gray2, diff);
//imshow("diff", diff);
//3.对差值图diff_thresh进行阈值化处理
Mat diff_thresh;
threshold(diff, diff_thresh, 80, 255, CV_THRESH_BINARY);
//imshow("diff_thresh", diff_thresh);
//4.腐蚀
Mat kernel_erode = getStructuringElement(MORPH_RECT, Size(3, 3));
Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(18, 18));
erode(diff_thresh, diff_thresh, kernel_erode);
//imshow("erode", diff_thresh);
//5.膨胀
dilate(diff_thresh, diff_thresh, kernel_dilate);
imshow("dilate", diff_thresh);
//6.查找轮廓并绘制轮廓
vector > contours;
findContours(diff_thresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
drawContours(result, contours, -1, Scalar(0, 0, 255), 2);//在result上绘制轮廓
//7.查找正外接矩形
vector boundRect(contours.size());
for (int i = 0; i < contours.size(); i++)
{
boundRect[i] = boundingRect(contours[i]);
rectangle(result, boundRect[i], Scalar(0, 255, 0), 2);//在result上绘制正外接矩形
}
return diff_thresh;
// return result;//返回result
}