opencv目标追踪c++
时间: 2023-12-03 08:40:59 浏览: 96
以下是使用Tracker实现简单目标跟踪的C++代码示例:
```c++
#include <opencv2/opencv.hpp>
#include <opencv2/tracking.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char **argv)
{
// 读取视频文件
VideoCapture cap("test.mp4");
// 检查视频是否成功打开
if (!cap.isOpened())
{
cout << "Error opening video file" << endl;
return -1;
}
// 选择跟踪算法
string trackerType = "KCF";
Ptr<Tracker> tracker;
if (trackerType == "KCF")
tracker = TrackerKCF::create();
else if (trackerType == "MIL")
tracker = TrackerMIL::create();
else if (trackerType == "BOOSTING")
tracker = TrackerBoosting::create();
else if (trackerType == "TLD")
tracker = TrackerTLD::create();
else if (trackerType == "MEDIANFLOW")
tracker = TrackerMedianFlow::create();
else if (trackerType == "GOTURN")
tracker = TrackerGOTURN::create();
else
{
cout << "Invalid tracker type" << endl;
return -1;
}
// 选择跟踪目标
Rect2d bbox(287, 23, 86, 320);
// 读取第一帧图像
Mat frame;
cap >> frame;
// 初始化跟踪器
tracker->init(frame, bbox);
// 跟踪目标
while (cap.read(frame))
{
// 更新跟踪器
bool ok = tracker->update(frame, bbox);
// 绘制跟踪框
if (ok)
rectangle(frame, bbox, Scalar(0, 255, 0), 2, 1);
else
putText(frame, "Tracking failure detected", Point(100, 80), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2);
// 显示图像
imshow("Tracking", frame);
// 按下ESC键退出
if (waitKey(1) == 27)
break;
}
return 0;
}
```
阅读全文