7a811c75371a08c07d38fb56b7ae034c2b68e008
[opencv] / samples / c / bgfg_codebook.cpp
1 // Background average sample code done with averages and done with codebooks
2 // (adapted from the OpenCV book sample)
3 // 
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.
6 //
7 // Gary Bradski Oct 3, 2008.
8 // 
9 /* *************** License:**************************
10    Oct. 3, 2008
11    Right to use this code in any way you want without warrenty, support or any guarentee of it working.
12
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
17  
18    AVAILABLE AT: 
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
24 #include "cvaux.h"
25 #include "cxmisc.h"
26 #include "highgui.h"
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30
31 //VARIABLES for CODEBOOK METHOD:
32 CvBGCodeBookModel* model = 0;
33 const int NCHANNELS = 3;
34 bool ch[NCHANNELS]={true,true,true}; // This sets what channels should be adjusted for background bounds
35
36 void help(void)
37 {
38     printf("\nLearn background and find foreground using simple average and average difference learning method:\n"
39         "\nUSAGE:\nbgfg_codebook [--nframes=300] [movie filename, else from camera]\n"
40         "***Keep the focus on the video windows, NOT the consol***\n\n"
41         "INTERACTIVE PARAMETERS:\n"
42         "\tESC,q,Q  - quit the program\n"
43         "\th    - print this help\n"
44         "\tp    - pause toggle\n"
45         "\ts    - single step\n"
46         "\tr    - run mode (single step off)\n"
47         "=== AVG PARAMS ===\n"
48         "\t-    - bump high threshold UP by 0.25\n"
49         "\t=    - bump high threshold DOWN by 0.25\n"
50         "\t[    - bump low threshold UP by 0.25\n"
51         "\t]    - bump low threshold DOWN by 0.25\n"
52         "=== CODEBOOK PARAMS ===\n"
53         "\ty,u,v- only adjust channel 0(y) or 1(u) or 2(v) respectively\n"
54         "\ta    - adjust all 3 channels at once\n"
55         "\tb    - adjust both 2 and 3 at once\n"
56         "\ti,o  - bump upper threshold up,down by 1\n"
57         "\tk,l  - bump lower threshold up,down by 1\n"
58         "\tSPACE - reset the model\n"
59         );
60 }
61
62 //
63 //USAGE:  ch9_background startFrameCollection# endFrameCollection# [movie filename, else from camera]
64 //If from AVI, then optionally add HighAvg, LowAvg, HighCB_Y LowCB_Y HighCB_U LowCB_U HighCB_V LowCB_V
65 //
66 int main(int argc, char** argv)
67 {
68     const char* filename = 0;
69     IplImage* rawImage = 0, *yuvImage = 0; //yuvImage is for codebook method
70     IplImage *ImaskCodeBook = 0,*ImaskCodeBookCC = 0;
71     CvCapture* capture = 0;
72
73     int c, n, nframes = 0;
74     int nframesToLearnBG = 300;
75
76     model = cvCreateBGCodeBookModel();
77     
78     //Set color thresholds to default values
79     model->modMin[0] = 3;
80     model->modMin[1] = model->modMin[2] = 3;
81     model->modMax[0] = 10;
82     model->modMax[1] = model->modMax[2] = 10;
83     model->cbBounds[0] = model->cbBounds[1] = model->cbBounds[2] = 10;
84
85     bool pause = false;
86     bool singlestep = false;
87
88     for( n = 1; n < argc; n++ )
89     {
90         static const char* nframesOpt = "--nframes=";
91         if( strncmp(argv[n], nframesOpt, strlen(nframesOpt))==0 )
92         {
93             if( sscanf(argv[n] + strlen(nframesOpt), "%d", &nframesToLearnBG) == 0 )
94             {
95                 help();
96                 return -1;
97             }
98         }
99         else
100             filename = argv[n];
101     }
102
103     if( !filename )
104     {
105         printf("Capture from camera\n");
106         capture = cvCaptureFromCAM( 0 );
107     }
108     else
109     {
110         printf("Capture from file %s\n",filename);
111         capture = cvCreateFileCapture( filename );
112     }
113
114     if( !capture )
115     {
116         printf( "Can not initialize video capturing\n\n" );
117         help();
118         return -1;
119     }
120
121     //MAIN PROCESSING LOOP:
122     for(;;)
123     {
124         if( !pause )
125         {
126             rawImage = cvQueryFrame( capture );
127             ++nframes;
128             if(!rawImage) 
129                 break;
130         }
131         if( singlestep )
132             pause = true;
133         
134         //First time:
135         if( nframes == 1 && rawImage )
136         {
137             // CODEBOOK METHOD ALLOCATION
138             yuvImage = cvCloneImage(rawImage);
139             ImaskCodeBook = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
140             ImaskCodeBookCC = cvCreateImage( cvGetSize(rawImage), IPL_DEPTH_8U, 1 );
141             cvSet(ImaskCodeBook,cvScalar(255));
142             
143             cvNamedWindow( "Raw", 1 );
144             cvNamedWindow( "ForegroundCodeBook",1);
145             cvNamedWindow( "CodeBook_ConnectComp",1);
146         }
147
148         // If we've got an rawImage and are good to go:                
149         if( rawImage )
150         {
151             cvCvtColor( rawImage, yuvImage, CV_BGR2YCrCb );//YUV For codebook method
152             //This is where we build our background model
153             if( !pause && nframes-1 < nframesToLearnBG  )
154                 cvBGCodeBookUpdate( model, yuvImage );
155
156             if( nframes-1 == nframesToLearnBG  )
157                 cvBGCodeBookClearStale( model, model->t/2 );
158             
159             //Find the foreground if any
160             if( nframes-1 >= nframesToLearnBG  )
161             {
162                 // Find foreground by codebook method
163                 cvBGCodeBookDiff( model, yuvImage, ImaskCodeBook );
164                 // This part just to visualize bounding boxes and centers if desired
165                 cvCopy(ImaskCodeBook,ImaskCodeBookCC);  
166                 cvSegmentFGMask( ImaskCodeBookCC );
167             }
168             //Display
169             cvShowImage( "Raw", rawImage );
170             cvShowImage( "ForegroundCodeBook",ImaskCodeBook);
171             cvShowImage( "CodeBook_ConnectComp",ImaskCodeBookCC);
172         }
173
174         // User input:
175         c = cvWaitKey(10)&0xFF;
176         c = tolower(c);
177         // End processing on ESC, q or Q
178         if(c == 27 || c == 'q')
179             break;
180         //Else check for user input
181         switch( c )
182         {
183         case 'h':
184             help();
185             break;
186         case 'p':
187             pause = !pause;
188             break;
189         case 's':
190             singlestep = !singlestep;
191             pause = false;
192             break;
193         case 'r':
194             pause = false;
195             singlestep = false;
196             break;
197         case ' ':
198             cvBGCodeBookClearStale( model, 0 );
199             nframes = 0;
200             break;
201             //CODEBOOK PARAMS
202         case 'y': case '0':
203         case 'u': case '1':
204         case 'v': case '2':
205         case 'a': case '3':
206         case 'b': 
207             ch[0] = c == 'y' || c == '0' || c == 'a' || c == '3';
208             ch[1] = c == 'u' || c == '1' || c == 'a' || c == '3' || c == 'b';
209             ch[2] = c == 'v' || c == '2' || c == 'a' || c == '3' || c == 'b';
210             printf("CodeBook YUV Channels active: %d, %d, %d\n", ch[0], ch[1], ch[2] );
211             break;
212         case 'i': //modify max classification bounds (max bound goes higher)
213         case 'o': //modify max classification bounds (max bound goes lower)
214         case 'k': //modify min classification bounds (min bound goes lower)
215         case 'l': //modify min classification bounds (min bound goes higher)
216             {
217             uchar* ptr = c == 'i' || c == 'o' ? model->modMax : model->modMin;
218             for(n=0; n<NCHANNELS; n++)
219             {
220                 if( ch[n] )
221                 {
222                     int v = ptr[n] + (c == 'i' || c == 'l' ? 1 : -1);
223                     ptr[n] = CV_CAST_8U(v);
224                 }
225                 printf("%d,", ptr[n]);
226             }
227             printf(" CodeBook %s Side\n", c == 'i' || c == 'o' ? "High" : "Low" );
228             }
229             break;
230         }
231     }           
232     
233     cvReleaseCapture( &capture );
234     cvDestroyWindow( "Raw" );
235     cvDestroyWindow( "ForegroundCodeBook");
236     cvDestroyWindow( "CodeBook_ConnectComp");
237     return 0;
238 }