Thursday, May 14, 2009

OpenCV#7: Simple motion detection

This is a simple motion detection algorithm using frame difference method. This example assumes that the video frames are stored in your system in a particular directory.

#include <iostream>
#include <sstream>

#include "cv.h"
#include "highgui.h"

using namespace std;

int main()
{

IplImage* frame_prev = cvLoadImage( "dir_name/frame0.jpg", CV_LOAD_IMAGE_GRAYSCALE );
int M = frame_prev->width;
int N = frame_prev->height;
IplImage* frame_curr;
IplImage* frame_diff = cvCreateImage( cvGetSize(frame_prev), 8, 1 );

for( int i=1; i<=500; ++i )
{
ostringstream oss;
oss << "dir_name/frame";
oss << i;
oss << ".jpg";

// motion detection - simple frame difference algorithm
frame_curr = cvLoadImage( oss.str().c_str(), CV_LOAD_IMAGE_GRAYSCALE );
cvAbsDiff( frame_curr, frame_prev, frame_diff );
cvThreshold( frame_diff, frame_diff, 30, 255, CV_THRESH_BINARY );
cvCopy( frame_curr, frame_prev );

cvNamedWindow( "Motion Detection", CV_WINDOW_AUTOSIZE );
cvShowImage( "Motion Detection", frame_diff );
if( (cvWaitKey(25) & 255) == 27 ) break; // wait for some time or 'ESC' key press
}

cvReleaseImage( &frame_prev );
cvDestroyWindow( "Motion Detection" );

return 0;
}

No comments:

Post a Comment

Followers