import time
import cv2
import sys

tracker = cv2.TrackerCSRT_create()
video = cv2.VideoCapture('./01.mp4')
if not video.isOpened():
    print("Could not open video")
    sys.exit()

i=0
while True:
    ok, frame = video.read()

    if ok is None or frame is None:
        break
    else:
        i+=1
        frame = cv2.resize(frame, (960, 540))

    if i==1:
        box = cv2.selectROI("Frame", frame, fromCenter=False,showCrosshair=True)
        ok = tracker.init(frame, box)
        if not ok:
            continue
    success, bbox = tracker.update(frame)

    if success:
        p1 = (int(bbox[0]), int(bbox[1]))
        p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
        cv2.rectangle(frame, p1, p2, (255, 0, 0), 2, 1)
    else:
        cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF


video.release()
cv2.destroyAllWindows()

为啥要做个记录,是因为4.5版本的opencv中使用csrt跟踪器的例子实在不好找.

https://github.com/abhiWriteCode/Object-Tracking这位朋友写的opencv常用跟踪器在4.5上行不通,官方给的是c++的例子,我是好不容易在https://www.pythonheidong.com/blog/article/500776/bd3bf022cfc1a6830d1f/ python3基于opencv的目标追踪,用KCF或者CSRT这个博客上找到了个东西,直接运行它的程序不能行,自己尝试上面两个博客和官方文档,改了写才形成上面程序

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐