opencv python 如何实现对一个视频中的物体进行跟踪
时间: 2024-06-10 07:06:05 浏览: 223
您可以使用OpenCV中的cv2.Tracker()函数来实现对视频中物体的跟踪。以下是一个示例代码:
```
import cv2
# 读取视频
cap = cv2.VideoCapture("video.mp4")
# 选择跟踪器类型
tracker_type = "CSRT"
tracker = None
if tracker_type == "BOOSTING":
tracker = cv2.TrackerBoosting_create()
elif tracker_type == "MIL":
tracker = cv2.TrackerMIL_create()
elif tracker_type == "KCF":
tracker = cv2.TrackerKCF_create()
elif tracker_type == "TLD":
tracker = cv2.TrackerTLD_create()
elif tracker_type == "MEDIANFLOW":
tracker = cv2.TrackerMedianFlow_create()
elif tracker_type == "GOTURN":
tracker = cv2.TrackerGOTURN_create()
elif tracker_type == "MOSSE":
tracker = cv2.TrackerMOSSE_create()
elif tracker_type == "CSRT":
tracker = cv2.TrackerCSRT_create()
# 读取第一帧并获取初始位置
success, frame = cap.read()
bbox = cv2.selectROI("Tracking", frame, False)
tracker.init(frame, bbox)
# 实时跟踪
while True:
# 读取当前帧
success, frame = cap.read()
if not success:
break
# 更新跟踪器并获取新位置
success, bbox = tracker.update(frame)
# 绘制跟踪结果
if success:
x, y, w, h = [int(i) for i in bbox]
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2, 1)
else:
cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
# 显示跟踪结果
cv2.imshow("Tracking", frame)
# 按q键退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
```
这段代码中,通过选择不同的跟踪器类型来初始化跟踪器,并用cv2.selectROI()函数获取初始位置,之后不断调用tracker.update()函数更新跟踪器并绘制跟踪结果。
阅读全文