OPenCV支持8种算法的目标跟踪,根据视频特点选择不同的算法。
8种算法的实现步骤:
1.创建类对象: create()
2.对象初始化: init() 初始帧图像、跟踪目标的初始矩形框位置
此处用Rect2d 设置矩形框位置,或者手动选取矩形框
3.while循环 对视频进行逐帧处理
update(,) 矩形框在下一帧的位置 (新一帧图像,目标矩形框在新一帧图像上的位置)
update实现所有跟踪计算工作
返回值:0 表示丢了 1表示OK
上代码:
string trackerTypes[8] = { "BOOSTING", "MIL", "KCF", "TLD", "MEDIANFLOW", "GOTURN", "CSRT", "MOSSE" };
// vector trackerTypes(types, std::end(types));
// 1.创建:Create a tracker
string trackerType = trackerTypes[6];
Ptr tracker;
if (trackerType == "BOOSTING")
tracker = TrackerBoosting::create();
else if (trackerType == "MIL")
tracker = TrackerMIL::create();
else if (trackerType == "KCF")
tracker = TrackerKCF::create();
else if (trackerType == "TLD")
tracker = TrackerTLD::create();
else if (trackerType == "MEDIANFLOW")
tracker = TrackerMedianFlow::create();
else if (trackerType == "GOTURN")
tracker = TrackerGOTURN::create();
else if (trackerType == "CSRT")
tracker = TrackerCSRT::create();
else if (trackerType == "MOSSE")
tracker = TrackerMOSSE::create();
else
{
cout << "INVALID TRACKER SPECIFIED" << endl;
cout << "Available Trackers are :" << endl;
for (int i = 0; i < sizeof(trackerTypes) / sizeof(trackerTypes[0]); i++)
cout << i << " : " << trackerTypes[i] << endl;
return ;
}
VideoCapture video("../hockey.mp4");
if (!video.isOpened())
{
cout << "Could not read video file" << endl;
return ;
}
Mat frame;
bool ok = video.read(frame);
Rect2d bbox(204, 131, 97, 222);
cout << "Initial bounding box : " << bbox << endl;
rectangle(frame, bbox, Scalar(255, 0, 0), 2, 1);
imshow("Tracking", frame);
//2.初始化
tracker->init(frame, bbox);
//3.每帧操作更新
while (video.read(frame))
{
double timer = (double)getTickCount();
bool ok = tracker->update(frame, bbox);
float fps = getTickFrequency() / ((double)getTickCount() - timer);
if (ok)
{
// Tracking success : Draw the tracked object
rectangle(frame, bbox, Scalar(255, 0, 0), 2, 1);
}
else
{
// Tracking failure detected.
putText(frame, "Tracking failure detected", Point(100, 80), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(0, 0, 255), 2);
}
putText(frame, trackerType + " Tracker", Point(100, 20), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50, 170, 50), 2);
putText(frame, "FPS : " + SSTR(int(fps)), Point(100, 50), FONT_HERSHEY_SIMPLEX, 0.75, Scalar(50, 170, 50), 2);
imshow("Tracking", frame);
// Exit if ESC pressed.
int k = waitKey(1);
if (k == 27)
{
break;
}
}