brokensidewalkfarm

Crash Course through CAMShift

Apr 19th, 2011
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.27 KB | None | 0 0
  1. #include <opencv2/video/tracking.hpp>
  2. #include <opencv2/imgproc/imgproc.hpp>
  3. #include <opencv2/highgui/highgui.hpp>
  4.  
  5. #include <iostream>
  6. #include <ctype.h>
  7. //#include <cstdlib>
  8. //#include <cmath>
  9. //#include <string>
  10.  
  11. using namespace cv;
  12. using namespace std;
  13.  
  14. void help()
  15. {
  16.     cout << "\nThis is a demo that shows mean-shift based tracking\n"
  17.     <<   "You select a color objects such as your face and it tracks it.\n"
  18.     <<   "This reads from video camera (0 by default, or the camera number the user enters\n"
  19.     << "Call:\n"
  20.     << "\n./camshiftdemo [camera number]"
  21.     << "\n" << endl;
  22.    
  23.     cout << "\n\nHot keys: \n"
  24.     "\tESC - quit the program\n"
  25.     "\tc - stop the tracking\n"
  26.     "\tb - switch to/from backprojection view\n"
  27.     "\th - show/hide object histogram\n"
  28.     "To initialize tracking, select the object with mouse\n" << endl;
  29. }
  30.  
  31. Mat image;
  32.  
  33. bool backprojMode = false;
  34. bool selectObject = false;
  35. int trackObject = 0;
  36. bool showHist = true;
  37. Point origin;
  38. Rect selection;
  39. int vmin = 10, vmax = 256, smin = 30;
  40.  
  41. void onMouse( int event, int x, int y, int, void* )
  42. {
  43.     if( selectObject )
  44.     {
  45.         selection.x = MIN(x, origin.x);
  46.         selection.y = MIN(y, origin.y);
  47.         selection.width = abs((int)(x-origin.x));
  48.         selection.height = abs((int)(y - origin.y));
  49.        
  50.         selection &= Rect(0, 0, image.cols, image.rows);
  51.     }
  52.    
  53.     switch( event )
  54.     {
  55.         case CV_EVENT_LBUTTONDOWN:
  56.             origin = Point(x,y);
  57.             selection = Rect(x,y,0,0);
  58.             selectObject = true;
  59.             break;
  60.         case CV_EVENT_LBUTTONUP:
  61.             selectObject = false;
  62.             if( selection.width > 0 && selection.height > 0 )
  63.                 trackObject = -1;
  64.             break;
  65.     }
  66. }
  67.  
  68.  
  69.  
  70. int main( int argc, char** argv )
  71. {
  72.     VideoCapture cap;
  73.     Rect trackWindow;
  74.     RotatedRect trackBox;
  75.     int hsize = 16;
  76.     float hranges[] = {0,180};
  77.     const float* phranges = hranges;
  78.    
  79.     if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))
  80.         cap.open(argc == 2 ? argv[1][0] - '0' : 0);
  81.     else if( argc == 2 )
  82.         cap.open(argv[1]);
  83.    
  84.     if( !cap.isOpened() )
  85.     {
  86.         help();
  87.         cout << "***Could not initialize capturing...***\n";
  88.         return 0;
  89.     }
  90.    
  91.     help();
  92.    
  93.     namedWindow( "Histogram", 1 );
  94.     namedWindow( "CamShift Demo", 1 );
  95.     setMouseCallback( "CamShift Demo", onMouse, 0 );
  96.     createTrackbar( "Vmin", "CamShift Demo", &vmin, 256, 0 );
  97.     createTrackbar( "Vmax", "CamShift Demo", &vmax, 256, 0 );
  98.     createTrackbar( "Smin", "CamShift Demo", &smin, 256, 0 );
  99.    
  100.     Mat hsv, hue, mask, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
  101.    
  102.     for(;;)
  103.     {
  104.         Mat frame;
  105.         cap >> frame;
  106.         if( frame.empty() )
  107.             break;
  108.        
  109.         frame.copyTo(image);
  110.         cvtColor(image, hsv, CV_BGR2HSV);
  111.        
  112.         if( trackObject )
  113.         {
  114.             int _vmin = vmin, _vmax = vmax;
  115.            
  116.             inRange(hsv, Scalar(0, smin, MIN(_vmin,_vmax)),
  117.                     Scalar(180, 256, MAX(_vmin, _vmax)), mask);
  118.             int ch[] = {0, 0};
  119.             hue.create(hsv.size(), hsv.depth());
  120.             mixChannels(&hsv, 1, &hue, 1, ch, 1);
  121.            
  122.             if( trackObject < 0 )
  123.             {
  124.                 Mat roi(hue, selection), maskroi(mask, selection);
  125.                 calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
  126.                 normalize(hist, hist, 0, 255, CV_MINMAX);
  127.                
  128.                 trackWindow = selection;
  129.                 trackObject = 1;
  130.                
  131.                 histimg = Scalar::all(0);
  132.                 int binW = histimg.cols / hsize;
  133.                 Mat buf(1, hsize, CV_8UC3);
  134.                 for( int i = 0; i < hsize; i++ )
  135.                     buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180./hsize), 255, 255);
  136.                 cvtColor(buf, buf, CV_HSV2BGR);
  137.                
  138.                 for( int i = 0; i < hsize; i++ )
  139.                 {
  140.                     int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows/255);
  141.                     rectangle( histimg, Point(i*binW,histimg.rows),
  142.                               Point((i+1)*binW,histimg.rows - val),
  143.                               Scalar(buf.at<Vec3b>(i)), -1, 8 );
  144.                 }
  145.             }
  146.            
  147.             calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
  148.             backproj &= mask;
  149.             RotatedRect trackBox = CamShift(backproj, trackWindow,
  150.                                             TermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 ));
  151.            
  152.             if( backprojMode )
  153.                 cvtColor( backproj, image, CV_GRAY2BGR );
  154.             ellipse( image, trackBox, Scalar(0,0,255), 3, CV_AA );
  155.         }
  156.        
  157.         if( selectObject && selection.width > 0 && selection.height > 0 )
  158.         {
  159.             Mat roi(image, selection);
  160.             bitwise_not(roi, roi);
  161.         }
  162.        
  163.         imshow( "CamShift Demo", image );
  164.         imshow( "Histogram", histimg );
  165.        
  166.         char c = (char)waitKey(10);
  167.         if( c == 27 )
  168.             break;
  169.         switch(c)
  170.         {
  171.             case 'b':
  172.                 backprojMode = !backprojMode;
  173.                 break;
  174.             case 'c':
  175.                 trackObject = 0;
  176.                 histimg = Scalar::all(0);
  177.                 break;
  178.             case 'h':
  179.                 showHist = !showHist;
  180.                 if( !showHist )
  181.                     destroyWindow( "Histogram" );
  182.                 else
  183.                     namedWindow( "Histogram", 1 );
  184.                 break;
  185.             default:
  186.                 ;
  187.         }
  188.     }
  189.    
  190.     return 0;
  191. }
Advertisement
Add Comment
Please, Sign In to add comment