#include <stdio.h>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <cvaux.h>//必须引此头文件
void main( )
{
//参数初始化定义
IplImage* pFrame = NULL;
IplImage* pFrImg = NULL;
IplImage* pBkImg = NULL;
CvCapture* pCapture = NULL;
IplImage* origin_rgb = NULL ;//定义rgb空间的存储
IplImage* origin_ycc = NULL ;//定义转换成YCrCb空间的存储
IplImage* lumi = NULL ;//定义亮度分量的存储空间
//定义窗口
cvNamedWindow("lumi",1);//定义显示窗口的名字,显示原始的视频
cvMoveWindow("lumi",30,0);//定义显示窗口的位置
cvNamedWindow("background",1);//显示经过转换格式的视频
cvMoveWindow("background",360,0);
cvNamedWindow("foreground",1);//显示经过亮度提取的视频
cvMoveWindow("foreground",690,0);
//读取一帧视频文件作为初始化
pCapture = cvCaptureFromFile("video.long.xvid.avi") ;
pFrame = cvQueryFrame(pCapture);
int i ;
for (i=0;i<2;i++)
{
pFrame = cvQueryFrame(pCapture);
}
//RGB转换成亮度
origin_rgb = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U, 3 );
origin_ycc = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U, 3 );
lumi = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U, 1 );
pFrImg = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U, 1 );
pBkImg = cvCreateImage(cvSize(pFrame->width, pFrame->height), IPL_DEPTH_8U, 1 );
//origin_rgb = cvCloneImage(pFrame) ;//或者 cvCopy(pFrame,origin_rgb,NULL) ;
cvCopy(pFrame,origin_rgb,NULL) ;//复制视频
cvCvtColor(origin_rgb,origin_ycc,CV_BGR2YCrCb) ; //实现视频格式转换
cvSplit(origin_ycc,lumi,NULL,NULL,NULL); //获取亮度分量
//为高斯模型设置初时参数
CvGaussBGStatModelParams* params = new CvGaussBGStatModelParams;
params->win_size = 50;
params->n_gauss = 3;
params->bg_threshold = 0.7;
params->std_threshold = 3.5;
params->minArea = 15;
params->weight_init = 0.333;
params->variance_init = 30;
CvBGStatModel* bgModel = cvCreateGaussianBGModel(lumi,params);
int key=-1;
while(key != 'q')
{
//获取下一帧视频
pFrame = cvQueryFrame(pCapture);
cvCopy(pFrame,origin_rgb,NULL) ;//复制视频
cvCvtColor(origin_rgb,origin_ycc,CV_BGR2YCrCb) ; //实现视频格式转换
cvSplit(origin_ycc,lumi,NULL,NULL,NULL); //获取亮度分量
if( !pFrame )
break;
//更新高斯模型
cvUpdateBGStatModel(lumi,bgModel);
pFrImg = bgModel->foreground ;//前景图象
pBkImg = bgModel->background ; //背景图象
//将图象倒转过来
pBkImg->origin = 1 ;
pFrImg->origin = 1 ;
lumi->origin = 1 ;
//显示结果
cvShowImage("lumi",lumi);
cvShowImage("background",pBkImg);
cvShowImage("foreground",pFrImg);
key = cvWaitKey(10);
}
// cvWaitKey(0) ;//窗口的回调函数,必须要的,不然窗口的显示会不正常
//释放窗口内存资源
cvDestroyWindow("lumi");
cvDestroyWindow("background");
cvDestroyWindow("foreground");
//释放图象占用的内存资源
cvReleaseImage(&lumi);
cvReleaseImage(&pBkImg);
cvReleaseImage(&pFrImg);
cvReleaseCapture(&pCapture);
cvReleaseBGStatModel( &bgModel );
}