yolov5结合 DeepSORT 等跟踪算法,预测目标的运动轨迹:
时间: 2025-06-30 16:34:45 浏览: 8
### 使用 YOLOv5 和 DeepSORT 实现目标检测与追踪并预测运动轨迹
#### 1. 安装依赖库
为了使用YOLOv5和DeepSORT,需要安装必要的Python包。可以通过pip命令完成:
```bash
pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113
pip install opencv-python-headless numpy scipy filterpy lap
git clone https://github.com/ultralytics/yolov5.git
cd yolov5
pip install -r requirements.txt
```
#### 2. 配置环境变量
确保将YOLOv5仓库路径添加到系统的PYTHONPATH环境中。
```bash
export PYTHONPATH=$PYTHONPATH:/path/to/yolov5
```
#### 3. 加载预训练模型
加载YOLOv5预训练权重文件用于初始化网络结构。
```python
import torch
from models.experimental import attempt_load
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = attempt_load('yolov5s.pt', map_location=device) # 或者其他版本如m, l, x等
```
#### 4. 初始化DeepSORT实例
创建一个新的`deepsort`对象来进行后续处理。
```python
from deep_sort.deep_sort import DeepSort
deepsort = DeepSort(
max_dist=0.2,
nn_budget=None,
max_iou_distance=0.7,
n_init=3,
metric='euclidean',
matching_threshold=0.3
)
```
#### 5. 处理每一帧图像
对于每一张输入图片或者视频流中的某一时刻的画面执行如下操作:
```python
def process_frame(frame):
results = model(frame)[0].xyxy[0].cpu().numpy()
detections = []
for *xyxy, conf, cls in reversed(results):
bbox = list(map(int, xyxy))
det = Detection(bbox=bbox, confidence=float(conf), class_name=int(cls))
detections.append(det)
outputs = deepsort.update(detections=detections, frame=frame)
return outputs
```
这里定义了一个名为`process_frame()`函数,该函数接收单张RGB格式的BGR色彩空间下的OpenCV读取后的图像作为参数,并返回由DeepSORT更新后得到的结果列表。其中包含了当前时间戳下所有被成功匹配上的物体的信息,包括其边界框坐标、类别编号以及唯一ID号。
#### 6. 绘制跟踪结果
最后,在原图上画出各个目标对应的矩形边框及其标签文字说明。
```python
import cv2
for output in outputs:
xmin, ymin, xmax, ymax, track_id = int(output[0]), int(output[1]), int(output[2]), int(output[3]), int(output[-1])
label = f'{track_id}'
color = (0, 255, 0)
thickness = 2
cv2.rectangle(img=frame, pt1=(xmin, ymin), pt2=(xmax, ymax), color=color, thickness=thickness)
cv2.putText(img=frame, text=label, org=(xmin, ymin - 10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.9, color=color, thickness=thickness)
```
通过上述步骤可以实现基于YOLOv5的目标检测加上DeepSORT算法进行实时多目标跟踪的任务[^1]。值得注意的是,由于DeepSORT内部集成了卡尔曼滤波器机制,因此能够对未来一段时间内的物体位置做出合理估计,从而达到一定程度上的运动轨迹预测效果[^2]。
阅读全文
相关推荐


















