近來,因為在項目中遇到跟蹤的難題,沒事翻看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;
}