使用cv2库将本地视频流按帧截取并捕捉ROI区域,通过matplotlib.pyplot 绘
制动态部分空间位置曲线。
1、从视频流按帧获取ROI,并跟踪
import cv2
import matplotlib.pyplot as plt
# 打开视频文件
cap = cv2.VideoCapture('video.mp4')
# 初始化跟踪器
tracker = cv2.TrackerKCF_create()
# 读取第一帧并初始化跟踪器
success, frame = cap.read()
bbox = cv2.selectROI(frame, False)
tracker.init(frame, bbox)
# 轨迹点列表
points = []
while True:
# 读取一帧
success, frame = cap.read()
if not success:
break
# 跟踪目标
success, bbox = tracker.update(frame)
if success:
# 绘制跟踪框
x, y, w, h = [int(v) for v in bbox]
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 记录跟踪器的中心点坐标
center_x, center_y = x + w/2, y + h/2
points.append((center_x, center_y))
# 显示当前帧
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
# 绘制轨迹
fig, ax = plt.subplots()
ax.set_aspect('equal')
ax.plot([p[0] for p in points], [p[1] for p in points], '-')
plt.show()
2、绘制保存的数据,按点绘制图像,显示轨迹
import csv
import matplotlib.pyplot as plt
# 从 CSV 文件中读取点数据
points = []
with open('data.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
x = float(row['x'])
y = float(row['y'])
points.append((x, y))
# 绘制点数据
fig, ax = plt.subplots()
x_values = [p[0] for p in points]
y_values = [p[1] for p in points]
ax.plot(x_values, y_values)
# 显示图形
plt.show()
网友评论