视频处理三帧差分法简易代码



#include "stdafx.h"
#include
#include
using namespace std;
using namespace cv;
const int threshold1 = 25;
const int threshold2 = 25;
int main()
{
VideoCapture cap(0);
namedWindow("test", 0);
if (!cap.isOpened())
{
cout << "open is file " << endl;
return 0;
}
//存三帧图片
Mat img;
Mat preimg;
Mat nextimg;
int flag;
Mat gray1, gray2, gray3;
//存两次相减的图片
Mat gray_img1, gray_img2;
Mat gray_img31, gray_img32;
Mat gray_img13, gray_img12;
Mat gray_img21, gray_img23;
//显示前景
Mat gray;
cap >> preimg;
cvtColor(preimg, gray1, CV_BGR2GRAY);
cap >> img;
cvtColor(img, gray2, CV_BGR2GRAY);
for (;;)
{
cap >> nextimg;
cvtColor(nextimg, gray3, CV_BGR2GRAY);


//第二帧减第一帧
subtract(gray2, gray1, gray_img21);
subtract(gray1, gray2, gray_img12);
add(gray_img21, gray_img12, gray_img1);
subtract(gray3, gray2, gray_img32);
subtract(gray2, gray3, gray_img23);
add(gray_img32, gray_img23, gray_img2);
for (int i = 0; i {
for (int j = 0; j {
if (abs(gray_img1.at(i, j)) >= threshold1)
gray_img1.at(i, j) = 225;
else gray_img1.at(i, j) = 0;
if (abs(gray_img2.at(i, j) >= threshold2))
gray_img2.at(i, j) = 225;
else gray_img2.at(i, j) = 0;
}
}
bitwise_and(gray_img1, gray_img2, gray);
dilate(gray, gray, Mat());
erode(gray, gray, Mat());
imshow("test", gray);
namedWindow("test1", 0);
imshow("test1", nextimg);


gray1 = gray2.clone();
gray2 = gray3.clone();


if (waitKey(30) >= 0) break;


}
return 0;
}

你可能感兴趣的:(vs,opencv)