opencv3使用KCF或TLD跟踪

TLD作者使用的版本是opencv2.*,在3.*上编译会报一堆问题,好在OpenTLD_OpenCV3已经给出了解决方案,不过自从opencv3.0开始就在contrib模块中自带了tracking模块,因此自己编译这个模块后使用这些算法还是很方便的.

#include 
#include 
#include 

using namespace std;
using namespace cv;

int main( int argc, char** argv ){
    
    String video_name = "video.avi";
    VideoCapture cap(video_name);
    if( !cap.isOpened() )
    {
        cout << "***Could not initialize capturing...***\n";
        return -1;
    }
    cv::Ptr tracker=cv::TrackerKCF::create();
    if (!tracker)
    {
        cout << "***Error in the instantiation of the tracker...***\n";
        return -1;
    }
    
    Mat frame;
    namedWindow( "Tracking API", 1 );
    Mat image;
    Rect2d boundingBox;
    bool paused = false;
    
    cap >> frame;
    frame.copyTo( image );
    imshow( "Tracking API", image );
    waitKey( 1 );
    boundingBox = selectROI("Tracking API", image,false,false);
    bool initialized = false;
    int frameCounter = 0;
    int64 timeTotal = 0;
    
    for ( ;; )
    {
        if( !paused )
        {
            if(initialized){
                cap >> frame;
                if(frame.empty()){
                    break;
                }
                frame.copyTo( image );
            }
            
            if( !initialized )
            {
                //initializes the tracker
                if( !tracker->init( frame, boundingBox ) )
                {
                    cout << "***Could not initialize tracker...***\n";
                    return -1;
                }
                initialized = true;
            }
            else if( initialized )
            {
                int64 frameTime = getTickCount();
                //updates the tracker
                if( tracker->update( frame, boundingBox ) )
                {
                    rectangle( image, boundingBox, Scalar( 255, 0, 0 ), 2, 1 );
                }
                frameTime = getTickCount() - frameTime;
                timeTotal += frameTime;
            }
            imshow( "Tracking API", image );
            frameCounter++;
        }
        
        char c = (char) waitKey( 1 );
        if( c == 'q' )
            break;
        if( c == 'p' )
            paused = !paused;
    }
    
    double s = frameCounter / (timeTotal / getTickFrequency());
    printf("FPS: %f\n", s);
    
    return 0;
}

 

你可能感兴趣的:(CV)