1 // Background average sample code done with averages and done with codebooks
2 // (adapted from the OpenCV book sample)
4 // NOTE: To get the keyboard to work, you *have* to have one of the video windows be active
5 // and NOT the consule window.
7 // Gary Bradski Oct 3, 2008.
9 /* *************** License:**************************
11 Right to use this code in any way you want without warrenty, support or any guarentee of it working.
13 BOOK: It would be nice if you cited it:
14 Learning OpenCV: Computer Vision with the OpenCV Library
15 by Gary Bradski and Adrian Kaehler
16 Published by O'Reilly Media, October 3, 2008
19 http://www.amazon.com/Learning-OpenCV-Computer-Vision-Library/dp/0596516134
20 Or: http://oreilly.com/catalog/9780596516130/
21 ISBN-10: 0596516134 or: ISBN-13: 978-0596516130
22 ************************************************** */
23 #include "opencv2/core/core.hpp"
24 #include "opencv2/video/background_segm.hpp"
25 #include "opencv2/imgproc/imgproc_c.h"
26 #include "opencv2/highgui/highgui.hpp"
35 //VARIABLES for CODEBOOK METHOD:
36 CvBGCodeBookModel* model = 0;
37 const int NCHANNELS = 3;
38 bool ch[NCHANNELS]={true,true,true}; // This sets what channels should be adjusted for background bounds
42 printf("\nLearn background and find foreground using simple average and average difference learning method:\n"
43 "Originally from the book: Learning OpenCV by O'Reilly press\n"
45 " bgfg_codebook [--nframes(-nf)=300] [--movie_filename(-mf)=tree.avi] [--camera(-c), use camera or not]\n"
46 "***Keep the focus on the video windows, NOT the consol***\n\n"
47 "INTERACTIVE PARAMETERS:\n"
48 "\tESC,q,Q - quit the program\n"
49 "\th - print this help\n"
50 "\tp - pause toggle\n"
52 "\tr - run mode (single step off)\n"
53 "=== AVG PARAMS ===\n"
54 "\t- - bump high threshold UP by 0.25\n"
55 "\t= - bump high threshold DOWN by 0.25\n"
56 "\t[ - bump low threshold UP by 0.25\n"
57 "\t] - bump low threshold DOWN by 0.25\n"
58 "=== CODEBOOK PARAMS ===\n"
59 "\ty,u,v- only adjust channel 0(y) or 1(u) or 2(v) respectively\n"
60 "\ta - adjust all 3 channels at once\n"
61 "\tb - adjust both 2 and 3 at once\n"
62 "\ti,o - bump upper threshold up,down by 1\n"
63 "\tk,l - bump lower threshold up,down by 1\n"
64 "\tSPACE - reset the model\n"
69 //USAGE: ch9_background startFrameCollection# endFrameCollection# [movie filename, else from camera]
70 //If from AVI, then optionally add HighAvg, LowAvg, HighCB_Y LowCB_Y HighCB_U LowCB_U HighCB_V LowCB_V
74 "{nf|nframes |300 |frames number}"
75 "{c |camera |false |use the camera or not}"
76 "{mf|movie_file|tree.avi |used movie video file}"
78 int main(int argc, const char** argv)
82 CommandLineParser parser(argc, argv, keys);
83 int nframesToLearnBG = parser.get<int>("nf");
84 bool useCamera = parser.get<bool>("c");
85 string filename = parser.get<string>("mf");
86 IplImage* rawImage = 0, *yuvImage = 0; //yuvImage is for codebook method
87 IplImage *ImaskCodeBook = 0,*ImaskCodeBookCC = 0;
88 CvCapture* capture = 0;
90 int c, n, nframes = 0;
92 model = cvCreateBGCodeBookModel();
94 //Set color thresholds to default values
96 model->modMin[1] = model->modMin[2] = 3;
97 model->modMax[0] = 10;
98 model->modMax[1] = model->modMax[2] = 10;
99 model->cbBounds[0] = model->cbBounds[1] = model->cbBounds[2] = 10;
102 bool singlestep = false;
106 printf("Capture from camera\n");
107 capture = cvCaptureFromCAM( 0 );
111 printf("Capture from file %s\n",filename.c_str());
112 capture = cvCreateFileCapture( filename.c_str() );
117 printf( "Can not initialize video capturing\n\n" );
122 //MAIN PROCESSING LOOP:
127 rawImage = cvQueryFrame( capture );
136 if( nframes == 1 && rawImage )
138 // CODEBOOK METHOD ALLOCATION
139 yuvImage = cvCloneImage(rawImage);
140 ImaskCodeBook = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
141 ImaskCodeBookCC = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
142 cvSet(ImaskCodeBook,cvScalar(255));
144 cvNamedWindow( "Raw", 1 );
145 cvNamedWindow( "ForegroundCodeBook",1);
146 cvNamedWindow( "CodeBook_ConnectComp",1);
149 // If we've got an rawImage and are good to go:
152 cvCvtColor( rawImage, yuvImage, CV_BGR2YCrCb );//YUV For codebook method
153 //This is where we build our background model
154 if( !pause && nframes-1 < nframesToLearnBG )
155 cvBGCodeBookUpdate( model, yuvImage );
157 if( nframes-1 == nframesToLearnBG )
158 cvBGCodeBookClearStale( model, model->t/2 );
160 //Find the foreground if any
161 if( nframes-1 >= nframesToLearnBG )
163 // Find foreground by codebook method
164 cvBGCodeBookDiff( model, yuvImage, ImaskCodeBook );
165 // This part just to visualize bounding boxes and centers if desired
166 cvCopy(ImaskCodeBook,ImaskCodeBookCC);
167 cvSegmentFGMask( ImaskCodeBookCC );
170 cvShowImage( "Raw", rawImage );
171 cvShowImage( "ForegroundCodeBook",ImaskCodeBook);
172 cvShowImage( "CodeBook_ConnectComp",ImaskCodeBookCC);
176 c = cvWaitKey(10)&0xFF;
178 // End processing on ESC, q or Q
179 if(c == 27 || c == 'q')
181 //Else check for user input
191 singlestep = !singlestep;
199 cvBGCodeBookClearStale( model, 0 );
208 ch[0] = c == 'y' || c == '0' || c == 'a' || c == '3';
209 ch[1] = c == 'u' || c == '1' || c == 'a' || c == '3' || c == 'b';
210 ch[2] = c == 'v' || c == '2' || c == 'a' || c == '3' || c == 'b';
211 printf("CodeBook YUV Channels active: %d, %d, %d\n", ch[0], ch[1], ch[2] );
213 case 'i': //modify max classification bounds (max bound goes higher)
214 case 'o': //modify max classification bounds (max bound goes lower)
215 case 'k': //modify min classification bounds (min bound goes lower)
216 case 'l': //modify min classification bounds (min bound goes higher)
218 uchar* ptr = c == 'i' || c == 'o' ? model->modMax : model->modMin;
219 for(n=0; n<NCHANNELS; n++)
223 int v = ptr[n] + (c == 'i' || c == 'l' ? 1 : -1);
224 ptr[n] = cv::saturate_cast<uchar>(v);
226 printf("%d,", ptr[n]);
228 printf(" CodeBook %s Side\n", c == 'i' || c == 'o' ? "High" : "Low" );
234 cvReleaseCapture( &capture );
235 cvDestroyWindow( "Raw" );
236 cvDestroyWindow( "ForegroundCodeBook");
237 cvDestroyWindow( "CodeBook_ConnectComp");