您的位置:首页 > 运维架构

基于OpenCV的背景消除算法[转]

2008-10-22 23:02 232 查看
//经实验发现,用背景减除方法也可以针对某些摄像机运动的情况,而非像大部分文章中所提到的该方法仅仅适合于摄像机静止的情况,而且效果还要较好!实验视频可以是一段足球视频!

/*
*建立多高斯背景模型
*/
void CMotionAnalysisPlatformView::OnBackgdiff()
{
// TODO: Add your command handler code here
IplImage* tmp_frame = 0;
IplImage* dst = 0;

if(!m_capture)
{
MessageBox("读取视频文件失败,请重新打开真彩色(24位)视频!", "错误信息");
return;
}

tmp_frame = cvQueryFrame(m_capture);
dst = cvCreateImage(cvGetSize(tmp_frame), 8, 1);
dst->origin = 1;

if(!tmp_frame)
{
MessageBox("读取视频文件失败,请重新打开真彩色(24位)视频!", "错误信息");
return;
}
cvNamedWindow("背景图像", 1);
cvNamedWindow("前景图像", 1);

//创建多高斯模型
CvBGStatModel* bg_model = cvCreateGaussianBGModel(tmp_frame);

for( int fr = 1;tmp_frame; tmp_frame = cvQueryFrame(m_capture), fr++ )
{
//printf("frame# %d : ", fr);
//获得背景模型更新过程所花费的时间,以 CPU时钟/每微秒 为单位计数
//double t = (double)cvGetTickCount(); //模型更新之前

cvUpdateBGStatModel( tmp_frame, bg_model );
//真正的函数实现体是在: icvUpdateFGDStatModel(tmp_frame, bg_model)

// t = (double)cvGetTickCount() - t; //模型更新之后

// 以左下角为坐标原点
bg_model->foreground->origin = bg_model->background->origin = 1;

//cvErode(bg_model->background, bg_model->background);
//滤除噪声
//cvErode(bg_model->foreground, bg_model->foreground);
//滤除噪声

//printf( "%.1f毫秒n", t/(cvGetTickFrequency()*1000.) );
//最后输出结果以毫秒为单位
cvShowImage("背景图像", bg_model->background);
cvCopy(bg_model->foreground, dst);
cvSmooth(dst, dst, CV_GAUSSIAN, 5);
cvMorphologyEx( dst, dst, 0, 0, CV_MOP_CLOSE, 3);
cvMorphologyEx( dst, dst, 0, 0, CV_MOP_OPEN, 1 );
//提取轮廓 到contour序列中
//cvFindContours 仅能处理 [单通道、颜色深度为8位的图像] 的轮廓提取
cvFindContours( dst,
m_storage, &m_contour, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

for( ; m_contour != 0; m_contour = m_contour->h_next )
{
CvScalar color = CV_RGB( 255, 0, 255 );
CvScalar color_rect = CV_RGB( 0, 255, 255);

m_contour_rect = cvBoundingRect(m_contour, 1);

/*if(m_contour_rect.height
+ m_contour_rect.width > 100 && m_contour_rect.width *
m_contour_rect.height > 20 &&
m_contour_rect.height/m_contour_rect.width > 1.5)
*/
if(fabs(cvContourArea(m_contour)) > 500.0)
{
cvRectangle(dst,
cvPoint(m_contour_rect.x, m_contour_rect.y),
cvPoint((m_contour_rect.x + m_contour_rect.width),(m_contour_rect.y +
m_contour_rect.height)), color_rect, 2, 8, 0);

/* replace CV_FILLED with 1 to see the outlines */
cvDrawContours( dst, m_contour, color, color, -1, CV_FILLED, 8, cvPoint(0,0));
cvShowImage("前景图像", dst);
// cvWaitKey(0);
}
}
int k = cvWaitKey(1); //等待一毫秒
if( k == 'q' ) break;
}

cvReleaseBGStatModel( &bg_model );
cvReleaseCapture(&m_capture);
cvReleaseImage(&dst);
if(m_storage) cvClearMemStorage(m_storage);
cvDestroyWindow("背景图像");
cvDestroyWindow("前景图像");
return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: