yolov5 deepsort单目标跟踪代码
时间: 2025-05-02 09:51:56 浏览: 24
### YOLOv5与DeepSORT结合实现单目标跟踪
为了实现YOLOv5与DeepSORT相结合的单目标跟踪,通常会遵循以下模式。代码结构主要分为几个部分:初始化YOLOv5模型、加载DeepSORT资源、处理每一帧图像数据并调用相应的方法完成检测和跟踪。
#### 初始化环境配置
```python
import torch
from deep_sort_realtime.deepsort_tracker import DeepSort
from ultralytics import YOLO
# 加载预训练好的YOLOv5权重文件
model = YOLO('yolov5s.pt')
# 创建DeepSort实例
deepsort = DeepSort(max_age=30, n_init=2)
```
#### 处理视频流或图片序列
对于每一张输入图像,先利用YOLOv5获取当前时刻所有可能出现的目标位置信息(即边界框),再把这些候选区域交给DeepSORT做进一步分析以维持稳定的身份识别[^1]。
```python
def process_frame(frame):
results = model.predict(frame)
detections = []
for result in results:
boxes = result.boxes.cpu().numpy()
for box in boxes:
x_min, y_min, x_max, y_max = map(int, box[:4])
confidence = float(box[4])
detection = {
'bbox': (x_min, y_min, x_max - x_min, y_max - y_min),
'confidence': confidence,
'class': int(result.names[int(box[-1])]),
}
detections.append(detection)
tracks = deepsort.update_tracks(detections, frame=frame.copy())
return tracks
```
#### 绘制追踪结果
当得到更新后的轨迹列表后,可以根据需求选择如何展示最终效果,比如画出每个物体随时间变化而移动的历史路径等。
```python
for track in tracks:
if not track.is_confirmed():
continue
bbox = track.to_tlbr() # 获取边框坐标(xmin,ymin,xmax,ymax)
id_ = track.track_id # 获得该track对应的唯一ID
cv2.rectangle(frame, tuple(map(int,bbox[:2])), tuple(map(int,bbox[2:])), color=(255,0,0), thickness=2)
label = f'ID-{id_}'
cv2.putText(frame,label,(int(bbox[0]), int(bbox[1])-10),cv2.FONT_HERSHEY_SIMPLEX,.9,(255,0,0),2,cv2.LINE_AA)
```
阅读全文
相关推荐


















