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"
5 #include <stdio.h>
6 #include <string>
7
8 using namespace std;
9 using namespace cv;
10
help()11 static void help()
12 {
13 printf("\n"
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"
17 "Call\n"
18 "./segment_objects [video file, else it reads camera 0]\n\n");
19 }
20
refineSegments(const Mat & img,Mat & mask,Mat & dst)21 static void refineSegments(const Mat& img, Mat& mask, Mat& dst)
22 {
23 int niters = 3;
24
25 vector<vector<Point> > contours;
26 vector<Vec4i> hierarchy;
27
28 Mat temp;
29
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);
33
34 findContours( temp, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE );
35
36 dst = Mat::zeros(img.size(), CV_8UC3);
37
38 if( contours.size() == 0 )
39 return;
40
41 // iterate through all the top-level contours,
42 // draw each connected component with its own random color
43 int idx = 0, largestComp = 0;
44 double maxArea = 0;
45
46 for( ; idx >= 0; idx = hierarchy[idx][0] )
47 {
48 const vector<Point>& c = contours[idx];
49 double area = fabs(contourArea(Mat(c)));
50 if( area > maxArea )
51 {
52 maxArea = area;
53 largestComp = idx;
54 }
55 }
56 Scalar color( 0, 0, 255 );
57 drawContours( dst, contours, largestComp, color, FILLED, LINE_8, hierarchy );
58 }
59
60
main(int argc,char ** argv)61 int main(int argc, char** argv)
62 {
63 VideoCapture cap;
64 bool update_bg_model = true;
65
66 help();
67
68 if( argc < 2 )
69 cap.open(0);
70 else
71 cap.open(std::string(argv[1]));
72
73 if( !cap.isOpened() )
74 {
75 printf("\nCan not open camera or video file\n");
76 return -1;
77 }
78
79 Mat tmp_frame, bgmask, out_frame;
80
81 cap >> tmp_frame;
82 if(tmp_frame.empty())
83 {
84 printf("can not read data from the video source\n");
85 return -1;
86 }
87
88 namedWindow("video", 1);
89 namedWindow("segmented", 1);
90
91 Ptr<BackgroundSubtractorMOG2> bgsubtractor=createBackgroundSubtractorMOG2();
92 bgsubtractor->setVarThreshold(10);
93
94 for(;;)
95 {
96 cap >> tmp_frame;
97 if( tmp_frame.empty() )
98 break;
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);
104 if( keycode == 27 )
105 break;
106 if( keycode == ' ' )
107 {
108 update_bg_model = !update_bg_model;
109 printf("Learn background is in state = %d\n",update_bg_model);
110 }
111 }
112
113 return 0;
114 }
115