OpenCV Cascade Classifier Training

This training is based on three stages and i listed all possible steps below.

  1. Downloading Tools and preparation :
    • Download and install openCV . It provides important tools for image preparation and training. Download from here and for installation steps visit my previous article from here
    • Download Haar Training material from here. Very useful tools and utilities for image preparation
    • Organize your +ve (must contains object you want to recognize and for complex object number of images must be more than 1000) and -ve images (at least 2000 / more) also known as background or samples images
  2. Training :
    • In my case i collected 1000 +ve images containing object and 2000 –ve images (without object).
    • List all –ve files in a neg.txt document. if your data set is big,  you can use DOS commands to list all images in txt file
    • in my case my working directory is e:/opencv/development/images. Go into your working directory and run DOS command
    • dir /b >neg.txt
    • To add full path for each -ve image name. create batch file as given below
    • for /F "delims=" %%j in (neg.txt) do echo.E:\opencv\development\%%j >>negNew.txt
      • Run your batch file and it will create a negNew.txt file with full path of -ve images
    • Next step is to crop +ve images using Objectmake.exe and create an info.txt file
        • Copy step2 from downloaded folder to your working directory. Put all +ve files in your rawdata directory. Simply execute Objectmake.exe file and start marking object of your interest in your +ve images
        • Once you are done with this step. Move info.txt file to your working directory home.
        • Now add absolute path for each +ve image in info.txt.
      for /F "delims=" %%j in (info.txt) do echo.E:\opencv\development\step2\rawdata\%%j >>infoNew.txt
    • Generated Vector file using createSample classic tool of OpenCV
        • create batch file and execute it. Batch file contains following command
      createsamples.exe -info infoNew.txt -vec samples.vec -num 137 -w 50 -h 35 PAUSE
      • you can change parameters according to your requirement
    • Verify vector file and browsed all cropped images
      opencv_createsamples.exe -vec samples.vec -w 50 -h 35 -show
      • if your vector file is correctly created. it will display all cropped images one by one
    • Initiate a Haar Cascade Classifier training to get cascade.xml trained file and is generated successfully. It takes lot of time depends upon your data set. To initiate this process create batch file with following command
        • create classifier directory in your working folder
      opencv_traincascade.exe -data classifier/ -vec samples.vec -bg negNew.txt -numstages 50 -minHitRate 0.999 -numPos 137 -numNeg 276 -maxFalseAlarmRate 0.5 -w 50 -h 35 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024
      • You will get cascade.xml file which is available in classifier directory. You can delete all other file. They are not required.
  3. Detection :
    1. Use opencv code for object detection. Have a look at code. Code is taken from the openCV tutorials. Check original code here
      #include "opencv2/objdetect/objdetect.hpp"
      #include "opencv2/highgui/highgui.hpp"
      #include "opencv2/imgproc/imgproc.hpp"
      #include <iostream>
      #include <stdio.h>
      
      using namespace std;
      using namespace cv;
      
      void detectAndDisplay( Mat frame );
      String cascade_name = "cascade.xml";
      CascadeClassifier cascade;
      
      string window_name = "Capture - Human detection";
      RNG rng(12345);
      int main( int argc, const char** argv )
      {
      CvCapture* capture;
      Mat frame;
      
      if( !cascade.load(cascade_name ) ) { printf("--(!)Error loading\n"); return -1; }; 
      capture = cvCaptureFromCAM( 0 ); 
      // capture = cvCaptureFromAVI("test.avi"); 
      
      if( capture ) { 
      while( true ) { 
      
      frame = cvQueryFrame( capture ); 
      
      if( !frame.empty() ) 
      { detectAndDisplay( frame ); } 
      else { printf(" --(!) No captured frame -- Break!"); 
      break; 
      }
      
      int c = waitKey(10); 
      if( (char)c == 'c' ) { break; 
      } } } 
      return 0; }
      
      
      void detectAndDisplay( Mat frame )
      {
        std::vector faces;
        Mat frame_gray;
      
        cvtColor( frame, frame_gray, CV_BGR2GRAY );
        equalizeHist( frame_gray, frame_gray );
      
        
        face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(50, 60) );
      
        for( size_t i = 0; i < faces.size(); i++ )
        {
      
      	  Rect r = faces[i];
      	              r.x += cvRound(r.width*0.1);
      	  	    r.width = cvRound(r.width*0.8);
      	  	    r.y += cvRound(r.height*0.06);
      	  	    r.height = cvRound(r.height*0.9);
      	  	    rectangle(frame, r.tl(), r.br(), cv::Scalar(0,255,0), 2);
      
        }
        imshow( window_name, frame );
       }
      
     

Useful Tutorials

  1. http://vgl-ait.org/cvwiki/doku.php?id=opencv:tutorial:haartraining
  2. http://docs.opencv.org/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html
  3. http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html
  4. http://www.tectute.com/2011/06/opencv-haartraining.html
  5. http://note.sonots.com/SciSoftware/haartraining.html

Watch this video for further details : https://youtu.be/x0HU016X8J4

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.