Opencv-python 视频跟踪

参考:https://blog.csdn.net/weixin_45875105/article/details/111311029
在这里插入图片描述

"""
    视频跟踪
"""
import sys
import cv2

def main():
    # 1.创建追踪对象
    # tracker = cv2.TrackerBoosting_create()
    # tracker = cv2.TrackerMIL_create()
    tracker = cv2.TrackerKCF_create()
    # tracker = cv2.TrackerTLD_create()
    # tracker = cv2.TrackerCSRT_create()
    # tracker = cv2.TrackerGOTURN_create()
    # tracker = cv2.TrackerMedianFlow_create()

    # 2.读取视频
    video = cv2.VideoCapture("jt1.mp4")

    # 视频读取失败
    if not video.isOpened():
        print("Could not open video")
        sys.exit()

    # 读取第一帧
    ok, frame = video.read()
    if not ok:
        print('Cannot read video file')
        sys.exit()

    # 3.设置跟踪ROI区域
    # 默认跟踪区域
    # bbox = (287, 23, 86, 320)

    # Uncomment the line below to select a different bounding box
    bbox = cv2.selectROI(frame, False)

    # 初始化跟踪对象
    ok = tracker.init(frame, bbox)

    # 4.循环读取视频并跟踪
    while True:
        # 读取视频图片
        ok, frame = video.read()
        if not ok:
            break

        # 开始计时
        timer = cv2.getTickCount()

        # 更新跟踪结果
        ok, bbox = tracker.update(frame)

        # 计算帧率
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)

        # 绘制结果
        if ok:
            # 跟踪失败
            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.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)
        cv2.imshow("Tracking", frame)

        # 退出
        k = cv2.waitKey(1) & 0xff
        if k == 27:
            break

if __name__ == '__main__':
    main()


选定目标,然后按空格

猜你喜欢

转载自blog.csdn.net/qq_21237549/article/details/121256047