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;
71 cap.open(std::string(argv[1]));
75 printf("\nCan not open camera or video file\n");
79 Mat tmp_frame, bgmask, out_frame;
84 printf("can not read data from the video source\n");
88 namedWindow("video", 1);
89 namedWindow("segmented", 1);
91 Ptr<BackgroundSubtractorMOG> bgsubtractor=createBackgroundSubtractorMOG();
92 bgsubtractor->setNoiseSigma(10);
99 bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
100 refineSegments(tmp_frame, bgmask, out_frame);
101 imshow("video", tmp_frame);
102 imshow("segmented", out_frame);
103 int keycode = waitKey(30);
108 update_bg_model = !update_bg_model;
109 printf("Learn background is in state = %d\n",update_bg_model);