标签:opencv
<span style="font-size:14px;">#include <opencv\cv.h> #include <opencv\highgui.h> #include <stdio.h> int main( int argc, char** argv ){ IplImage* pFrame = NULL; IplImage* pFrImg = NULL; IplImage* pBkImg = NULL; CvMat* pFrameMat = NULL; CvMat* pFrMat = NULL; CvMat* pBkMat = NULL; CvCapture* pCapture = NULL; int nFrmNum = 0; cvNamedWindow("video", 1); cvNamedWindow("background",1); cvNamedWindow("foreground",1); cvMoveWindow("video", 30, 0); cvMoveWindow("background", 360, 0); cvMoveWindow("foreground", 690, 0); //打开视频文件 if( !(pCapture = cvCaptureFromFile("video.avi")) ){ fprintf(stderr, "Can not open video file video.avi\n"); return -2; } //逐帧读取视频 while(pFrame = cvQueryFrame( pCapture )){ nFrmNum++; // 第一帧需要申请内存并初始化 if(nFrmNum == 1){ pBkImg = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U,1); pFrImg = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U,1); pBkMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1); pFrMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1); pFrameMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1); // 转换为单通道图像再处理 cvCvtColor(pFrame, pBkImg, CV_BGR2GRAY); cvCvtColor(pFrame, pFrImg, CV_BGR2GRAY); cvConvert(pFrImg, pFrameMat); cvConvert(pFrImg, pFrMat); cvConvert(pFrImg, pBkMat); }else{ cvCvtColor(pFrame, pFrImg, CV_BGR2GRAY); cvConvert(pFrImg, pFrameMat); // 高斯滤波平滑图像 cvSmooth(pFrameMat, pFrameMat, CV_GAUSSIAN, 3, 0, 0); // 当前帧与背景图相减 cvAbsDiff(pFrameMat, pBkMat, pFrMat); // 二值化背景图 cvThreshold(pFrMat, pFrImg, 60, 255.0, CV_THRESH_BINARY); //进行形态学滤波,去除噪声. 效果不好,将行车都作为噪声去除了 //cvErode(pFrImg, pFrImg, 0, 1); //cvDilate(pFrImg, pFrImg, 0, 1); // 更新背景 cvRunningAvg(pFrameMat, pBkMat, 0.003, 0); // 将背景转换为图像格式,用于显示 cvConvert(pBkMat, pBkImg); cvShowImage("video", pFrame); cvShowImage("background", pBkImg); cvShowImage("foreground", pFrImg); if( cvWaitKey(2) >= 0 ) break; } } cvDestroyWindow("video"); cvDestroyWindow("background"); cvDestroyWindow("foreground"); cvReleaseImage(&pFrImg); cvReleaseImage(&pBkImg); cvReleaseMat(&pFrameMat); cvReleaseMat(&pFrMat); cvReleaseMat(&pBkMat); return 0; } </span>
运行结果截图:
标签:opencv
原文地址:http://blog.csdn.net/u010002704/article/details/43734779