yolov8训练deepsort多目标追踪
时间: 2025-06-28 19:09:28 浏览: 11
### 使用YOLOv8与DeepSort实现多目标追踪
#### 数据准备
为了训练YOLOv8用于检测,需先准备好标注的数据集。数据应按照特定结构组织,通常包括图像文件夹和对应的标签文件夹。每个标签文件采用txt格式保存边界框坐标以及类别编号[^2]。
#### YOLOv8模型配置与预处理
安装必要的依赖库之后,在命令行工具里指定参数启动训练流程。这期间要调整超参比如batch size、epochs数目等以适应具体场景需求。对于自定义数据源而言,还需修改`data.yaml`中的路径指向本地存储位置,并设定好类别的映射关系。
#### 集成DeepSort模块
完成上述工作后,下一步就是引入DeepSort组件以便于执行跟踪任务。此部分涉及到特征提取网络的选择(如ResNet)、初始化Kalman Filter实例化Track对象列表等一系列操作。当新帧到来时,通过调用predict()更新状态估计值;而correct()函数则负责依据观测修正预测误差[^3]。
#### 启动联合推理服务
最后一步便是构建完整的pipeline:读取输入流 -> 调用YOLOv8获取候选区域 -> 将这些detections传递给DeepSort处理器 -> 输出带ID的结果可视化画面。整个过程可以通过Python脚本封装起来方便部署应用环境当中去。
```python
from ultralytics import YOLO
import numpy as np
from deep_sort_realtime.deepsort_tracker import DeepSort
model = YOLO('yolov8n.pt') # 加载预训练权重或自己训练后的最佳模型
tracker = DeepSort(max_age=30, n_init=2)
def process_frame(frame):
results = model.predict(source=np.array([frame]), save=False)[0].boxes.data.cpu().numpy()
detections = []
for result in results:
bbox = list(map(int, result[:4]))
conf = float(result[4])
cls = int(result[-1])
if conf >= 0.5: # 只考虑置信度大于等于阈值的对象
detections.append(([bbox], conf, cls))
tracks = tracker.update_tracks(detections, frame=frame.copy())
output_image = draw_boxes_on_image(tracks, frame)
return output_image
def draw_boxes_on_image(tracks, image):
for track in tracks:
if not track.is_confirmed():
continue
track_id = track.track_id
ltrb = track.to_ltrb()
cv2.rectangle(image, (int(ltrb[0]), int(ltrb[1])), (int(ltrb[2]), int(ltrb[3])), color=(255, 0, 0), thickness=2)
text_scale = max(1, min(3, abs(int(ltrb[2]) - int(ltrb[0])) // 15))
label = f'ID-{track_id}'
((label_width, label_height), _) = cv2.getTextSize(label, fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=text_scale, thickness=2)
box_coords = ((int(ltrb[0]), int(ltrb[1])), (int(ltrb[0]) + label_width, int(ltrb[1]) - label_height - 10))
cv2.rectangle(image, box_coords[0], box_coords[1], color=(255, 0, 0), thickness=cv2.FILLED)
cv2.putText(image, label, org=(int(ltrb[0]), int(ltrb[1]) - 10),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=text_scale,
color=(255, 255, 255),
thickness=2)
return image
```
阅读全文
相关推荐


















