当前位置: 首页 > news >正文

pytorch 深度学习目标检测算法yolov5训练电动车闯红灯检测数据集 建立基于深度学习Yolov5电动车闯红灯检测识别

pytorch 深度学习目标检测算法yolov5训练电动车闯红灯检测数据集 建立基于深度学习Yolov5电动车闯红灯检测识别

文章目录

      • 1. 数据准备
        • 数据集结构
        • 数据标注
        • 数据划分
      • 2. 环境搭建
        • 安装依赖
      • 3. 数据配置
      • 4. 模型训练
        • 使用YOLOv5进行训练
      • 5. 配置超参数
      • 6. 模型推理
        • 单张图片推理
      • 7. 批量推理
      • 8. 性能评估
        • mAP计算
        • 自定义评估脚本

yolov5电动车闯红灯检测, 可检测 红灯 绿灯 电动车三类
1



基于YOLOv5的电动车闯红灯检测系统涉及多个步骤,包括数据准备、环境搭建、模型训练、超参数配置、模型推理、批量推理以及性能评估。以下是详细的实现步骤和代码示例。

1. 数据准备

数据集结构

确保你的数据集结构如下:

traffic_dataset/ ├── images/ │ ├── train/ │ └── val/ └── labels/ ├── train/ └── val/
数据标注

每个图像文件对应一个.txt文件,格式为YOLO适用的标注格式,每行包含类别ID和边界框信息(归一化后的中心点坐标和宽高)。

例如:

0 0.5 0.5 0.2 0.2 1 0.7 0.3 0.1 0.1
数据划分

将数据集按比例划分为训练集和验证集(例如9:1)。

importosimportrandomfromshutilimportcopyfile# 定义数据集路径dataset_path='traffic_dataset'images_path=os.path.join(dataset_path,'images')labels_path=os.path.join(dataset_path,'labels')# 创建目录os.makedirs(images_path,exist_ok=True)os.makedirs(labels_path,exist_ok=True)# 获取所有图像文件image_files=[fforfinos.listdir(dataset_path)iff.endswith('.jpg')orf.endswith('.png')]random.shuffle(image_files)# 按比例划分训练集和验证集train_ratio=0.9train_size=int(len(image_files)*train_ratio)train_images=image_files[:train_size]val_images=image_files[train_size:]# 复制文件到对应的目录forimg_fileintrain_images:label_file=img_file.replace('.jpg','.txt').replace('.png','.txt')copyfile(os.path.join(dataset_path,img_file),os.path.join(images_path,'train',img_file))copyfile(os.path.join(dataset_path,label_file),os.path.join(labels_path,'train',label_file))forimg_fileinval_images:label_file=img_file.replace('.jpg','.txt').replace('.png','.txt')copyfile(os.path.join(dataset_path,img_file),os.path.join(images_path,'val',img_file))copyfile(os.path.join(dataset_path,label_file),os.path.join(labels_path,'val',label_file))

2. 环境搭建

安装依赖
# 创建并激活虚拟环境conda create-ntraffic_detectionpython=3.8conda activate traffic_detection# 安装YOLOv5和相关库pipinstalltorch torchvisiongitclone https://github.com/ultralytics/yolov5.gitcdyolov5 pipinstall-rrequirements.txt

3. 数据配置

traffic_dataset/目录下创建一个名为data.yaml的数据配置文件,内容如下:

train:./images/train/val:./images/val/nc:3names:['red_light','green_light','non_motor_vehicle']

4. 模型训练

使用YOLOv5进行训练
cdyolov5 python train.py--img640--batch16--epochs100--data../traffic_dataset/data.yaml--weightsyolov5s.pt

5. 配置超参数

在训练过程中,可以通过修改yolov5/data/hyps/hyp.scratch.yaml文件来设置超参数。以下是一些常见的超参数及其说明:

  • lr0: 初始学习率,默认值通常为0.01。
  • lrf: 最终学习率因子,默认值通常为0.01。
  • momentum: 动量,默认值通常为0.937。
  • weight_decay: 权重衰减,默认值通常为0.0005。

6. 模型推理

单张图片推理
fromyolov5.models.experimentalimportattempt_loadfromyolov5.utils.datasetsimportLoadImagesfromyolov5.utils.generalimportnon_max_suppression,scale_coordsfromyolov5.utils.torch_utilsimportselect_deviceimportcv2importtorchdefinfer_image(weights,img_path):device=select_device('')model=attempt_load(weights,map_location=device)dataset=LoadImages(img_path)forpath,img,im0s,vid_capindataset:img=torch.from_numpy(img).to(device)img=img.float()/255.0ifimg.ndimension()==3:img=img.unsqueeze(0)pred=model(img,augment=False)[0]pred=non_max_suppression(pred,conf_thres=0.25,iou_thres=0.45)fordetinpred:iflen(det):det[:,:4]=scale_coords(img.shape[2:],det[:,:4],im0s.shape).round()for*xyxy,conf,clsinreversed(det):label=f'{model.names[int(cls)]}{conf:.2f}'plot_one_box(xyxy,im0s,label=label,color=(0,255,0),line_thickness=3)cv2.imshow('Traffic Detection',im0s)cv2.waitKey(0)cv2.destroyAllWindows()if__name__=="__main__":weights='runs/train/exp/weights/best.pt'img_path='path/to/test_image.jpg'infer_image(weights,img_path)

7. 批量推理

importosdefbatch_infer_images(weights,directory):forfilenameinos.listdir(directory):iffilename.endswith(".jpg")orfilename.endswith(".png"):image_path=os.path.join(directory,filename)annotated_frame=infer_image(weights,image_path)cv2.imwrite(f"output_{filename}",annotated_frame)if__name__=="__main__":weights='runs/train/exp/weights/best.pt'directory='path/to/images'batch_infer_images(weights,directory)

8. 性能评估

mAP计算

YOLOv5自带评估功能,可以在验证集上计算mAP。

cdyolov5 python val.py--img640--batch16--data../traffic_dataset/data.yaml--weightsruns/train/exp/weights/best.pt
自定义评估脚本

如果你想要更详细的评估指标,比如针对特定类别的准确率和召回率,可以编写自定义脚本。

fromsklearn.metricsimportprecision_recall_fscore_supportdefevaluate_model(model,dataset):all_preds=[]all_labels=[]forimages,labelsindataset:preds=model(images)pred_classes=[int(pred.cls[0])forpredinpreds]true_classes=labels.numpy().flatten()all_preds.extend(pred_classes)all_labels.extend(true_classes)precision,recall,f1,_=precision_recall_fscore_support(all_labels,all_preds,average='weighted')print(f'Precision:{precision:.2f}, Recall:{recall:.2f}, F1 Score:{f1:.2f}')# 示例:评估模型性能evaluate_model(model,val_dataset)

以上就是关于如何在YOLOv5基础上构建电动车闯红灯检测系统的完整指南,包括数据准备、环境搭建、模型训练、超参数配置、模型推理、批量推理以及性能评估代码。根据实际需求调整上述代码段,关键代码示例,仅供参考。

http://www.jsqmd.com/news/627424/

相关文章:

  • 2026年靠谱的公路桥梁钢模板/挂篮钢模板/钢模板厂家推荐与选购指南 - 品牌宣传支持者
  • MGeo地址相似度匹配实战:电商物流地址清洗完整流程
  • 迁移学习中的Coral损失函数:原理详解与避坑指南
  • Qwen-Image-Edit LoRA模型AnythingtoRealCharacters2511代码实例:Python API调用方法
  • 这才是AI的真实结构:90%的人都理解错了
  • Phi-4-mini-reasoning助力MySQL数据库课程设计:智能查询优化与ER图推理
  • 通义千问3-Reranker-0.6B应用场景:AI辅助写作工具内容相关性筛选
  • 2026年热门的江苏智能净水器/江苏超滤净水器/智能净水器生产厂家 - 行业平台推荐
  • ANIMATEDIFF PRO惊艳效果:16帧内头发飘动轨迹、衣料褶皱物理模拟动态呈现
  • 手把手教你部署HY-MT1.5-7B:33种语言翻译服务一键启动
  • 忍者像素绘卷实战案例:为微信小程序游戏生成像素风加载动画帧
  • 一键升级你的投资分析:AI股票分析师镜像部署与核心功能详解
  • Qwen3-8B快速上手:无需复杂配置,开箱即用的本地AI解决方案
  • S2-Pro赋能微信小程序:开发智能对话AI应用实战
  • MusePublic部署教程:离线环境无网络部署MusePublic全组件方案
  • 2026年靠谱的安全气囊发生器外壳钢管/钢管厂家实力参考 - 品牌宣传支持者
  • 保姆级教程:Qwen3-ASR-1.7B一键部署,小白也能玩转52种语言识别
  • SiameseUIE开源大模型教程:中文信息抽取领域的轻量级SOTA方案
  • VoxCPM-1.5-WEBUI镜像使用教程:网页界面操作,轻松合成个性化语音
  • ofa_image-caption部署教程:阿里云ECS GPU实例一键部署全流程
  • Perl处理特殊字符的单行命令实例
  • 2026年质量好的高压水阻起动柜/高压同步电机起动柜新厂实力推荐(更新) - 行业平台推荐
  • Python的__format_spec__方法扩展格式化字符串语法的自定义格式
  • 3步搞定Phi-3-mini-4k-instruct-gguf在WSL中的部署与调用
  • .NET源码生成器基于partial范式开发和nuget打包墙
  • 小白也能学会:用Qwen2.5-7B微调镜像,10分钟打造专属对话机器人
  • 快速体验AI写春联:春联生成模型-中文-base在线Demo搭建教程
  • KART-RERANK模型监控与告警:构建生产环境可观测性体系
  • 2026年知名的大连公考鹏鹏面试/大连公考教师编/大连公考省考班/大连公考国考合作参考指南公司 - 品牌宣传支持者
  • 机器学习可解释性:特征重要性分析与可视化