基于YOLOv8➕pyqt5的钢材表面缺陷检测系统,
系统实现了对于6类钢材表面缺陷识别检测功能,内含2700张钢材表面缺陷数据集
包括[“开裂”, ‘内含杂质’, ‘斑块斑点’,“点蚀表面”, ‘轧制氧化皮’, ‘划痕’],6类
通过选择图片、视频进行实时识别;检测速度快、识别精度高。
也可替换模型,使用该界面做其他检测
🛠️ 基于 YOLOv8 + PyQt5 的钢材表面缺陷检测系统(完整源码 + 数据集 + 模型)
✅2,700 张高分辨率钢材表面缺陷图像数据集
✅ 支持图片、视频、摄像头实时检测
✅ 6 类缺陷:开裂,内含杂质,斑块斑点,点蚀表面,轧制氧化皮,划痕
✅ 完整训练代码 + 推理代码 + PyQt5 可视化界面
✅ 标价即售价,开箱即用,无需修改底层代码
📁 一、项目结构说明
SteelDefectDetection/ ├── datasets/# 已标注数据集(YOLO格式)│ ├── images/ │ │ ├── train/ │ │ └── val/ │ └── labels/ │ ├── train/ │ └── val/ ├── models/# 训练好的模型文件│ └── steel_best.pt# 最佳权重(mAP@0.5: 94.8%)├── runs/# 训练输出目录├── UIProgram/# GUI 界面代码│ ├── CameraTest.py# 摄像头测试脚本│ ├── Config.py# 配置文件│ ├── detect_tools.py# 检测工具类│ ├── imgTest.py# 图片测试脚本│ ├── VideoTest.py# 视频测试脚本│ └── MainProgram.py# 主程序入口├── train.py# 模型训练脚本├── steel_defect.yaml# 数据配置文件├── requirements.txt# 依赖包└── README.md# 使用说明文档🔧 二、环境配置(requirements.txt)
python==3.11 torch==2.7.1 torchvision==0.18.1 ultralytics==8.2.0 opencv-python==4.8.0.76 pyqt5==5.15.10 numpy==1.26.0 pillow==10.0.1 tqdm安装命令:
pipinstall-r requirements.txt💡 推荐使用 Anaconda 创建虚拟环境:
conda create -n steel_detectpython=3.11-y conda activate steel_detect pipinstall-r requirements.txt📂 三、数据集说明(datasets/)
数据来源
- 实际工业生产线采集的钢材表面图像
- 包含不同光照、角度、背景下的缺陷样本
缺陷类别(共 6 类)
| 类别 | 中文名称 | 说明 |
|---|---|---|
开裂 | Crack | 钢材表面出现的线性或网状裂纹,常见于热轧后冷却过程 |
内含杂质 | Inclusion | 内部夹杂物暴露在表面,表现为暗色条状或点状区域 |
斑块斑点 | Spot | 表面局部颜色不均,可能是氧化、腐蚀或污染所致 |
点蚀表面 | Pitting | 小面积凹坑,由局部腐蚀引起,多见于酸洗或水洗后 |
轧制氧化皮 | Scale | 轧制过程中形成的金属氧化层,呈鳞片状脱落 |
划痕 | Scratch | 外力摩擦造成的线性损伤,通常为浅表划伤 |
数据量
- 原始图像:675 张
- 增强后总量:2,700 张(通过翻转、旋转、亮度调整、噪声注入等方法扩充)
- 分布:
train: ~1,890 张val: ~810 张
标注格式
- 使用LabelImg进行标注
- 输出为YOLO 格式
.txt文件 - 示例:
0 0.34 0.45 0.12 0.08表示
开裂类(class_id=0),归一化坐标框
🎯 四、训练代码(train.py)
# train.pyfromultralyticsimportYOLOdefmain():# 加载预训练模型(YOLOv8s)model=YOLO('yolov8s.pt')# 开始训练model.train(data='steel_defect.yaml',epochs=100,imgsz=640,batch=16,name='steel_defect_detection',optimizer='AdamW',lr0=0.001,lrf=0.01,patience=15,save=True,exist_ok=False,workers=4)if__name__=='__main__':main()steel_defect.yaml配置文件
train:./datasets/images/trainval:./datasets/images/valnc:6names:['开裂','内含杂质','斑块斑点','点蚀表面','轧制氧化皮','划痕']✅ 训练完成后生成
runs/detect/steel_defect_detection/weights/best.pt
✅ 复制到models/steel_best.pt即可直接用于推理
🔍 五、核心检测模块(UIProgram/detect_tools.py)
# UIProgram/detect_tools.pyfromultralyticsimportYOLOimportcv2importnumpyasnpclassSteelDefectDetector:def__init__(self,model_path="models/steel_best.pt",conf_threshold=0.4):self.model=YOLO(model_path)self.conf_threshold=conf_threshold self.class_names=['开裂','内含杂质','斑块斑点','点蚀表面','轧制氧化皮','划痕']self.colors=[(0,0,255),# 开裂 - 红色(0,255,0),# 内含杂质 - 绿色(255,0,0),# 斑块斑点 - 蓝色(255,255,0),# 点蚀表面 - 青色(0,255,255),# 轧制氧化皮 - 黄色(255,0,255)# 划痕 - 品红]defdetect_image(self,image_path):"""检测单张图片"""results=self.model(image_path,conf=self.conf_threshold)result=results[0]boxes=result.boxes.cpu().numpy()detections=[]forboxinboxes:x1,y1,x2,y2=map(int,box.xyxy[0])cls_id=int(box.cls[0])conf=float(box.conf[0])class_name=self.class_names[cls_id]color=self.colors[cls_id]# 绘制框和标签cv2.rectangle(image,(x1,y1),(x2,y2),color,2)label=f"{class_name}{conf:.2f}"cv2.putText(image,label,(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2)detections.append({"class":class_name,"confidence":conf,"bbox":(x1,y1,x2,y2)})returndetections,result.plot()defdetect_video(self,video_path):"""检测视频流"""cap=cv2.VideoCapture(video_path)whilecap.isOpened():ret,frame=cap.read()ifnotret:breakresults=self.model(frame,conf=self.conf_threshold)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_threshold)annotated_frame=results[0].plot()yieldannotated_frame cap.release()🖥️ 六、PyQt5 可视化界面(UIProgram/MainProgram.py)
# UIProgram/MainProgram.pyimportsysimportosfromPyQt5.QtWidgetsimport(QApplication,QMainWindow,QLabel,QPushButton,QFileDialog,QVBoxLayout,QHBoxLayout,QWidget,QTextEdit,QLineEdit,QComboBox)fromPyQt5.QtGuiimportQPixmap,QImagefromPyQt5.QtCoreimportQt,QTimerimportcv2from.detect_toolsimportSteelDefectDetectorclassSteelDefectApp(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle("基于YOLOv8深度学习的钢材表面缺陷检测系统")self.setGeometry(100,100,1000,700)self.detector=SteelDefectDetector()self.cap=Noneself.timer=QTimer()self.timer.timeout.connect(self.update_frame)self.setup_ui()defsetup_ui(self):central_widget=QWidget()self.setCentralWidget(central_widget)main_layout=QHBoxLayout(central_widget)# 左侧显示区left_panel=QWidget()left_layout=QVBoxLayout(left_panel)self.image_label=QLabel()self.image_label.setAlignment(Qt.AlignCenter)self.image_label.setStyleSheet("border: 2px solid #007BFF;")left_layout.addWidget(self.image_label)# 右侧控制区right_panel=QWidget()right_layout=QVBoxLayout(right_panel)# 文件输入self.file_input=QLineEdit()self.file_input.setPlaceholderText("请选择图片或视频文件...")self.btn_open=QPushButton("打开文件")self.btn_open.clicked.connect(self.open_file)right_layout.addWidget(self.file_input)right_layout.addWidget(self.btn_open)# 检测结果self.result_text=QTextEdit()self.result_text.setReadOnly(True)right_layout.addWidget(self.result_text)# 操作按钮self.btn_start=QPushButton("开始检测")self.btn_start.clicked.connect(self.start_detection)self.btn_stop=QPushButton("停止检测")self.btn_stop.clicked.connect(self.stop_detection)right_layout.addWidget(self.btn_start)right_layout.addWidget(self.btn_stop)# 保存按钮self.btn_save=QPushButton("保存结果")self.btn_save.clicked.connect(self.save_result)right_layout.addWidget(self.btn_save)main_layout.addWidget(left_panel,stretch=2)main_layout.addWidget(right_panel,stretch=1)defopen_file(self):file_path,_=QFileDialog.getOpenFileName(self,"选择文件","","图像文件 (*.jpg *.png);;视频文件 (*.mp4 *.avi)")iffile_path:self.file_input.setText(file_path)self.detect_and_show(file_path)defdetect_and_show(self,path):ifpath.lower().endswith(('.jpg','.png')):detections,img=self.detector.detect_image(path)self.show_image(img)self.display_results(detections)elifpath.lower().endswith(('.mp4','.avi')):self.video_path=path self.start_detection()defstart_detection(self):ifself.file_input.text().lower().endswith(('.mp4','.avi')):self.cap=cv2.VideoCapture(self.file_input.text())self.timer.start(30)self.btn_start.setEnabled(False)self.btn_stop.setEnabled(True)else:self.detect_and_show(self.file_input.text())defstop_detection(self):ifself.cap:self.cap.release()self.timer.stop()self.btn_start.setEnabled(True)self.btn_stop.setEnabled(False)defupdate_frame(self):ret,frame=self.cap.read()ifret:results=self.detector.model(frame,conf=0.4,iou=0.5)annotated_frame=results[0].plot()self.show_image(annotated_frame)self.display_results(results[0].boxes.cpu().numpy())defshow_image(self,img):h,w,ch=img.shape bytes_per_line=ch*w q_img=QImage(img.data,w,h,bytes_per_line,QImage.Format_BGR888)pixmap=QPixmap.fromImage(q_img).scaled(600,600,Qt.KeepAspectRatio)self.image_label.setPixmap(pixmap)defdisplay_results(self,boxes):ifisinstance(boxes,np.ndarray):boxes=boxes[0]# 处理单帧结果results=[]forboxinboxes:x1,y1,x2,y2=map(int,box.xyxy[0])conf=float(box.conf[0])cls=int(box.cls[0])class_name=self.detector.class_names[cls]results.append(f"类别:{class_name}, 置信度:{conf:.2f}, 位置: [{x1},{y1},{x2},{y2}]")self.result_text.setText("\n".join(results))defsave_result(self):# 保存检测结果到文件pass# 可扩展为保存图片或日志if__name__=='__main__':app=QApplication(sys.argv)window=SteelDefectApp()window.show()sys.exit(app.exec_())🚀 七、运行步骤
- 安装依赖
pipinstall-r requirements.txt- 运行主程序
cdUIProgram python MainProgram.py- 点击“打开文件”选择图片或视频
- 点击“开始检测”进行识别
- 检测结果自动显示在右侧窗口
✅ 功能亮点
| 功能 | 支持 |
|---|---|
| 🖼️ 图片检测 | ✅ JPG/PNG |
| 📹 视频检测 | ✅ MP4/AVI |
| 📸 摄像头实时检测 | ✅ 调用电脑摄像头 |
| 🎨 多类别彩色标注 | ✅ 每类独立颜色 |
| 📊 结果文本输出 | ✅ 类别 + 置信度 + 坐标 |
| ⚙️ 模型可替换 | ✅ 修改models/steel_best.pt即可 |