Skip to content

Instantly share code, notes, and snippets.

@joshuajnoble
Created August 23, 2013 04:43
Show Gist options
  • Save joshuajnoble/6315622 to your computer and use it in GitHub Desktop.
Save joshuajnoble/6315622 to your computer and use it in GitHub Desktop.
Using BackgroundSubtractorMOG2 in Cinder
#include "cinder/app/AppBasic.h"
#include "cinder/gl/gl.h"
#include "cinder/Capture.h"
#include "CinderOpenCV.h"
#include "cinder/gl/Texture.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class bgModelApp : public AppBasic {
public:
void setup();
void mouseDown( MouseEvent event );
void update();
void draw();
cv::BackgroundSubtractorMOG2 mBackgroundModel;
cv::Mat mNewestFrameMat, mForegroundMask, mForegroundImage;
gl::Texture mForegroundTex, mBackgroundTex;
Capture capture;
bool updateBackgroundModel;
};
void bgModelApp::setup()
{
capture = Capture(640, 480);
capture.start();
gl::Texture::Format fmt;
mForegroundTex = gl::Texture(640, 480, fmt);
mBackgroundTex = gl::Texture(640, 480, fmt);
}
void bgModelApp::mouseDown( MouseEvent event )
{
// this is manual right now, but a check of a motion hist or optical flow
// can tell you how much the frame has changed so you know when to update
updateBackgroundModel = true;
}
void bgModelApp::update()
{
if(capture.checkNewFrame()) {
//update the model
mNewestFrameMat = toOcv(capture.getSurface());
mBackgroundModel(mNewestFrameMat, mForegroundMask, updateBackgroundModel ? -1 : 0);
mForegroundImage = cv::Mat::zeros(640, 480, CV_8UC3); // blank it
mNewestFrameMat.copyTo(mForegroundImage, mForegroundMask);
Surface tmpFg = fromOcv(mNewestFrameMat);
mForegroundTex.update( tmpFg );
// a way to diff the prev foregrounds and then update the model
cv::Mat bgimg;
mBackgroundModel.getBackgroundImage(bgimg);
Surface tmpBg = fromOcv(bgimg);
mBackgroundTex.update( tmpBg );
}
}
void bgModelApp::draw()
{
// clear out the window with black
gl::clear( Color( 0, 0, 0 ) );
gl::draw( mForegroundTex );
}
CINDER_APP_BASIC( bgModelApp, RendererGl )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment