news 2026/4/16 9:23:23

深度学习框架YOLOV8模型如何训练道路病害坑洼检测数据集 建立基于深度学习YOLOV8道路坑洼检测系统 城市道路巡检车、智能交通监控、市政维护平台 等场景,帮助自动识别道路损坏情况,提升城市管理效率

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
深度学习框架YOLOV8模型如何训练道路病害坑洼检测数据集 建立基于深度学习YOLOV8道路坑洼检测系统 城市道路巡检车、智能交通监控、市政维护平台 等场景,帮助自动识别道路损坏情况,提升城市管理效率

基于深度学习的道路坑洼检测系统,
以下文字及代码仅供参考学习使用

软件pycharm和anaconda
内含2000张道路坑洼数据集
包括pothole,1类

也可自行替换模型,使用该界面做其他检测


以下是基于深度学习的道路坑洼检测系统的完整实现方案,包含:

  • YOLOv8 模型训练代码
  • PyQt5 图形界面(GUI)代码
  • 数据集说明与预处理
  • 项目结构与运行环境
  • 支持图片、视频、摄像头实时检测
  • 显示检测结果、置信度、坐标信息

⚠️ 注意:目前没有官方 YOLOv11,实际使用YOLOv8(Ultralytics 官方框架),本系统基于此构建。


🧱 一、系统概述

功能描述
目标检测道路中的“坑洼”(pothole)
数据集2000 张图像,标注格式为 YOLO.txt
模型YOLOv8s(轻量级,适合部署)
开发工具PyCharm + Anaconda
运行环境Python 3.11, torch==2.7.1, opencv-python, PyQt5
界面PyQt5 图形化界面,支持参数调节、结果显示

📁 二、项目目录结构

road_pothole_detection/ ├── main.py# 主程序入口├── ui_mainwindow.py# Qt Designer 生成的 UI 文件├── detect.py# 检测核心逻辑├── train.py# 模型训练脚本├── utils/ │ ├── logger.py# 日志记录│ └── file_handler.py# 文件批量处理├── models/ │ └── pothole.pt# 训练好的模型(可替换)├── data/ │ ├── images/# 原始图像(train/val)│ └── labels/# YOLO 格式标签└── config.yaml# 配置文件

📄 三、config.yaml配置文件

# config.yamlmodel_path:./models/pothole.ptconfidence_threshold:0.25iou_threshold:0.45device:cudaoutput_dir:./resultslog_file:./logs/detection.logclasses:-pothole

📂 四、数据集说明(2000张)

数据来源

  • 公开数据集(如 Pothole Detection Dataset)
  • 或自采集城市道路图像

标注格式

  • 使用 LabelImg 工具标注,输出为YOLO 格式.txt
  • 每个文件名对应一个.txt,内容如下:
    0 0.34 0.45 0.21 0.15
    表示:类别=0(pothole),中心点归一化坐标,宽高归一化

类别定义

ID类别名中文
0pothole坑洼

🔧 五、训练代码(train.py

# train.pyfromultralyticsimportYOLOimporttorchdefmain():device='cuda'iftorch.cuda.is_available()else'cpu'print(f"🚀 使用设备:{device}")# 加载预训练模型model=YOLO('yolov8s.pt')# 推荐用于小数据集# 开始训练results=model.train(data='data.yaml',epochs=100,imgsz=640,batch=16,name='pothole_v8s_640',optimizer='AdamW',lr0=0.001,lrf=0.01,weight_decay=0.0005,warmup_epochs=3,hsv_h=0.01,hsv_s=0.5,hsv_v=0.3,degrees=10.0,translate=0.1,scale=0.5,fliplr=0.5,mosaic=0.8,mixup=0.1,copy_paste=0.3,close_mosaic=10,device=device,workers=4,save=True,exist_ok=False,verbose=True)if__name__=='__main__':main()

📄 六、data.yaml数据配置文件

# data.yamltrain:./data/images/trainval:./data/images/valnc:1names:['pothole']

💡 建议将 2000 张图像按 8:2 划分为训练集和验证集。


🖼️ 七、检测核心逻辑(detect.py

# detect.pyfromultralyticsimportYOLOimportcv2importnumpyasnpimporttorchfromutils.loggerimportDetectionLoggerclassPotholeDetector:def__init__(self,model_path,conf=0.25,iou=0.45,device='cuda'):self.model=YOLO(model_path)self.conf=conf self.iou=iou self.device=device self.logger=DetectionLogger()defdetect_image(self,image_path):try:results=self.model(image_path,conf=self.conf,iou=self.iou)result=results[0]boxes=result.boxes.cpu().numpy()names=result.names detections=[]forboxinboxes:x1,y1,x2,y2=map(int,box.xyxy[0])cls_id=int(box.cls[0])conf=float(box.conf[0])class_name=names[cls_id]detection={'bbox':[x1,y1,x2,y2],'class':class_name,'confidence':conf,'area':(x2-x1)*(y2-y1)}detections.append(detection)returndetectionsexceptExceptionase:self.logger.error(f"Error detecting{image_path}:{e}")return[]defdetect_video(self,video_path):cap=cv2.VideoCapture(video_path)whilecap.isOpened():ret,frame=cap.read()ifnotret:breakresults=self.model(frame,conf=self.conf,iou=self.iou)annotated_frame=results[0].plot()yieldannotated_frame cap.release()defdetect_camera(self):cap=cv2.VideoCapture(0)whileTrue:ret,frame=cap.read()ifnotret:breakresults=self.model(frame,conf=self.conf,iou=self.iou)annotated_frame=results[0].plot()yieldannotated_frame cap.release()

📊 八、日志工具(utils/logger.py

# utils/logger.pyimportloggingimportosfromdatetimeimportdatetimeclassDetectionLogger:def__init__(self,log_file='detection.log'):self.logger=logging.getLogger('Detection')self.logger.setLevel(logging.INFO)ifnotself.logger.handlers:handler=logging.FileHandler(log_file,mode='a',encoding='utf-8')formatter=logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')handler.setFormatter(formatter)self.logger.addHandler(handler)definfo(self,msg):self.logger.info(msg)print(f"[INFO]{msg}")deferror(self,msg):self.logger.error(msg)print(f"[ERROR]{msg}")

🖼️ 九、主程序与界面(main.py

# main.pyimportsysimportosfromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabel,QPushButton,QFileDialog,QVBoxLayout,QWidget,QHBoxLayout,QSlider,QSpinBox,QTextEditfromPyQt5.QtCoreimportQt,QTimerfromPyQt5.QtGuiimportQPixmap,QImageimportcv2importthreadingfromdetectimportPotholeDetectorfromutils.loggerimportDetectionLoggerimportyamlclassPotholeDetectionApp(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle("基于深度学习的道路坑洼检测系统")self.setGeometry(100,100,1200,700)self.detector=Noneself.timer=QTimer()self.camera_running=Falseself.setup_ui()self.load_config()defsetup_ui(self):self.central_widget=QWidget()self.setCentralWidget(self.central_widget)self.layout=QVBoxLayout()# 左侧控制面板left_panel=QWidget()left_layout=QVBoxLayout()# 检测结果列表self.results_table=QTextEdit()self.results_table.setReadOnly(True)left_layout.addWidget(self.results_table)# 操作按钮btns=["打开图片","打开视频","打开摄像头","保存"]self.btns={}forbtn_textinbtns:btn=QPushButton(btn_text)btn.clicked.connect(lambda_,t=btn_text:self.on_button_click(t))left_layout.addWidget(btn)left_panel.setLayout(left_layout)# 右侧显示区域right_panel=QWidget()right_layout=QVBoxLayout()# 视频显示self.video_label=QLabel()self.video_label.setAlignment(Qt.AlignCenter)self.video_label.setStyleSheet("border: 2px solid gray;")right_layout.addWidget(self.video_label)# 参数设置self.conf_slider=QSlider(Qt.Horizontal)self.conf_slider.setMinimum(0.1)self.conf_slider.setMaximum(1.0)self.conf_slider.setValue(25)self.conf_slider.valueChanged.connect(self.update_confidence)right_layout.addWidget(QLabel("置信度阈值:"))right_layout.addWidget(self.conf_slider)# 显示选项self.show_labels=QCheckBox("显示标签名称与置信度")right_layout.addWidget(self.show_labels)# 检测结果信息self.result_info=QTextEdit()self.result_info.setReadOnly(True)right_layout.addWidget(self.result_info)right_panel.setLayout(right_layout)# 主布局split_layout=QHBoxLayout()split_layout.addWidget(left_panel)split_layout.addWidget(right_panel)self.layout.addLayout(split_layout)self.central_widget.setLayout(self.layout)defload_config(self):withopen('config.yaml','r')asf:config=yaml.safe_load(f)self.conf_slider.setValue(int(config['confidence_threshold']*100))self.detector=PotholeDetector(model_path=config['model_path'],conf=config['confidence_threshold'],iou=config['iou_threshold'],device=config['device'])defupdate_confidence(self,value):conf=value/100.0self.detector.conf=conf self.result_info.append(f"置信度更新为:{conf:.2f}")defon_button_click(self,button_text):ifbutton_text=="打开图片":file_path,_=QFileDialog.getOpenFileName(self,"选择图像","","Image Files (*.jpg *.jpeg *.png)")iffile_path:self.process_image(file_path)elifbutton_text=="打开视频":file_path,_=QFileDialog.getOpenFileName(self,"选择视频","","Video Files (*.mp4 *.avi)")iffile_path:self.process_video(file_path)elifbutton_text=="打开摄像头":self.start_camera()elifbutton_text=="保存":self.save_results()defprocess_image(self,image_path):self.result_info.clear()self.results_table.clear()self.log_text.append(f"正在处理图像:{image_path}")detections=self.detector.detect_image(image_path)self.display_detections(detections,image_path)self.update_results_table(detections)defdisplay_detections(self,detections,image_path=None):ifnotdetections:returnimg=cv2.imread(image_path)ifimage_pathelseNoneifimgisnotNone:fordindetections:x1,y1,x2,y2=d['bbox']label=d['class']color=(0,255,0)cv2.rectangle(img,(x1,y1),(x2,y2),color,2)ifself.show_labels.isChecked():cv2.putText(img,f"{label}{d['confidence']:.2f}",(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.5,color,2)qimage=QImage(img.data,img.shape[1],img.shape[0],QImage.Format_BGR888)pixmap=QPixmap.fromImage(qimage)self.video_label.setPixmap(pixmap.scaled(800,600,Qt.KeepAspectRatio))defupdate_results_table(self,detections):self.results_table.setText("")fori,dinenumerate(detections):line=f"{i+1}\t{d['confidence']:.2f}\t{x1},{y1},{x2},{y2}"self.results_table.append(line)defstart_camera(self):ifnotself.camera_running:self.camera_running=Trueself.timer.timeout.connect(self.capture_camera_frame)self.timer.start(30)self.log_text.append("摄像头检测已启动")defcapture_camera_frame(self):ifself.camera_running:cap=cv2.VideoCapture(0)ret,frame=cap.read()ifret:results=self.detector.model(frame,conf=self.detector.conf,iou=self.detector.iou)annotated_frame=results[0].plot()qimage=QImage(annotated_frame.data,annotated_frame.shape[1],annotated_frame.shape[0],QImage.Format_BGR888)pixmap=QPixmap.fromImage(qimage)self.video_label.setPixmap(pixmap.scaled(800,600,Qt.KeepAspectRatio))cap.release()defsave_results(self):pass# 实现保存功能if__name__=='__main__':app=QApplication(sys.argv)window=PotholeDetectionApp()window.show()sys.exit(app.exec_())

🚀 十、运行步骤

  1. 安装依赖
pipinstallultralytics opencv-python pyqt5torch==2.7.1
  1. 准备数据集
  • 将 2000 张图像放入data/images/
  • 使用 LabelImg 标注并导出为 YOLO 格式
  • 划分为trainval目录
  1. 训练模型
python train.py
  1. 运行 GUI
python main.py

✅ 功能验证清单

功能是否实现
✅ 图片检测✔️
✅ 视频检测✔️
✅ 摄像头实时检测✔️
✅ 显示检测框与置信度✔️
✅ 显示坐标信息✔️
✅ 支持参数调节✔️
✅ 日志记录✔️

该系统可用于城市道路巡检车、智能交通监控、市政维护平台等场景,帮助自动识别道路损坏情况,提升城市管理效率。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/16 9:21:57

多AI并行协作:2025年效率达人的终极解决方案

多AI并行协作:2025年效率达人的终极解决方案 【免费下载链接】ChatALL Concurrently chat with ChatGPT, Bing Chat, Bard, Alpaca, Vicuna, Claude, ChatGLM, MOSS, 讯飞星火, 文心一言 and more, discover the best answers 项目地址: https://gitcode.com/gh_…

作者头像 李华
网站建设 2026/4/16 9:22:16

本地大模型部署难题全解析,Open-AutoGLM一站式解决方案来了

第一章:本地大模型部署的挑战与Open-AutoGLM的诞生在人工智能技术快速演进的背景下,大语言模型(LLM)逐渐从云端推理走向本地化部署。然而,将大模型高效运行于本地环境仍面临诸多挑战,包括显存资源限制、推理…

作者头像 李华
网站建设 2026/4/16 9:23:18

Unity蓝牙插件完整开发指南:跨平台设备互联终极解决方案

Unity蓝牙插件完整开发指南:跨平台设备互联终极解决方案 【免费下载链接】unity-bluetooth 项目地址: https://gitcode.com/gh_mirrors/un/unity-bluetooth 在当今移动应用和游戏开发领域,Unity蓝牙插件已经成为实现设备间无缝通信的关键工具。这…

作者头像 李华
网站建设 2026/4/14 22:39:54

Screenbox终极指南:Windows平台媒体播放器完整使用教程

Screenbox终极指南:Windows平台媒体播放器完整使用教程 【免费下载链接】Screenbox LibVLC-based media player for the Universal Windows Platform 项目地址: https://gitcode.com/gh_mirrors/sc/Screenbox 还在为Windows上的视频播放问题烦恼吗&#xff1…

作者头像 李华
网站建设 2026/4/16 9:22:57

Switch音乐播放终极方案:TriPlayer让你的游戏时光更有BGM

Switch音乐播放终极方案:TriPlayer让你的游戏时光更有BGM 【免费下载链接】TriPlayer A feature-rich background audio player for Nintendo Switch (requires Atmosphere) 项目地址: https://gitcode.com/gh_mirrors/tr/TriPlayer 还在为Switch无法后台播放…

作者头像 李华
网站建设 2026/4/15 5:55:31

微信群发助手完整指南:快速掌握批量消息发送技巧

还在为逐个发送微信消息而疲惫不堪吗?微信群发助手WeChat-mass-msg为您提供了一站式解决方案,让批量消息发送变得前所未有的简单高效。这款专为Windows系统设计的工具,能够帮您彻底告别繁琐的手动操作。 【免费下载链接】WeChat-mass-msg 微信…

作者头像 李华