标签:
上一篇文章介绍有原理,本文给出参考代码,注意,这里的代码仅仅有参考意义,并没有考虑工程实际中的效率,内存耗费等问题,望谅解。
int CallTime = 0;//定义调用次数计数器 IplImage* BackGroundImage;//上一帧灰度图 IplImage* DiffImage_1;//上一帧差分图的二值化图 void ThreeFrmDiff(IplImage* pColorIn) { CallTime++; if(CallTime > 10)//防止溢出 { CallTime = 10; } CvSize ImageSize = cvSize(pColorIn->width,pColorIn->height); IplImage* GrayImage = cvCreateImage(ImageSize,IPL_DEPTH_8U,1);//当前帧的灰度图 IplImage* GxImage = cvCreateImage(ImageSize,IPL_DEPTH_8U,1);//当前帧的X方向梯度图 IplImage* GyImage = cvCreateImage(ImageSize,IPL_DEPTH_8U,1);//当前帧的Y方向梯度图 IplImage* DiffImage = cvCreateImage(ImageSize,IPL_DEPTH_8U,1);//当前帧的差分图 IplImage* DiffImage_2 = cvCreateImage(ImageSize,IPL_DEPTH_8U,1);//前一帧差分图 IplImage* pyr = cvCreateImage(cvSize((ImageSize.width&-2)/2,(ImageSize.height&-2)/2),8,1); //进行腐蚀去除噪声的中间临时图片 uchar* DiffImageData_2; DiffImageData_2 = (uchar*)DiffImage_2->imageData;//得到前一帧差分图的数据 int height,width,step;//定义图像的高,宽,步长 int SumInRect = 0;//指定矩形内图像数据之和 int y1, y2, x1, x2;//对运动目标画框时的四个坐标点位置 y1 = 0; y2 = 0; x1 = 0; x2 = 0; char Kx[9] = {1,0,-1,2,0,-2,1,0,-1};//X方向掩模,用于得到X方向梯度图 char Ky[9] = {1,2,1,0,0,0,-1,-2,-1};//Y方向掩模,用于得到Y方向梯度图 CvMat KX,KY; KX = cvMat(3,3,CV_8S,Kx);//构建掩模内核 KY = cvMat(3,3,CV_8S,Ky);//构建掩模内核 cvCvtColor(pColorIn,GrayImage,CV_BGR2GRAY);//将当前帧转化为灰度图 cvSmooth(GrayImage,GrayImage,CV_GAUSSIAN,7,7);//进行平滑处理 cvFilter2D(GrayImage,GxImage,&KX,cvPoint(-1,-1));//得到X方向的梯度图 cvFilter2D(GrayImage,GyImage,&KY,cvPoint(-1,-1));//得到Y方向的梯度图 cvAdd(GxImage,GyImage,GrayImage,NULL);//得到梯度图 height = GrayImage->height; width = GrayImage->width; step = GrayImage->widthStep; CvRect rect;//定义矩形框 if(CallTime == 1)//如果是第一帧 { //对Image_1,BackGroundImage,DiffImage_1进行内存申请 BackGroundImage = cvCreateImage(ImageSize,IPL_DEPTH_8U,1); DiffImage_1 = cvCreateImage(ImageSize,IPL_DEPTH_8U,1); cvCopy(GrayImage,BackGroundImage,NULL);//如果是第一帧,设置为背景 } else { cvAbsDiff(GrayImage,BackGroundImage,DiffImage);//得到当前帧的差分图 cvCopy(GrayImage,BackGroundImage,NULL);//将当前帧的梯度图作为下一帧的背景 cvThreshold(DiffImage,DiffImage,15,255,CV_THRESH_BINARY);//二值化当前差分图 if(CallTime > 2)//如果大于等于第三帧 { cvAnd(DiffImage,DiffImage_1,DiffImage_2);//进行“与”运算,得到前一帧灰度图的“准确”运动目标 char str[256]; memset(str, '\0', 256*sizeof(char)); static int iCount = 0; sprintf(str, "./img/%d.jpg", iCount++); cvSaveImage(str, DiffImage_2); } cvPyrDown(DiffImage_2,pyr,7);//向下采样 cvErode(pyr,pyr,0,1);//腐蚀,消除小的噪声 cvPyrUp(pyr,DiffImage_2,7); cvCopy(DiffImage,DiffImage_1,NULL);//备份当前差分图的二值化图 } cvReleaseImage(&GxImage); cvReleaseImage(&GyImage); cvReleaseImage(&GrayImage); cvReleaseImage(&DiffImage); cvReleaseImage(&DiffImage_2); cvReleaseImage(&pyr); }
标签:
原文地址:http://blog.csdn.net/carson2005/article/details/42218701