1 #include "opencv2/core.hpp"
2 #include <opencv2/core/utility.hpp>
3 #include "opencv2/imgproc.hpp"
4 #include "opencv2/video/background_segm.hpp"
5 #include "opencv2/videoio.hpp"
6 #include "opencv2/highgui.hpp"
14 printf("\nDo background segmentation, especially demonstrating the use of cvUpdateBGStatModel().\n"
15 "Learns the background at the start and then segments.\n"
16 "Learning is togged by the space key. Will read from file or camera\n"
18 " ./bgfg_segm [--camera]=<use camera, if this key is present>, [--file_name]=<path to movie file> \n\n");
23 "{c camera | | use camera or not}"
24 "{m method |mog2 | method (knn or mog2) }"
25 "{s smooth | | smooth the mask }"
26 "{fn file_name|tree.avi | movie file }"
29 //this is a sample for foreground detection functions
30 int main(int argc, const char** argv)
34 CommandLineParser parser(argc, argv, keys);
35 bool useCamera = parser.has("camera");
36 bool smoothMask = parser.has("smooth");
37 string file = parser.get<string>("file_name");
38 string method = parser.get<string>("method");
40 bool update_bg_model = true;
45 cap.open(file.c_str());
47 parser.printMessage();
51 printf("can not open camera or video file\n");
55 namedWindow("image", WINDOW_NORMAL);
56 namedWindow("foreground mask", WINDOW_NORMAL);
57 namedWindow("foreground image", WINDOW_NORMAL);
58 namedWindow("mean background image", WINDOW_NORMAL);
60 Ptr<BackgroundSubtractor> bg_model = method == "knn" ?
61 createBackgroundSubtractorKNN().dynamicCast<BackgroundSubtractor>() :
62 createBackgroundSubtractorMOG2().dynamicCast<BackgroundSubtractor>();
64 Mat img0, img, fgmask, fgimg;
73 resize(img0, img, Size(640, 640*img0.rows/img0.cols), INTER_LINEAR);
76 fgimg.create(img.size(), img.type());
79 bg_model->apply(img, fgmask, update_bg_model ? -1 : 0);
82 GaussianBlur(fgmask, fgmask, Size(11, 11), 3.5, 3.5);
83 threshold(fgmask, fgmask, 10, 255, THRESH_BINARY);
86 fgimg = Scalar::all(0);
87 img.copyTo(fgimg, fgmask);
90 bg_model->getBackgroundImage(bgimg);
93 imshow("foreground mask", fgmask);
94 imshow("foreground image", fgimg);
96 imshow("mean background image", bgimg );
98 char k = (char)waitKey(30);
102 update_bg_model = !update_bg_model;
104 printf("Background update is on\n");
106 printf("Background update is off\n");