1 #include <opencv2/opencv.hpp>
11 using namespace cv::ml;
14 void get_svm_detector(const Ptr<SVM>& svm, vector< float > & hog_detector );
15 void convert_to_ml(const std::vector< cv::Mat > & train_samples, cv::Mat& trainData );
16 void load_images( const string & prefix, const string & filename, vector< Mat > & img_lst );
17 void sample_neg( const vector< Mat > & full_neg_lst, vector< Mat > & neg_lst, const Size & size );
18 Mat get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size );
19 void compute_hog( const vector< Mat > & img_lst, vector< Mat > & gradient_lst, const Size & size );
20 void train_svm( const vector< Mat > & gradient_lst, const vector< int > & labels );
21 void draw_locations( Mat & img, const vector< Rect > & locations, const Scalar & color );
22 void test_it( const Size & size );
24 void get_svm_detector(const Ptr<SVM>& svm, vector< float > & hog_detector )
26 // get the support vectors
27 Mat sv = svm->getSupportVectors();
28 const int sv_total = sv.rows;
29 // get the decision function
31 double rho = svm->getDecisionFunction(0, alpha, svidx);
33 CV_Assert( alpha.total() == 1 && svidx.total() == 1 && sv_total == 1 );
34 CV_Assert( (alpha.type() == CV_64F && alpha.at<double>(0) == 1.) ||
35 (alpha.type() == CV_32F && alpha.at<float>(0) == 1.f) );
36 CV_Assert( sv.type() == CV_32F );
39 hog_detector.resize(sv.cols + 1);
40 memcpy(&hog_detector[0], sv.ptr(), sv.cols*sizeof(hog_detector[0]));
41 hog_detector[sv.cols] = (float)-rho;
46 * Convert training/testing set to be used by OpenCV Machine Learning algorithms.
47 * TrainData is a matrix of size (#samples x max(#cols,#rows) per samples), in 32FC1.
48 * Transposition of samples are made if needed.
50 void convert_to_ml(const std::vector< cv::Mat > & train_samples, cv::Mat& trainData )
53 const int rows = (int)train_samples.size();
54 const int cols = (int)std::max( train_samples[0].cols, train_samples[0].rows );
55 cv::Mat tmp(1, cols, CV_32FC1); //< used for transposition if needed
56 trainData = cv::Mat(rows, cols, CV_32FC1 );
57 vector< Mat >::const_iterator itr = train_samples.begin();
58 vector< Mat >::const_iterator end = train_samples.end();
59 for( int i = 0 ; itr != end ; ++itr, ++i )
61 CV_Assert( itr->cols == 1 ||
65 transpose( *(itr), tmp );
66 tmp.copyTo( trainData.row( i ) );
68 else if( itr->rows == 1 )
70 itr->copyTo( trainData.row( i ) );
75 void load_images( const string & prefix, const string & filename, vector< Mat > & img_lst )
80 file.open( (prefix+filename).c_str() );
83 cerr << "Unable to open the list of images from " << filename << " filename." << endl;
87 bool end_of_parsing = false;
88 while( !end_of_parsing )
90 getline( file, line );
91 if( line == "" ) // no more file to read
93 end_of_parsing = true;
96 Mat img = imread( (prefix+line).c_str() ); // load the image
97 if( img.empty() ) // invalid image, just skip it.
100 imshow( "image", img );
103 img_lst.push_back( img.clone() );
107 void sample_neg( const vector< Mat > & full_neg_lst, vector< Mat > & neg_lst, const Size & size )
110 box.width = size.width;
111 box.height = size.height;
113 const int size_x = box.width;
114 const int size_y = box.height;
116 srand( (unsigned int)time( NULL ) );
118 vector< Mat >::const_iterator img = full_neg_lst.begin();
119 vector< Mat >::const_iterator end = full_neg_lst.end();
120 for( ; img != end ; ++img )
122 box.x = rand() % (img->cols - size_x);
123 box.y = rand() % (img->rows - size_y);
124 Mat roi = (*img)(box);
125 neg_lst.push_back( roi.clone() );
127 imshow( "img", roi.clone() );
133 // From http://www.juergenwiki.de/work/wiki/doku.php?id=public:hog_descriptor_computation_and_visualization
134 Mat get_hogdescriptor_visu(const Mat& color_origImg, vector<float>& descriptorValues, const Size & size )
136 const int DIMX = size.width;
137 const int DIMY = size.height;
140 resize(color_origImg, visu, Size( (int)(color_origImg.cols*zoomFac), (int)(color_origImg.rows*zoomFac) ) );
143 int gradientBinSize = 9;
144 float radRangeForOneBin = (float)(CV_PI/(float)gradientBinSize); // dividing 180° into 9 bins, how large (in rad) is one bin?
146 // prepare data structure: 9 orientation / gradient strenghts for each cell
147 int cells_in_x_dir = DIMX / cellSize;
148 int cells_in_y_dir = DIMY / cellSize;
149 float*** gradientStrengths = new float**[cells_in_y_dir];
150 int** cellUpdateCounter = new int*[cells_in_y_dir];
151 for (int y=0; y<cells_in_y_dir; y++)
153 gradientStrengths[y] = new float*[cells_in_x_dir];
154 cellUpdateCounter[y] = new int[cells_in_x_dir];
155 for (int x=0; x<cells_in_x_dir; x++)
157 gradientStrengths[y][x] = new float[gradientBinSize];
158 cellUpdateCounter[y][x] = 0;
160 for (int bin=0; bin<gradientBinSize; bin++)
161 gradientStrengths[y][x][bin] = 0.0;
165 // nr of blocks = nr of cells - 1
166 // since there is a new block on each cell (overlapping blocks!) but the last one
167 int blocks_in_x_dir = cells_in_x_dir - 1;
168 int blocks_in_y_dir = cells_in_y_dir - 1;
170 // compute gradient strengths per cell
171 int descriptorDataIdx = 0;
175 for (int blockx=0; blockx<blocks_in_x_dir; blockx++)
177 for (int blocky=0; blocky<blocks_in_y_dir; blocky++)
179 // 4 cells per block ...
180 for (int cellNr=0; cellNr<4; cellNr++)
182 // compute corresponding cell nr
185 if (cellNr==1) celly++;
186 if (cellNr==2) cellx++;
193 for (int bin=0; bin<gradientBinSize; bin++)
195 float gradientStrength = descriptorValues[ descriptorDataIdx ];
198 gradientStrengths[celly][cellx][bin] += gradientStrength;
203 // note: overlapping blocks lead to multiple updates of this sum!
204 // we therefore keep track how often a cell was updated,
205 // to compute average gradient strengths
206 cellUpdateCounter[celly][cellx]++;
211 } // for (all block x pos)
212 } // for (all block y pos)
215 // compute average gradient strengths
216 for (celly=0; celly<cells_in_y_dir; celly++)
218 for (cellx=0; cellx<cells_in_x_dir; cellx++)
221 float NrUpdatesForThisCell = (float)cellUpdateCounter[celly][cellx];
223 // compute average gradient strenghts for each gradient bin direction
224 for (int bin=0; bin<gradientBinSize; bin++)
226 gradientStrengths[celly][cellx][bin] /= NrUpdatesForThisCell;
232 for (celly=0; celly<cells_in_y_dir; celly++)
234 for (cellx=0; cellx<cells_in_x_dir; cellx++)
236 int drawX = cellx * cellSize;
237 int drawY = celly * cellSize;
239 int mx = drawX + cellSize/2;
240 int my = drawY + cellSize/2;
242 rectangle(visu, Point((int)(drawX*zoomFac), (int)(drawY*zoomFac)), Point((int)((drawX+cellSize)*zoomFac), (int)((drawY+cellSize)*zoomFac)), Scalar(100,100,100), 1);
244 // draw in each cell all 9 gradient strengths
245 for (int bin=0; bin<gradientBinSize; bin++)
247 float currentGradStrength = gradientStrengths[celly][cellx][bin];
250 if (currentGradStrength==0)
253 float currRad = bin * radRangeForOneBin + radRangeForOneBin/2;
255 float dirVecX = cos( currRad );
256 float dirVecY = sin( currRad );
257 float maxVecLen = (float)(cellSize/2.f);
258 float scale = 2.5; // just a visualization scale, to see the lines better
260 // compute line coordinates
261 float x1 = mx - dirVecX * currentGradStrength * maxVecLen * scale;
262 float y1 = my - dirVecY * currentGradStrength * maxVecLen * scale;
263 float x2 = mx + dirVecX * currentGradStrength * maxVecLen * scale;
264 float y2 = my + dirVecY * currentGradStrength * maxVecLen * scale;
266 // draw gradient visualization
267 line(visu, Point((int)(x1*zoomFac),(int)(y1*zoomFac)), Point((int)(x2*zoomFac),(int)(y2*zoomFac)), Scalar(0,255,0), 1);
275 // don't forget to free memory allocated by helper data structures!
276 for (int y=0; y<cells_in_y_dir; y++)
278 for (int x=0; x<cells_in_x_dir; x++)
280 delete[] gradientStrengths[y][x];
282 delete[] gradientStrengths[y];
283 delete[] cellUpdateCounter[y];
285 delete[] gradientStrengths;
286 delete[] cellUpdateCounter;
290 } // get_hogdescriptor_visu
292 void compute_hog( const vector< Mat > & img_lst, vector< Mat > & gradient_lst, const Size & size )
297 vector< Point > location;
298 vector< float > descriptors;
300 vector< Mat >::const_iterator img = img_lst.begin();
301 vector< Mat >::const_iterator end = img_lst.end();
302 for( ; img != end ; ++img )
304 cvtColor( *img, gray, COLOR_BGR2GRAY );
305 hog.compute( gray, descriptors, Size( 8, 8 ), Size( 0, 0 ), location );
306 gradient_lst.push_back( Mat( descriptors ).clone() );
308 imshow( "gradient", get_hogdescriptor_visu( img->clone(), descriptors, size ) );
314 void train_svm( const vector< Mat > & gradient_lst, const vector< int > & labels )
316 /* Default values to train SVM */
320 params.termCrit.epsilon = 1e-3;
322 params.kernelType = SVM::LINEAR;
324 params.p = 0.1; // for EPSILON_SVR, epsilon in loss function?
325 params.C = 0.01; // From paper, soft classifier
326 params.svmType = SVM::EPS_SVR; // C_SVC; // EPSILON_SVR; // may be also NU_SVR; // do regression task
329 convert_to_ml( gradient_lst, train_data );
331 clog << "Start training...";
332 Ptr<SVM> svm = StatModel::train<SVM>(train_data, ROW_SAMPLE, Mat(labels), params);
333 clog << "...[done]" << endl;
335 svm->save( "my_people_detector.yml" );
338 void draw_locations( Mat & img, const vector< Rect > & locations, const Scalar & color )
340 if( !locations.empty() )
342 vector< Rect >::const_iterator loc = locations.begin();
343 vector< Rect >::const_iterator end = locations.end();
344 for( ; loc != end ; ++loc )
346 rectangle( img, *loc, color, 2 );
351 void test_it( const Size & size )
354 Scalar reference( 0, 255, 0 );
355 Scalar trained( 0, 0, 255 );
359 HOGDescriptor my_hog;
360 my_hog.winSize = size;
362 vector< Rect > locations;
364 // Load the trained SVM.
365 svm = StatModel::load<SVM>( "my_people_detector.yml" );
366 // Set the trained svm to my_hog
367 vector< float > hog_detector;
368 get_svm_detector( svm, hog_detector );
369 my_hog.setSVMDetector( hog_detector );
370 // Set the people detector.
371 hog.setSVMDetector( hog.getDefaultPeopleDetector() );
374 if( !video.isOpened() )
376 cerr << "Unable to open the device 0" << endl;
380 bool end_of_process = false;
381 while( !end_of_process )
390 hog.detectMultiScale( img, locations );
391 draw_locations( draw, locations, reference );
394 my_hog.detectMultiScale( img, locations );
395 draw_locations( draw, locations, trained );
397 imshow( "Video", draw );
398 key = (char)waitKey( 10 );
400 end_of_process = true;
404 int main( int argc, char** argv )
408 cout << "Wrong number of parameters." << endl
409 << "Usage: " << argv[0] << " pos_dir pos.lst neg_dir neg.lst" << endl
410 << "example: " << argv[0] << " /INRIA_dataset/ Train/pos.lst /INRIA_dataset/ Train/neg.lst" << endl;
413 vector< Mat > pos_lst;
414 vector< Mat > full_neg_lst;
415 vector< Mat > neg_lst;
416 vector< Mat > gradient_lst;
417 vector< int > labels;
419 load_images( argv[1], argv[2], pos_lst );
420 labels.assign( pos_lst.size(), +1 );
421 const unsigned int old = (unsigned int)labels.size();
422 load_images( argv[3], argv[4], full_neg_lst );
423 sample_neg( full_neg_lst, neg_lst, Size( 96,160 ) );
424 labels.insert( labels.end(), neg_lst.size(), -1 );
425 CV_Assert( old < labels.size() );
427 compute_hog( pos_lst, gradient_lst, Size( 96, 160 ) );
428 compute_hog( neg_lst, gradient_lst, Size( 96, 160 ) );
430 train_svm( gradient_lst, labels );
432 test_it( Size( 96, 160 ) ); // change with your parameters