opencv目标追踪python
时间: 2023-08-23 08:04:18 浏览: 154
目标跟踪opencv代码
5星 · 资源好评率100%
好的,关于OpenCV目标追踪的Python实现,你可以参考以下步骤:
1. 导入OpenCV库和NumPy库:
```python
import cv2
import numpy as np
```
2. 读取视频文件或者摄像头数据:
```python
cap = cv2.VideoCapture("video.mp4") # 从视频文件读取
# cap = cv2.VideoCapture(0) # 从摄像头读取
```
3. 创建窗口并定义鼠标事件的回调函数:
```python
cv2.namedWindow("frame")
cv2.setMouseCallback("frame", draw_rectangle)
def draw_rectangle(event, x, y, flags, params):
global x_init, y_init, drawing, top_left_pt, bottom_right_pt
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
x_init, y_init = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
top_left_pt, bottom_right_pt = (x_init, y_init), (x, y)
cv2.rectangle(frame, top_left_pt, bottom_right_pt, (0, 255, 0), 2)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
top_left_pt, bottom_right_pt = (x_init, y_init), (x, y)
cv2.rectangle(frame, top_left_pt, bottom_right_pt, (0, 255, 0), 2)
```
这个回调函数用于在视频帧上绘制矩形框,以选择目标区域。
4. 读取视频帧,选择目标区域并进行初始化:
```python
ret, frame = cap.read()
while not ret:
ret, frame = cap.read()
cv2.imshow("frame", frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 获取目标区域
roi = frame[top_left_pt[1]:bottom_right_pt[1], top_left_pt[0]:bottom_right_pt[0]]
# 初始化追踪器
tracker = cv2.TrackerMOSSE_create()
ok = tracker.init(frame, tuple(top_left_pt+np.array(bottom_right_pt)))
```
5. 在每一帧中进行目标追踪:
```python
while True:
ret, frame = cap.read()
if not ret:
break
ok, bbox = tracker.update(frame)
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, 255, 0), 2)
else:
# 追踪失败
cv2.putText(frame, "Tracking failure detected", (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
cv2.imshow("frame", frame)
if cv2.waitKey(25) & 0xFF == ord("q"):
break
```
这个循环中,每一次迭代都会读取一帧视频,然后调用追踪器进行目标追踪。如果追踪成功,就在视频帧上绘制矩形框来表示目标位置,否则就在视频帧上显示追踪失败的信息。最后,如果按下“q”键,就退出循环。
6. 释放资源:
```python
cap.release()
cv2.destroyAllWindows()
```
这是一个基本的OpenCV目标追踪的Python实现。需要注意的是,不同的追踪器的初始化和更新方法可能不同。
阅读全文