opencv三幀差分法運動檢測


基於幀間差分法進行升級的三幀差分法,不同的測試視頻可以設置不同二值化閾值來增強效果。
根據實際情況進行形態學處理。
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>

#define threshold_diff1 25 //設置簡單幀差法閾值
#define threshold_diff2 25 //設置簡單幀差法閾值

using namespace cv;
using namespace std;

int main(int argc,unsigned char* argv[])
{
Mat img_src1,img_src2,img_src3;//3幀法需要3幀圖片
Mat img_dst,gray1,gray2,gray3;
Mat gray_diff1,gray_diff2;//存儲2次相減的圖片
Mat gray_diff11,gray_diff12;
Mat gray_diff21,gray_diff22;
Mat gray;//用來顯示前景的
bool pause=false;

VideoCapture vido_file("test3.avi");//在這里改相應的文件名
namedWindow("foreground",0);
for (;;)
{
if(!false)
{
vido_file >>img_src1;
cvtColor(img_src1,gray1,CV_BGR2GRAY);

waitKey(33);
vido_file >>img_src2;
cvtColor(img_src2,gray2,CV_BGR2GRAY);
imshow("video_src",img_src2);//

waitKey(33);
vido_file >>img_src3;
cvtColor(img_src3,gray3,CV_BGR2GRAY);

Sobel(gray1,gray1, CV_8U,1,0,3,0.4,128);
Sobel(gray2,gray2, CV_8U,1,0,3,0.4,128);
Sobel(gray3,gray3, CV_8U,1,0,3,0.4,128);

subtract(gray2,gray1,gray_diff11);//第二幀減第一幀
subtract(gray1,gray2,gray_diff12);
add(gray_diff11,gray_diff12,gray_diff1);
subtract(gray3,gray2,gray_diff21);//第三幀減第二幀
subtract(gray2,gray3,gray_diff22);
add(gray_diff21,gray_diff22,gray_diff2);

for(int i=0;i<gray_diff1.rows;i++)
for(int j=0;j<gray_diff1.cols;j++)
{
if(abs(gray_diff1.at<unsigned char>(i,j))>=threshold_diff1)//這里模板參數一定要用unsigned char,否則就一直報錯
gray_diff1.at<unsigned char>(i,j)=255; //第一次相減閾值處理
else gray_diff1.at<unsigned char>(i,j)=0;

if(abs(gray_diff2.at<unsigned char>(i,j))>=threshold_diff2)//第二次相減閾值處理
gray_diff2.at<unsigned char>(i,j)=255;
else gray_diff2.at<unsigned char>(i,j)=0;
}
bitwise_and(gray_diff1,gray_diff2,gray);

dilate(gray,gray,Mat());erode(gray,gray,Mat());

imshow("foreground",gray);
}
if( cvWaitKey(33) >= 0 )
break;
}
return 0;
}


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com