1
#include "opencv2/imgproc/imgproc.hpp"
2
#include "opencv2/videoio/videoio.hpp"
3
#include "opencv2/highgui/highgui.hpp"
4
#include "opencv2/video/background_segm.hpp"
14
"This program demonstrated a simple method of connected components clean up of background subtraction\n"
15
"When the program starts, it begins learning the background.\n"
16
"You can toggle background learning on and off by hitting the space bar.\n"
18
"./segment_objects [video file, else it reads camera 0]\n\n");
21
static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
25
vector<vector<Point> > contours;
26
vector<Vec4i> hierarchy;
30
dilate(mask, temp, Mat(), Point(-1,-1), niters);
31
erode(temp, temp, Mat(), Point(-1,-1), niters*2);
32
dilate(temp, temp, Mat(), Point(-1,-1), niters);
34
findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );
36
dst = Mat::zeros(img.size(), CV_8UC3);
38
if( contours.size() == 0 )
41
// iterate through all the top-level contours,
42
// draw each connected component with its own random color
43
int idx = 0, largestComp = 0;
46
for( ; idx >= 0; idx = hierarchy[idx][0] )
48
const vector<Point>& c = contours[idx];
49
double area = fabs(contourArea(Mat(c)));
56
Scalar color( 0, 0, 255 );
57
drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
61
int main(int argc, char** argv)
64
bool update_bg_model = true;
66
CommandLineParser parser(argc, argv, "{help h||}{@input||}");
67
if (parser.has("help"))
72
string input = parser.get<std::string>("@input");
80
printf("\nCan not open camera or video file\n");
84
Mat tmp_frame, bgmask, out_frame;
89
printf("can not read data from the video source\n");
93
namedWindow("video", 1);
94
namedWindow("segmented", 1);
96
Ptr<BackgroundSubtractorMOG2> bgsubtractor=createBackgroundSubtractorMOG2();
97
bgsubtractor->setVarThreshold(10);
102
if( tmp_frame.empty() )
104
bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
105
refineSegments(tmp_frame, bgmask, out_frame);
106
imshow("video", tmp_frame);
107
imshow("segmented", out_frame);
108
int keycode = waitKey(30);
113
update_bg_model = !update_bg_model;
114
printf("Learn background is in state = %d\n",update_bg_model);