OpenCV混合高斯背景建模

本文介绍了一个基于OpenCV的混合高斯背景建模(MOG)实例,演示了如何使用MOG进行视频背景减除并检测前景物体,提供了一段完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要内容是一个混合高斯背景建模[1]的OpenCV例子。
想要了解MOG原理可以参考混合高斯背景建模原理及实现

OpenCV的MOG例子代码如下:

#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <time.h>
#include <iostream>
#include <fstream>
#include <Windows.h>  
#include <opencv2/opencv.hpp> 

using namespace cv;  
using namespace std;

bool pause = false;//是否暂停
int frameNum = 0;

int main()
{
    uchar key = false;//用来设置暂停

    VideoCapture video("test2.avi"); 
    //Mat frame,mask,thresholdImage,output;
    Mat frame,mask;
    video>>frame;
    //bgSubtractor(history,nmixtures,backgroundRatio,noiseSigma)  
    BackgroundSubtractorMOG bgSubtractor(5,2,0.75,false);

    while(true){
        video>>frame;
        ++frameNum;
        //bgSubtractor(当前帧,二值图,学习率);
        bgSubtractor(frame,mask,0.01);
        imshow("frame",frame);
        imshow("mask",mask);
        waitKey(20);

        //按键P切换暂停和播放
        key = cvWaitKey(1);
        if(key == 'p') pause = true;
        while(pause)
            if(cvWaitKey(0)=='p')
                pause = false;  
    }

    return 0;
}

构造函数可以使用默认构造函数或带形参的构造函数,调用的接口只有重载操作符():

//! the default constructor
CV_WRAP BackgroundSubtractorMOG();
//! the full constructor that takes the length of the history, the number of gaussian mixtures, the background ratio parameter and the noise strength
CV_WRAP BackgroundSubtractorMOG(int history, int nmixtures, double backgroundRatio, double noiseSigma=0);
//! the destructor
virtual ~BackgroundSubtractorMOG();
//! the update operator
virtual void operator()(InputArray image, OutputArray fgmask, double learningRate=0);

函数调用所涉及到的参数得根据实际应用场景进行调整,下面几张图只是简单的前景检测结果:
1
2
3
4

参考资料:

[1] KaewTraKulPong, Pakorn, and Richard Bowden. “An improved adaptive background mixture model for real-time tracking with shadow detection.” Video-Based Surveillance Systems. Springer US, 2002. 135-144. 引用次数:1228

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值