Opencv4.5 KCF算法 示例

最近开始看一些目标跟踪的内容,下面是KCF的一个例子,数据集为地址Visual Tracker Benchmark

在使用KCF类时,数据为灰度图时需要根据要求设置参数,否则update函数报错。如Error: Bad argument (Matrix operand is an empty matrix.) in cv::checkOpe..

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
using namespace cv;

int main() {
  Rect2d roi;
  Mat frame;
  // 灰度图需要设置参数  不是灰度图可按照默认参数
  TrackerKCF::Params param;
  param.desc_pca = TrackerKCF::GRAY;
  param.compressed_size = 0x01;
  param.detect_thresh = 0.3;
  //参数设置结束
  Ptr tracker = TrackerKCF::create(param); 


  string frame_file = "D:/OTB/Car4/Car4/img/0%03d.jpg";
  VideoCapture Sequence(frame_file);


  Sequence >> frame;
  while (1) {
    char key = waitKey(1);
    if (key == 'a') // 按a键跳帧
    {
      Sequence >> frame;
    }
    if (key == 'e') // 按e键退出跳帧
    {
      break;
    }
    imshow("image", frame);
  }


  cv::destroyWindow("image");

  roi = selectROI("tracker", frame);

  if (roi.width == 0 || roi.height == 0)
    return 0;

    tracker->init(frame, roi);

  int ncnt = 0;
  printf("Start the tracking process\n");

  for (;;) {
    // get frame from the video
    Sequence >> frame;
    // stop the program if no more images
    if (frame.rows == 0 || frame.cols == 0) {
      cv::destroyWindow("tracker");
      break;
    }

    printf("frame cnt:%d\n",ncnt);
    ncnt++;
//    imwrite(str,frame);
//    continue;
    // update the tracking result
    tracker->update(frame, roi);
    // draw the tracked object
    rectangle(frame, roi, Scalar(255, 0, 0), 2, 1);
    // show image with the tracked object
    imshow("tracker", frame);
    // quit on ESC button
    if (char(waitKey(1)) == 'q') {
      cv::destroyWindow("tracker");
      break;
    }
  }
  return 0;
}
效果如下:

Opencv4.5 KCF算法 示例_第1张图片

你可能感兴趣的:(算法)