opencv实现目标跟踪及视频转存

创建跟踪器

def createTypeTracker(trackerType):
读取视频第一帧,选择跟踪的目标

读第一帧。

ok, frame = video.read()

选择边界框

bbox = cv2.selectROI(frame, False)
初始化跟踪器
tracker_type = ‘MIL’
tracker = createTypeTracker(tracker_type)

用第一帧和包围框初始化跟踪器

ok = tracker.init(frame, bbox)
随着视频进行更新跟踪

更新跟踪器

ok, bbox = tracker.update(frame)

完整代码如下:

import cv2
import sys
import numpy as np

# 创建一个跟踪器,algorithm: KCF、CSRT、DaSiamRPN、GOTURM、MIL
trackerTypes = ['BOOSTING', 'MIL', 'KCF', 'TLD', 'MEDIANFLOW', 'GOTURN', 'MOSSE', 'CSRT']

def createTypeTracker(trackerType):
    if trackerType == trackerTypes[0]:
        tracker = cv2.legacy.TrackerBoosting_create()
    elif trackerType == trackerTypes[1]:
        tracker = cv2.TrackerMIL_create()
    elif trackerType == trackerTypes[2]:
        tracker = cv2.legacy.TrackerKCF_create()
    elif trackerType == trackerTypes[3]:
        tracker = cv2.legacy.TrackerTLD_create()
    elif trackerType == trackerTypes[4]:
        tracker = cv2.legacy.TrackerMedianFlow_create()
    elif trackerType == trackerTypes[5]:  # 暂时存在问题
        tracker = cv2.TrackerGOTURN_create()
    elif trackerType == trackerTypes[6]:
        tracker = cv2.legacy.TrackerMOSSE_create()
    elif trackerType == trackerTypes[7]:
        tracker = cv2.legacy.TrackerCSRT_create()
    else:
        tracker = None

    return tracker


videoPth = 'D:/workspace_all/pyCharm/BicycleTrackerByOpenCV/video2.mp4'

if __name__ == '__main__':
    # 经测试CSRT效果最好
    tracker_type = 'CSRT'
    tracker = createTypeTracker(tracker_type)
    # 读取视频
    video = cv2.VideoCapture(videoPth)
    #fps = video.get(cv2.CAP_PROP_FPS)

    # 用于展示
    cv2.namedWindow("test", 0)
    cv2.resizeWindow("test", 1200, 900)  # 设置窗口的长和宽

    # 获取视频的帧率和尺寸
    fps = video.get(cv2.CAP_PROP_FPS)
    width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    # 保存跟踪视频
    output = cv2.VideoWriter('D:/desktop/output.mp4', cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))


    # 如果视频没有打开,退出。
    if not video.isOpened():
        print
        "Could not open video"
        sys.exit()

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

    # 定义一个初始边界框
    bbox = (287, 23, 86, 320)

    # 选择一个不同的边界框
    bbox = cv2.selectROI('test', frame, False)

    # 用第一帧和包围框初始化跟踪器
    ok = tracker.init(frame, bbox)

    while True:
        # 读取一个新的帧
        ok, frame = video.read()
        if not ok:
            break

        # 启动计时器
        timer = cv2.getTickCount()

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

        # 计算帧率(FPS)
        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, (0, 0, 255), 2, 3)
        else:
            # 跟踪失败
            cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)

        # 在帧上显示跟踪器类型名字
        cv2.putText(frame, tracker_type + " Tracker", (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);

        # 在帧上显示帧率FPS
        cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2);

        # 显示结果
        # cv2.imshow("Tracking", frame)
        cv2.imshow('test', frame)

        # 保存视频
        output.write(frame)

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

    output.release()

跟踪效果

opencv实现目标跟踪及视频转存_第1张图片

常见问题

https://blog.csdn.net/taotao_guiwang/article/details/133301116?spm=1001.2014.3001.5501

参考

https://blog.csdn.net/weixin_45823221/article/details/128470499

你可能感兴趣的:(python,opencv,目标跟踪,python)