yolov8 + deepsort 实现
yolov8 + deeposrt 的代码实现
·
实现步骤:
- 安装ultralytics
- 安装 deep_sort
- 设置视频地址
import cv2
from ultralytics import YOLO
from deep_sort_realtime.deepsort_tracker import DeepSort
# 1. 初始化 YOLOv8(只保留 person 类)
model = YOLO("yolov8n.pt")
model.model.names # 查看 80 类索引
PERSON_ID = 0 # COCO 中 person 对应索引 0
# 2. 初始化 DeepSORT
tracker = DeepSort(
max_age=30, # 丢失 30 帧才删除轨迹
n_init=3, # 连续 3 帧命中才确认轨迹
max_iou_distance=0.7,
max_cosine_distance=0.2,
nn_budget=100,
)
# 3. 打开视频
in_video = "运动会无人机拍摄_p1.mp4"
cap = cv2.VideoCapture(in_video)
fps = int(cap.get(cv2.CAP_PROP_FPS))
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out_video = cv2.VideoWriter("output/street_tracked_sport.mp4", fourcc, fps, (w, h))
frame_id = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame_id += 1
print(frame_id)
# 3.1 YOLOv8 推理
results = model(frame, classes=[PERSON_ID], verbose=False)[0] # 只检测行人
detections = []
for *xyxy, conf, cls in results.boxes.data.tolist():
x1, y1, x2, y2 = map(int, xyxy)
w_box = x2 - x1
h_box = y2 - y1
detections.append([[x1, y1, w_box, h_box], conf])
# 3.2 DeepSORT 更新
tracks = tracker.update_tracks(detections, frame=frame)
# 3.3 画框 + ID
for track in tracks:
if not track.is_confirmed():
continue
x1, y1, x2, y2 = map(int, track.to_ltrb())
tid = track.track_id
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"id:{tid}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# 3.4 写入结果
out_video.write(frame)
# 可选:实时预览
# cv2.imshow("YOLOv8+DeepSORT", frame)
# if cv2.waitKey(1) & 0xFF == 27: # ESC 退出
# break
cap.release()
out_video.release()
cv2.destroyAllWindows()
print("Done! 结果已保存到 output/street_tracked_sport.mp4")
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)