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" 7#include <stdio.h> 8 9using namespace std; 10using namespace cv; 11 12static void help() 13{ 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" 17"Usage: \n" 18" ./bgfg_segm [--camera]=<use camera, if this key is present>, [--file_name]=<path to movie file> \n\n"); 19} 20 21const char* keys = 22{ 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|../data/tree.avi | movie file }" 27}; 28 29//this is a sample for foreground detection functions 30int main(int argc, const char** argv) 31{ 32 help(); 33 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"); 39 VideoCapture cap; 40 bool update_bg_model = true; 41 42 if( useCamera ) 43 cap.open(0); 44 else 45 cap.open(file.c_str()); 46 47 parser.printMessage(); 48 49 if( !cap.isOpened() ) 50 { 51 printf("can not open camera or video file\n"); 52 return -1; 53 } 54 55 namedWindow("image", WINDOW_NORMAL); 56 namedWindow("foreground mask", WINDOW_NORMAL); 57 namedWindow("foreground image", WINDOW_NORMAL); 58 namedWindow("mean background image", WINDOW_NORMAL); 59 60 Ptr<BackgroundSubtractor> bg_model = method == "knn" ? 61 createBackgroundSubtractorKNN().dynamicCast<BackgroundSubtractor>() : 62 createBackgroundSubtractorMOG2().dynamicCast<BackgroundSubtractor>(); 63 64 Mat img0, img, fgmask, fgimg; 65 66 for(;;) 67 { 68 cap >> img0; 69 70 if( img0.empty() ) 71 break; 72 73 resize(img0, img, Size(640, 640*img0.rows/img0.cols), INTER_LINEAR); 74 75 if( fgimg.empty() ) 76 fgimg.create(img.size(), img.type()); 77 78 //update the model 79 bg_model->apply(img, fgmask, update_bg_model ? -1 : 0); 80 if( smoothMask ) 81 { 82 GaussianBlur(fgmask, fgmask, Size(11, 11), 3.5, 3.5); 83 threshold(fgmask, fgmask, 10, 255, THRESH_BINARY); 84 } 85 86 fgimg = Scalar::all(0); 87 img.copyTo(fgimg, fgmask); 88 89 Mat bgimg; 90 bg_model->getBackgroundImage(bgimg); 91 92 imshow("image", img); 93 imshow("foreground mask", fgmask); 94 imshow("foreground image", fgimg); 95 if(!bgimg.empty()) 96 imshow("mean background image", bgimg ); 97 98 char k = (char)waitKey(30); 99 if( k == 27 ) break; 100 if( k == ' ' ) 101 { 102 update_bg_model = !update_bg_model; 103 if(update_bg_model) 104 printf("Background update is on\n"); 105 else 106 printf("Background update is off\n"); 107 } 108 } 109 110 return 0; 111} 112