yolov8使用DeepSort
时间: 2025-01-19 20:57:31 浏览: 93
集成YOLOv8与DeepSort实现目标检测与跟踪
准备工作
为了在YOLOv8中集成并使用DeepSort进行目标跟踪,需先安装必要的库和依赖项。确保环境已配置好Python以及pip工具。
git clone https://github.com/ultralytics/ultralytics.git
cd ultralytics/
pip install -r requirements.txt
对于DeepSort部分:
git clone https://github.com/nwojke/deep_sort.git
cd deep_sort
pip install .
修改YOLOv8输出以便于DeepSort输入
为了让YOLOv8的输出能够被DeepSort直接利用,通常需要调整YOLOv8预测结果的形式使其匹配DeepSort所需的格式[^2]。具体来说,YOLOv8会给出边界框坐标、置信度分数及类别标签;而这些信息正是初始化DeepSort所需的数据结构的一部分。
编写主程序逻辑
下面是一个简单的例子展示如何将两者结合起来完成实时视频流上的对象追踪功能[^3]。
from pathlib import Path
import cv2
import torch
from models.common import DetectMultiBackend
from utils.general import non_max_suppression, scale_boxes
from utils.torch_utils import select_device
from deep_sort.utils.parser import get_config
from deep_sort.deep_sort import DeepSort
def main():
weights = 'yolov8n.pt' # 权重文件路径
source = '0' # 输入源(这里设置为摄像头)
device = select_device('') # 设备选择(CPU/GPU)
model = DetectMultiBackend(weights=weights, device=device) # 加载模型
cfg = get_config()
cfg.merge_from_file("deep_sort/configs/deep_sort.yaml") # 加载DeepSort配置
deepsort = DeepSort(cfg.DEEPSORT.REID_CKPT,
max_dist=cfg.DEEPSORT.MAX_DIST,
min_confidence=cfg.DEEPSORT.MIN_CONFIDENCE,
nms_max_overlap=cfg.DEEPSORT.NMS_MAX_OVERLAP,
max_iou_distance=cfg.DEEPSORT.MAX_IOU_DISTANCE,
max_age=cfg.DEEPSORT.MAX_AGE,
n_init=cfg.DEEPSORT.N_INIT,
nn_budget=cfg.DEEPSORT.NN_BUDGET,
use_cuda=True)
cap = cv2.VideoCapture(int(source))
while True:
ret, frame = cap.read()
if not ret:
break
results = model(frame, augment=False)[0]
detections = []
for *xyxy, conf, cls in reversed(results.xyxy[0]):
bbox = [int(x.item()) for x in xyxy]
det = [*bbox, float(conf)]
detections.append(det)
outputs = deepsort.update(torch.Tensor(detections), [[frame.shape[1], frame.shape[0]]])
for output in list(outputs):
bbox = output[:4]
id_num = int(output[-1])
label = f'{id_num}'
plot_one_box(bbox, frame, label=label, color=(0, 255, 0))
cv2.imshow("Frame", frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
这段代码展示了基本框架,在实际部署过程中还需要考虑更多细节优化性能等问题[^4]。
相关推荐


















