🚗🚶♂️ 使用 YOLOv11/8 和 DeepSort 实现车辆与行人实时跟踪与计数
本项目将 YOLOv11/8 与 DeepSort 相结合,实现了对目标的实时跟踪与计数。提供了一个封装的 Detector 类,方便将此功能嵌入到自定义项目中。
- 目标跟踪:实时跟踪车辆与行人。
- 计数功能:轻松统计视频流中的车辆或行人数。
- 封装式接口:
Detector类封装了检测与跟踪逻辑,便于集成。 - 高度自定义:支持训练自己的 YOLOv11/8 模型并无缝接入框架。
pip install -r requirements.txt确保安装了 requirements.txt 文件中列出的所有依赖。
python main_yolov11.py
python main_yolov8.pyclassDetector(baseDet):
def__init__(self):
super(Detector, self).__init__()
self.init_model()
self.build_config()
definit_model(self):
self.weights='weights/YOLOv11m.pt'self.device='0'iftorch.cuda.is_available() else'cpu'self.device=select_device(self.device)
model=attempt_load(self.weights, map_location=self.device)
model.to(self.device).eval()
model.half()
# torch.save(model, 'test.pt')self.m=modelself.names=model.module.namesifhasattr(
model, 'module') elsemodel.namesdefpreprocess(self, img):
img0=img.copy()
img=letterbox(img, new_shape=self.img_size)[0]
img=img[:, :, ::-1].transpose(2, 0, 1)
img=np.ascontiguousarray(img)
img=torch.from_numpy(img).to(self.device)
img=img.half() # 半精度img/=255.0# 图像归一化ifimg.ndimension() ==3:
img=img.unsqueeze(0)
returnimg0, imgdefdetect(self, im):
im0, img=self.preprocess(im)
pred=self.m(img, augment=False)[0]
pred=pred.float()
pred=non_max_suppression(pred, self.threshold, 0.4)
pred_boxes= []
fordetinpred:
ifdetisnotNoneandlen(det):
det[:, :4] =scale_coords(
img.shape[2:], det[:, :4], im0.shape).round()
for*x, conf, cls_idindet:
lbl=self.names[int(cls_id)]
ifnotlblin ['person', 'car', 'truck']:
continuex1, y1=int(x[0]), int(x[1])
x2, y2=int(x[2]), int(x[3])
pred_boxes.append(
(x1, y1, x2, y2, lbl, conf))
returnim, pred_boxes- 调用
self.detect()方法返回图像和预测结果
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)- 调用
self.update()方法更新追踪结果
训练完成后,将模型权重文件放置于 weights 文件夹中。
fromAIDetector_pytorchimportDetectordet=Detector()func_status= {}
func_status['headpose'] =Noneresult=det.feedCap(im, func_status)im: 输入的 BGR 图像。result['frame']: 检测结果的可视化图像。
- Bilibili: https://space.bilibili.com/470550823
- CSDN: https://blog.csdn.net/weixin_44936889
- AI Studio: https://aistudio.baidu.com/aistudio/personalcenter/thirdview/67156
- GitHub: https://github.com/Sharpiless
关注我的微信公众号,获取更多深度学习教程:
公众号:可达鸭的深度学习教程
本项目遵循 MIT License 协议。
标明目标检测部分来源:https://github.com/ultralytics/ultralytics

