1 #include "opencv2/imgproc/imgproc.hpp"
2 #include "opencv2/highgui/highgui.hpp"
3 #include "opencv2/video/background_segm.hpp"
13 "This program demonstrated a simple method of connected components clean up of background subtraction\n"
14 "When the program starts, it begins learning the background.\n"
15 "You can toggle background learning on and off by hitting the space bar.\n"
17 "./segment_objects [video file, else it reads camera 0]\n\n");
20 static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
24 vector<vector<Point> > contours;
25 vector<Vec4i> hierarchy;
29 dilate(mask, temp, Mat(), Point(-1,-1), niters);
30 erode(temp, temp, Mat(), Point(-1,-1), niters*2);
31 dilate(temp, temp, Mat(), Point(-1,-1), niters);
33 findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );
35 dst = Mat::zeros(img.size(), CV_8UC3);
37 if( contours.size() == 0 )
40 // iterate through all the top-level contours,
41 // draw each connected component with its own random color
42 int idx = 0, largestComp = 0;
45 for( ; idx >= 0; idx = hierarchy[idx][0] )
47 const vector<Point>& c = contours[idx];
48 double area = fabs(contourArea(Mat(c)));
55 Scalar color( 0, 0, 255 );
56 drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
60 int main(int argc, char** argv)
63 bool update_bg_model = true;
70 cap.open(std::string(argv[1]));
74 printf("\nCan not open camera or video file\n");
78 Mat tmp_frame, bgmask, out_frame;
83 printf("can not read data from the video source\n");
87 namedWindow("video", 1);
88 namedWindow("segmented", 1);
90 Ptr<BackgroundSubtractorMOG> bgsubtractor=createBackgroundSubtractorMOG();
91 bgsubtractor->setNoiseSigma(10);
98 bgsubtractor->apply(tmp_frame, bgmask, update_bg_model ? -1 : 0);
99 //CvMat _bgmask = bgmask;
100 //cvSegmentFGMask(&_bgmask);
101 refineSegments(tmp_frame, bgmask, out_frame);
102 imshow("video", tmp_frame);
103 imshow("segmented", out_frame);
104 int keycode = waitKey(30);
109 update_bg_model = !update_bg_model;
110 printf("Learn background is in state = %d\n",update_bg_model);