#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
IplImage* mhi=NULL;
IplImage* silh=NULL;
IplImage** buf=NULL;
const int N=2;
int last=0;
const double MHI_DURATION = 1;
void update_mhi( IplImage* img, IplImage* dst, int diff_threshold)
{
double timestamp = clock()/100.;
CvSize size = cvSize(img->width,img->height);
int idx1, idx2;
// IplImage* pyr = cvCreateImage( cvSize((size.width &-2)/2, (size.height&-2)/2), 8, 1 );
// IplImage* pyr = cvCreateImage( cvSize((size.width )/2, (size.height)/2), 8, 1 );
//仅第一次进入循环时运行
if( !mhi || mhi->width != size.width || mhi->height != size.height )
{
if( buf == 0 )
{
buf = (IplImage**)malloc(N*sizeof(buf[0]));//buf[0]为四个字节 buf大小申请为四个图片的大小
memset( buf, 0, N*sizeof(buf[0])); //将fuf的全部内容置零
}
for(int i = 0; i < N; i++ )
{
cvReleaseImage( &buf[i] );
buf[i] = cvCreateImage( size, IPL_DEPTH_8U, 1 );
cvZero( buf[i] );// clear Buffer Frame at the beginning
}
cvReleaseImage( &mhi );
mhi = cvCreateImage( size, IPL_DEPTH_32F, 1 );
cvZero( mhi ); // clear MHI at the beginning
}
cvCvtColor( img, buf[last], CV_BGR2GRAY ); // convert frame to grayscale
idx1 = last;
idx2 = (last + 1) % N; // index of (last - (N-1))th frame
last = idx2;
silh = buf[idx2];
cvAbsDiff( buf[idx1], buf[idx2], silh ); // get difference between frames
cvThreshold( silh, silh, diff_threshold, 255, CV_THRESH_BINARY );
cvUpdateMotionHistory( silh, mhi, timestamp, MHI_DURATION );
cvConvert( mhi, dst );
cvSmooth( dst, dst, CV_MEDIAN, 3, 0, 0, 0 );
// cvPyrDown( dst, pyr, CV_GAUSSIAN_5x5 );
// cvDilate( pyr, pyr, 0, 1 );
// cvPyrUp( pyr, dst, CV_GAUSSIAN_5x5 );
// cvReleaseImage( &pyr );
cvDilate( dst, dst, 0, 1 );
}
int main()
{
CvCapture* pCapture =cvCreateFileCapture("video.avi");
int numfrm=0;
cvNamedWindow("video");
cvNamedWindow("HISTORY");
cvMoveWindow("video",0,0);
cvMoveWindow("HISTORY",500,0);
IplImage *pFrame=NULL;
IplImage *motion=NULL;
while(pFrame = cvQueryFrame( pCapture )) //遍历
{
numfrm++; //遍历
if(!motion)
{
motion=cvCreateImage(cvSize(pFrame->width,pFrame->height),8,1);
cvZero(motion);
motion->origin=pFrame->origin;
}
update_mhi(pFrame,motion,60);
cvShowImage("video",pFrame);
cvShowImage("HISTORY",motion);
if(cvWaitKey(300)==27)
break;
}
cvReleaseImage(&pFrame);
cvReleaseImage(&motion);
cvReleaseImage( &silh );
cvReleaseCapture(&pCapture);
cvDestroyWindow("video");
cvDestroyWindow("HISTORY");
return 0;
}
程序运行结果: