1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
|
#include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/background_segm.hpp" #include "opencv2/highgui/highgui.hpp" #include <stdio.h> using namespace std; using namespace cv;
static void help() { printf("\n\n\t此程序展示了视频前后背景分离的方法,采用cvUpdateBGStatModel()方法.\n" "\n\n\t程序首先会“学习背景”,然后进行分割。\n" "\n\n\t可以用过【Space】空格进行功能切换。\n\n"); }
int main(int argc, const char** argv) { help(); VideoCapture cap; bool update_bg_model = true;
cap.open(0);
if( !cap.isOpened() ) { printf("can not open camera or video file\n"); return -1; }
namedWindow("image", WINDOW_AUTOSIZE); namedWindow("foreground mask", WINDOW_AUTOSIZE); namedWindow("foreground image", WINDOW_AUTOSIZE); namedWindow("mean background image", WINDOW_AUTOSIZE);
Ptr<BackgroundSubtractorMOG2> bg_model = createBackgroundSubtractorMOG2();
Mat img, fgmask, fgimg;
for(;;) { cap >> img;
if( img.empty() ) break;
if( fgimg.empty() ) fgimg.create(img.size(), img.type());
bg_model->apply(img, fgmask, update_bg_model ? -1 : 0);
fgimg = Scalar::all(0); img.copyTo(fgimg, fgmask);
Mat bgimg; bg_model->getBackgroundImage(bgimg);
imshow("image", img); imshow("foreground mask", fgmask); imshow("foreground image", fgimg); if(!bgimg.empty()) imshow("mean background image", bgimg );
char k = (char)waitKey(1); if( k == 27 ) break; if( k == ' ' ) { update_bg_model = !update_bg_model; if(update_bg_model) printf("\t>背景更新(Background update)已打开\n"); else printf("\t>背景更新(Background update)已关闭\n"); } }
return 0; }
|