OpenCV里基于特征跟踪类FeatureTracker分析

近来,因为在项目中遇到跟踪的难题,没事翻看opencv2.4.5里的相关源码查阅,偶然发现在opencv的contrib文件夹下实现了多种目标跟踪算法,包括featuretracker、hybridtracker和detection_based_tracker等。由于是改代码是放置于contrib文件夹下,所以不能直接调用(除非自己重新编译)。对源代码进行了提取,单还是有错,欢迎同道之人下载下来一起找错,相互交流。

首先附上main函数里的相关代码:

Rect box(0,0,0,0);
bool drawing_box = false;
bool gotBB = false;
string video ="E:\\Video\\test1.avi";

//bounding box mouse callback
void mouseHandler(int event, int x, int y, int flags, void *param)
{
 switch( event )
 {
  case CV_EVENT_MOUSEMOVE:
  if (drawing_box)
  {
    box.width = x-box.x;
    box.height = y-box.y;
  }
  break;
  case CV_EVENT_LBUTTONDOWN:
  drawing_box = true;
  box = Rect( x, y, 0, 0 );
  break;
  case CV_EVENT_LBUTTONUP:
  drawing_box = false;
  if( box.width < 0 )
  {
    box.x += box.width;
    box.width *= -1;
  }
  if( box.height < 0 )
  {
    box.y += box.height;
    box.height *= -1;
  }
  gotBB = true;
  break;
 }
}

void drawBox(Mat& image, CvRect box, Scalar color, int thick)
{
 rectangle( image, cvPoint(box.x, box.y), cvPoint(box.x+box.width,box.y+box.height),color, thick);
}

int main(int argc, char * argv[])

 VideoCapture capture;
 Mat frame;

CvFeatureTrackerParams params;
 params.feature_type = 0;
 params.window_size = 0;
 FeatureTraker tracker(params);

//FeatureTraker tracker; 
 
 capture.open(video); 
 if (!capture.isOpened())
 {
  cout << " video file open failed..." << endl;
  return 1;
 }
 capture >> frame; 
 if ( frame.empty())
 {
  cout << " get frame error..." << endl;
  return 1;
 }
 resize( frame, frame, Size(352,288)); 
 //Register mouse callback to draw the bounding box
 namedWindow("fetureTracker",CV_WINDOW_AUTOSIZE);
 setMouseCallback( "fetureTracker", mouseHandler, NULL );
 
GETBOUNDINGBOX:
 while(!gotBB)
 {   
  drawBox(frame,box,Scalar(0,255,0),2);
  imshow("fetureTracker", frame);
  if ( waitKey(33) == 'q')
   return 0; 
 }
 if (box.area()<160)
 {
  cout << "Bounding box too small, try again." << endl;
  gotBB = false;
  goto GETBOUNDINGBOX;
 } 
 //Remove callback
 setMouseCallback( "fetureTracker", NULL, NULL );
 printf("Initial Bounding Box = x:%d y:%d h:%d w:%d\n",box.x,box.y,box.width,box.height);
 
 tracker.newTrackingWindow(frame,box);
 Point2f pt = tracker.getTrackingCenter();
 circle(frame,pt,5,Scalar(0,0,255),2);

for (;;)
 {
  capture>>frame;
  resize( frame, frame, Size(352,288)); 
  tracker.updateTrackingWindow(frame);
  pt = tracker.getTrackingCenter();
  circle(frame,pt,5,Scalar(0,0,255),2);
  drawBox(frame,box,Scalar(0,255,0),2);
  imshow("fetureTracker", frame);
  if ( waitKey(33) == 'q')
   break;
 } 

return 0;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/9be85ba1e1b37a8b5e17960b0d9cfa18.html