Motion Detection using Frame Differencing and Mean Background Model

Instead of using static background model to find difference in current frame, I am using frame difference technique where current frame is compared or subtracted from previous frame. The difference depends upon speed of moving objects. Making a fair analysis is very difficult. Find the code bellow to find difference in frames.

VideoCapture capture("ewap/seq_hotel.avi");
	Mat pFrame, cFrame, motion;
	int fWidth, fHeight;

	fHeight= capture.get(CAP_PROP_FRAME_HEIGHT);
	fWidth = capture.get(CAP_PROP_FRAME_WIDTH);


	cvNamedWindow( "video", CV_WINDOW_AUTOSIZE );
	if(capture.read(pFrame)){

		while( 1 )
		{

			if(!capture.read(cFrame))
				break;

			if(cFrame.empty())
				break;

			absdiff(cFrame,pFrame,motion);

			cvtColor(motion,motion,CV_RGB2GRAY);

			Mat ero1 = getStructuringElement(MORPH_RECT, Size(3,3));

			threshold(motion, motion, 30, 255,CV_THRESH_BINARY );



			imshow( "video", motion);
			waitKey(1);
			pFrame = cFrame.clone();
		}
	}	
	capture.release();

Frame Difference

Mean background Model

The simplest technique is to take a background image without any moving object. Subtract current frame from static background image to find changes in current frame. But it can’t deal with objects being added or removed from static scene, illumination changes and changes in camera position etc. To overcome above mentioned issues frame difference approach is commonly used. I discussed frame differencing approach above. Average background is an alternative technique is used to incorporate background changes. I discussed averaging method in another article. Average background can be computed using accumlateWeighted function to determine average background.

accumulateweighted(current_frame, average_frame, 0.01); 

0.01 is passed as learning rate. The following code is used to subtract average model from current frame to find difference. Moving objects and some noise is also shown in video output.

VideoCapture capture("ewap/seq_hotel.avi");
	Mat model, cFrame, motion;
	int fWidth, fHeight;

	fHeight= capture.get(CAP_PROP_FRAME_HEIGHT);
	fWidth = capture.get(CAP_PROP_FRAME_WIDTH);

	cvNamedWindow( "video", CV_WINDOW_AUTOSIZE );


		while( 1 )
		{

			if(!capture.read(cFrame))
				break;

			if(cFrame.empty())
				break;
			model= imread("ewap/bgmodel.jpg",1);

			absdiff(cFrame,model,motion);
			cvtColor(motion,motion,CV_RGB2GRAY);

			threshold(motion, motion, 30, 255,CV_THRESH_BINARY );

			imshow( "video", motion);
			waitKey(1);			
		}
		
	capture.release();

Results after running above code on EWAP dataset

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.