![](https://csdnimg.cn/release/download_crawler_static/87877868/bg4.jpg)
frame = cv2.imread('frame.jpg')
# 对视频帧进行预处理
img = letterbox(frame, new_shape=640)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
img = np.ascontiguousarray(img)
# 将视频帧输入 YOLO v5 模型进行目标检测
img = torch.from_numpy(img).to(torch.device('cpu'))
img = img.float() / 255.0
img = img.unsqueeze(0)
pred = model(img)[0]
# 进行非极大值抑制
pred = non_max_suppression(pred, 0.4, 0.5)
# 对每个检测到的目标进行深度排序
for det in pred:
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
bbox_xywh = []
confs = []
for *xyxy, conf, cls in reversed(det):
x_c, y_c, bbox_w, bbox_h = bbox_xywh_scale(*xyxy, frame.shape)
obj = [x_c, y_c, bbox_w, bbox_h]
bbox_xywh.append(obj)
confs.append([conf.item()])
xywhs = torch.Tensor(bbox_xywh)
confss = torch.Tensor(confs)
outputs = deepsort.update(xywhs, confss, frame)
# 绘制跟踪结果
for output in outputs:
bbox_tlwh = output[0:4]
id = output[4]
plot_one_box(bbox_tlwh, frame, label=id, color=(0, 255, 0), line_thickness=3)
# 显示跟踪结果
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# 释放资源
cv2.destroyAllWindows()