Skip to content

Instantly share code, notes, and snippets.

@roxlu
Created November 4, 2016 15:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roxlu/ed192db7705f274a9a934e0c79292a56 to your computer and use it in GitHub Desktop.
Save roxlu/ed192db7705f274a9a934e0c79292a56 to your computer and use it in GitHub Desktop.
#include <poly/Log.h>
#include <OpenCvBackgroundSubtraction.h>
namespace poly {
OpenCvBackgroundSubtraction::OpenCvBackgroundSubtraction()
:subtractor(NULL)
,width(0)
,height(0)
{
}
int OpenCvBackgroundSubtraction::init(int w, int h) {
if (w <= 0) {
SX_ERROR("w should be bigger then 0.");
return -1;
}
if (h <= 0) {
SX_ERROR("h should be bigger then 0.");
return -2;
}
width = w;
height = h;
subtractor = cv::createBackgroundSubtractorMOG2(20, 16, true);
if (NULL == subtractor) {
SX_ERROR("Failed to create the background subtractor.");
return -1;
}
return 0;
}
int OpenCvBackgroundSubtraction::update(uint8_t* pixels) {
if (NULL == pixels) {
SX_ERROR("Given pixels are NULL.");
return -1;
}
if (0 == width) {
SX_ERROR("width is 0. call init().");
return -2;
}
if (0 == height) {
SX_ERROR("height is 0. call init().");
return -3;
}
if (NULL == subtractor) {
SX_ERROR("subtractor is NULL. call init().");
return -4;
}
cv::Mat frame(height, width, CV_8UC1, pixels, CV_AUTOSTEP);
if (true == mask.empty()) {
mask.create(frame.size(), frame.type());
}
subtractor->apply(frame, mask, -1);
return 0;
}
} /* namespace poly */
#ifndef POLY_OPENCV_BACKGROUND_SUBTRACTION_H
#define POLY_OPENCV_BACKGROUND_SUBTRACTION_H
#include <opencv2/imgproc.hpp>
#include <opencv2/video/background_segm.hpp>
namespace poly {
class OpenCvBackgroundSubtraction {
public:
OpenCvBackgroundSubtraction();
int init(int w, int h);
int update(uint8_t* pixels);
private:
cv::BackgroundSubtractor* subtractor;
cv::Mat mask;
int width;
int height;
};
} /* namespace poly */
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment