基于YOLOv11的轴承缺陷识别检测系统(YOLOv11深度学习+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)

 一、项目介绍

本文基于深度学习目标检测算法YOLOv11,设计并实现了一套轴承缺陷智能识别系统。针对工业场景中轴承表面常见的凹槽(aocao)、凹线(aoxian)、擦伤(cashang)和划痕(huahen)四类缺陷,构建了包含1,085张图像的数据集(训练集759张、验证集326张),通过数据增强和迁移学习优化模型性能。系统采用PyTorch框架开发,集成用户友好的UI界面与登录注册功能,支持实时检测与结果可视化。实验表明,YOLOv11在验证集上达到平均精度(mAP@0.5)99.5%,显著提高了缺陷检测效率。本研究为工业质检自动化提供了可落地的解决方案。

引言
轴承作为机械设备的核心部件,其表面缺陷直接影响设备寿命与运行安全。传统人工检测存在效率低、主观性强等问题,而基于深度学习的视觉检测技术为解决这一难题提供了新思路。YOLO系列算法因其实时性与高精度在工业检测中广受关注,但现有研究多集中于通用场景,针对轴承多类缺陷的定制化检测系统仍待探索。

目录

 一、项目介绍

二、项目功能展示

2.1 用户登录系统

2.2 检测功能

2.3 检测结果显示

2.4 参数配置

2.5 其他功能

3. 技术特点

4. 系统流程

三、数据集介绍

数据集配置文件

四、项目环境配置

创建虚拟环境

安装所需要库

五、模型训练

训练代码

训练结果

六、核心代码

🔐登录注册验证

🎯 多重检测模式

🖼️ 沉浸式可视化

⚙️ 参数配置系统

✨ UI美学设计

🔄 智能工作流

七、项目源码(视频简介)


基于深度学习YOLOv11的轴承缺陷识别检测系统(YOLOv11+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)_哔哩哔哩_bilibili

基于深度学习YOLOv11的轴承缺陷识别检测系统(YOLOv11+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)

二、项目功能展示

✅ 用户登录注册:支持密码检测和安全性验证。

✅ 三种检测模式:基于YOLOv11模型,支持图片、视频和实时摄像头三种检测,精准识别目标。

✅ 双画面对比:同屏显示原始画面与检测结果。

✅ 数据可视化:实时表格展示检测目标的类别、置信度及坐标。

✅智能参数调节:提供置信度滑块,动态优化检测精度,适应不同场景需求。

✅科幻风交互界面:深色主题搭配动态光效,减少视觉疲劳,提升操作体验。

✅多线程高性能架构:独立检测线程保障流畅运行,实时状态提示,响应迅速无卡顿。

2.1 用户登录系统

  • 提供用户登录和注册功能

  • 用户名和密码验证

  • 账户信息本地存储(accounts.json)

  • 密码长度至少6位的安全要求

2.2 检测功能

  • 图片检测:支持JPG/JPEG/PNG/BMP格式图片的火焰烟雾检测

  • 视频检测:支持MP4/AVI/MOV格式视频的逐帧检测

  • 摄像头检测:实时摄像头流检测(默认摄像头0)

  • 检测结果保存到"results"目录

2.3 检测结果显示

  • 显示原始图像和检测结果图像

  • 检测结果表格展示,包含:

    • 检测到的类别

    • 置信度分数

    • 物体位置坐标(x,y)、

2.4 参数配置

  • 模型选择

  • 置信度阈值调节(0-1.0)

  • IoU(交并比)阈值调节(0-1.0)

  • 实时同步滑块和数值输入框

2.5 其他功能

  • 检测结果保存功能

  • 视频检测时自动保存结果视频

  • 状态栏显示系统状态和最后更新时间

  • 无边框窗口设计,可拖动和调整大小

3. 技术特点

  • 采用多线程处理检测任务,避免界面卡顿

  • 精美的UI设计,具有科技感的视觉效果:

    • 发光边框和按钮

    • 悬停和按下状态效果

    • 自定义滑块、表格和下拉框样式

  • 检测结果保存机制

  • 响应式布局,适应不同窗口大小

4. 系统流程

  1. 用户登录/注册

  2. 选择检测模式(图片/视频/摄像头)

  3. 调整检测参数(可选)

  4. 开始检测并查看结果

  5. 可选择保存检测结果

  6. 停止检测或切换其他模式

三、数据集介绍

本研究所使用的轴承缺陷数据集共包含 1,085 张 高分辨率工业图像,涵盖轴承表面常见的 4 类缺陷凹槽(aocao)、凹线(aoxian)、擦伤(cashang)和划痕(huahen)。数据集按照 8:2 的比例 划分为 训练集(759 张) 和 验证集(326 张),以确保模型训练和评估的可靠性。

数据集配置文件

数据集采用标准化YOLO格式组织:

train: F:\轴承缺陷检测数据集\images\train
val: F:\轴承缺陷检测数据集\images\val

nc: 4
names: ['aocao', 'aoxian', 'cashang', 'huahen']

四、项目环境配置

创建虚拟环境

首先新建一个Anaconda环境,每个项目用不同的环境,这样项目中所用的依赖包互不干扰。

终端输入

conda create -n yolov11 python==3.9

激活虚拟环境

conda activate yolov11
 

安装cpu版本pytorch

pip install torch torchvision torchaudio

安装所需要库

pip install -r requirements.txt

pycharm中配置anaconda

五、模型训练

训练代码

from ultralytics import YOLO

model_path = 'yolo11s.pt'
data_path = 'data.yaml'

if __name__ == '__main__':
    model = YOLO(model_path)
    results = model.train(data=data_path,
                          epochs=100,
                          batch=8,
                          device='0',
                          workers=0,
                          project='runs',
                          name='exp',
                          )
根据实际情况更换模型
# yolov11n.yaml (nano):轻量化模型,适合嵌入式设备,速度快但精度略低。
# yolov11s.yaml (small):小模型,适合实时任务。
# yolov11m.yaml (medium):中等大小模型,兼顾速度和精度。
# yolov11b.yaml (base):基本版模型,适合大部分应用场景。
# yolov11l.yaml (large):大型模型,适合对精度要求高的任务。
  • --batch 8:每批次8张图像。
  • --epochs 100:训练100轮。
  • --datasets/data.yaml:数据集配置文件。
  • --weights yolov11s.pt:初始化模型权重,yolov11s.pt 是预训练的轻量级YOLO模型。

训练结果

六、核心代码

import sys

import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication, QMessageBox, QFileDialog
from PyQt5.QtCore import QThread, pyqtSignal
from ultralytics import YOLO
from UiMain import UiMainWindow
import time
import os
from PyQt5.QtWidgets import QDialog
from LoginWindow import LoginWindow

class DetectionThread(QThread):
    frame_received = pyqtSignal(np.ndarray, np.ndarray, list)  # 原始帧, 检测帧, 检测结果
    finished_signal = pyqtSignal()  # 线程完成信号

    def __init__(self, model, source, conf, iou, parent=None):
        super().__init__(parent)
        self.model = model
        self.source = source
        self.conf = conf
        self.iou = iou
        self.running = True

    def run(self):
        try:
            if isinstance(self.source, int) or self.source.endswith(('.mp4', '.avi', '.mov')):  # 视频或摄像头
                cap = cv2.VideoCapture(self.source)
                while self.running and cap.isOpened():
                    ret, frame = cap.read()
                    if not ret:
                        break

                    # 保存原始帧
                    original_frame = frame.copy()

                    # 检测
                    results = self.model(frame, conf=self.conf, iou=self.iou)
                    annotated_frame = results[0].plot()

                    # 提取检测结果
                    detections = []
                    for result in results:
                        for box in result.boxes:
                            class_id = int(box.cls)
                            class_name = self.model.names[class_id]
                            confidence = float(box.conf)
                            x, y, w, h = box.xywh[0].tolist()
                            detections.append((class_name, confidence, x, y))

                    # 发送信号
                    self.frame_received.emit(
                        cv2.cvtColor(original_frame, cv2.COLOR_BGR2RGB),
                        cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB),
                        detections
                    )

                    # 控制帧率
                    time.sleep(0.03)  # 约30fps

                cap.release()
            else:  # 图片
                frame = cv2.imread(self.source)
                if frame is not None:
                    original_frame = frame.copy()
                    results = self.model(frame, conf=self.conf, iou=self.iou)
                    annotated_frame = results[0].plot()

                    # 提取检测结果
                    detections = []
                    for result in results:
                        for box in result.boxes:
                            class_id = int(box.cls)
                            class_name = self.model.names[class_id]
                            confidence = float(box.conf)
                            x, y, w, h = box.xywh[0].tolist()
                            detections.append((class_name, confidence, x, y))

                    self.frame_received.emit(
                        cv2.cvtColor(original_frame, cv2.COLOR_BGR2RGB),
                        cv2.cvtColor(annotated_frame, cv2.COLOR_BGR2RGB),
                        detections
                    )

        except Exception as e:
            print(f"Detection error: {e}")
        finally:
            self.finished_signal.emit()

    def stop(self):
        self.running = False


class MainWindow(UiMainWindow):
    def __init__(self):
        super().__init__()

        # 初始化模型
        self.model = None
        self.detection_thread = None
        self.current_image = None
        self.current_result = None
        self.video_writer = None
        self.is_camera_running = False
        self.is_video_running = False
        self.last_detection_result = None  # 新增:保存最后一次检测结果

        # 连接按钮信号
        self.image_btn.clicked.connect(self.detect_image)
        self.video_btn.clicked.connect(self.detect_video)
        self.camera_btn.clicked.connect(self.detect_camera)
        self.stop_btn.clicked.connect(self.stop_detection)
        self.save_btn.clicked.connect(self.save_result)

        # 初始化模型
        self.load_model()

    def load_model(self):
        try:
            model_name = self.model_combo.currentText()
            self.model = YOLO(f"{model_name}.pt")  # 自动下载或加载本地模型
            self.update_status(f"模型 {model_name} 加载成功")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"模型加载失败: {str(e)}")
            self.update_status("模型加载失败")

    def detect_image(self):
        if self.detection_thread and self.detection_thread.isRunning():
            QMessageBox.warning(self, "警告", "请先停止当前检测任务")
            return

        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择图片", "", "图片文件 (*.jpg *.jpeg *.png *.bmp)")

        if file_path:
            self.clear_results()
            self.current_image = cv2.imread(file_path)
            self.current_image = cv2.cvtColor(self.current_image, cv2.COLOR_BGR2RGB)
            self.display_image(self.original_image_label, self.current_image)

            # 创建检测线程
            conf = self.confidence_spinbox.value()
            iou = self.iou_spinbox.value()
            self.detection_thread = DetectionThread(self.model, file_path, conf, iou)
            self.detection_thread.frame_received.connect(self.on_frame_received)
            self.detection_thread.finished_signal.connect(self.on_detection_finished)
            self.detection_thread.start()

            self.update_status(f"正在检测图片: {os.path.basename(file_path)}")

    def detect_video(self):
        if self.detection_thread and self.detection_thread.isRunning():
            QMessageBox.warning(self, "警告", "请先停止当前检测任务")
            return

        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择视频", "", "视频文件 (*.mp4 *.avi *.mov)")

        if file_path:
            self.clear_results()
            self.is_video_running = True

            # 初始化视频写入器
            cap = cv2.VideoCapture(file_path)
            frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = cap.get(cv2.CAP_PROP_FPS)
            cap.release()

            # 创建保存路径
            save_dir = "results"
            os.makedirs(save_dir, exist_ok=True)
            timestamp = time.strftime("%Y%m%d_%H%M%S")
            save_path = os.path.join(save_dir, f"result_{timestamp}.mp4")

            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            self.video_writer = cv2.VideoWriter(save_path, fourcc, fps, (frame_width, frame_height))

            # 创建检测线程
            conf = self.confidence_spinbox.value()
            iou = self.iou_spinbox.value()
            self.detection_thread = DetectionThread(self.model, file_path, conf, iou)
            self.detection_thread.frame_received.connect(self.on_frame_received)
            self.detection_thread.finished_signal.connect(self.on_detection_finished)
            self.detection_thread.start()

            self.update_status(f"正在检测视频: {os.path.basename(file_path)}")

    def detect_camera(self):
        if self.detection_thread and self.detection_thread.isRunning():
            QMessageBox.warning(self, "警告", "请先停止当前检测任务")
            return

        self.clear_results()
        self.is_camera_running = True

        # 创建检测线程 (默认使用摄像头0)
        conf = self.confidence_spinbox.value()
        iou = self.iou_spinbox.value()
        self.detection_thread = DetectionThread(self.model, 0, conf, iou)
        self.detection_thread.frame_received.connect(self.on_frame_received)
        self.detection_thread.finished_signal.connect(self.on_detection_finished)
        self.detection_thread.start()

        self.update_status("正在从摄像头检测...")

🔐登录注册验证

对应文件:LoginWindow.py

# 账户验证核心逻辑
def handle_login(self):
    username = self.username_input.text().strip()
    password = self.password_input.text().strip()
    
    if not username or not password:
        QMessageBox.warning(self, "警告", "用户名和密码不能为空!")
        return
    
    if username in self.accounts and self.accounts[username] == password:
        self.accept()  # 验证通过
    else:
        QMessageBox.warning(self, "错误", "用户名或密码错误!")

# 密码强度检查(注册时)
def handle_register(self):
    if len(password) < 6:  # 密码长度≥6位
        QMessageBox.warning(self, "警告", "密码长度至少为6位!")

🎯 多重检测模式

对应文件:main.py

图片检测

def detect_image(self):
    file_path, _ = QFileDialog.getOpenFileName(
        self, "选择图片", "", "图片文件 (*.jpg *.jpeg *.png *.bmp)")
    if file_path:
        self.detection_thread = DetectionThread(self.model, file_path, conf, iou)
        self.detection_thread.start()  # 启动检测线程

视频检测

def detect_video(self):
    file_path, _ = QFileDialog.getOpenFileName(
        self, "选择视频", "", "视频文件 (*.mp4 *.avi *.mov)")
    if file_path:
        self.video_writer = cv2.VideoWriter()  # 初始化视频写入器
        self.detection_thread = DetectionThread(self.model, file_path, conf, iou)

实时摄像头

def detect_camera(self):
    self.detection_thread = DetectionThread(self.model, 0, conf, iou)  # 摄像头设备号0
    self.detection_thread.start()

🖼️ 沉浸式可视化

对应文件:UiMain.py

双画面显示

def display_image(self, label, image):
    q_img = QImage(image.data, w, h, bytes_per_line, QImage.Format_RGB888)
    pixmap = QPixmap.fromImage(q_img)
    label.setPixmap(pixmap.scaled(label.size(), Qt.KeepAspectRatio))  # 自适应缩放

结果表格

def add_detection_result(self, class_name, confidence, x, y):
    self.results_table.insertRow(row)
    items = [
        QTableWidgetItem(class_name),  # 类别列
        QTableWidgetItem(f"{confidence:.2f}"),  # 置信度
        QTableWidgetItem(f"{x:.1f}"),  # X坐标
        QTableWidgetItem(f"{y:.1f}")   # Y坐标
    ]

⚙️ 参数配置系统

对应文件:UiMain.py

双阈值联动控制

# 置信度阈值同步
def update_confidence(self, value):
    confidence = value / 100.0
    self.confidence_spinbox.setValue(confidence)  # 滑块→数值框
    self.confidence_label.setText(f"置信度阈值: {confidence:.2f}")

# IoU阈值同步  
def update_iou(self, value):
    iou = value / 100.0
    self.iou_spinbox.setValue(iou)

✨ UI美学设计

对应文件:UiMain.py

科幻风格按钮

def create_button(self, text, color):
    return f"""
    QPushButton {{
        border: 1px solid {color};
        color: {color};
        border-radius: 6px;
    }}
    QPushButton:hover {{
        background-color: {self.lighten_color(color, 10)};
        box-shadow: 0 0 10px {color};  # 悬停发光效果
    }}
    """

动态状态栏

def update_status(self, message):
    self.status_bar.showMessage(
        f"状态: {message} | 最后更新: {time.strftime('%H:%M:%S')}"  # 实时时间戳
    )

🔄 智能工作流

对应文件:main.py

线程管理

class DetectionThread(QThread):
    frame_received = pyqtSignal(np.ndarray, np.ndarray, list)  # 信号量通信
    
    def run(self):
        while self.running:  # 多线程检测循环
            results = self.model(frame, conf=self.conf, iou=self.iou)
            self.frame_received.emit(original_frame, result_frame, detections)

七、项目源码(视频简介)

基于深度学习YOLOv11的轴承缺陷识别检测系统(YOLOv11+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)_哔哩哔哩_bilibili

基于深度学习YOLOv11的轴承缺陷识别检测系统(YOLOv11+YOLO数据集+UI界面+登录注册界面+Python项目源码+模型)

### 系统设计与实现 #### 1. YOLOv11 模型训练 YOLOv11 是一种高效的实时目标检测模型,适用于缺陷检测等工业场景。在实现工件缺陷检测系统时,首先需要使用 YOLOv11 进行模型训练。以下是一个简单的训练代码示例: ```python import warnings from ultralytics import YOLO warnings.filterwarnings('ignore') if __name__ == '__main__': model = YOLO('ultralytics/cfg/models/11/yolo11.yaml') model.train(data='data/TopWeld.yaml', cache=False, imgsz=640, epochs=200, batch=8, close_mosaic=10, device='0', optimizer='SGD', project='runs/train', name='exp') ``` 该代码通过 `ultralytics` 库加载 YOLOv11 的配置文件,并使用指定的数据集进行训练。训练参数包括图像尺寸 (`imgsz`)、训练轮数 (`epochs`)、批量大小 (`batch`) 等[^3]。 #### 2. 数据集准备 数据集缺陷检测系统的核心组成部分。通常,数据集应包含大量带有标注的图像,标注信息包括缺陷的位置和类别。可以使用开源数据集作为起点,或者根据具体需求自行构建数据集。例如,一个典型的 YAML 配置文件如下所示: ```yaml train: ../data/images/train/ val: ../data/images/val/ nc: 5 names: ['LouHan', 'DuanHan', 'BaoDian', 'DuanXuHan', 'NeiCeXiaCi'] ``` 该配置文件指定了训练集和验证集的路径、类别数量以及类别名称[^3]。 #### 3. PySide6 GUI 设计 PySide6 是基于 Qt6 的 Python 绑定库,用于开发图形用户界面(GUI)。设计一个简单的 PySide6 界面可以通过以下步骤完成: - **设计 GUI**:使用 Qt Designer 工具拖拽控件或手动编写代码创建界面。 - **响应 UI 操作**:使用信号与槽机制连接界面操作(如按钮点击)与业务逻辑。 - **打包发布**:将应用程序打包为可执行文件以便部署。 以下是一个简单的 PySide6 界面示例代码: ```python import sys from PySide6.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QFileDialog from PySide6.QtCore import Qt class DefectDetectionApp(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("YOLOv11 缺陷检测系统") self.setGeometry(100, 100, 400, 300) self.label = QLabel("请选择一张图片", self) self.label.setAlignment(Qt.AlignCenter) self.button = QPushButton("选择图片", self) self.button.clicked.connect(self.open_image_dialog) layout = QVBoxLayout() layout.addWidget(self.label) layout.addWidget(self.button) container = QWidget() container.setLayout(layout) self.setCentralWidget(container) def open_image_dialog(self): file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Image Files (*.png *.jpg *.bmp)") if file_name: self.label.setText(f"已选择图片: {file_name}") if __name__ == "__main__": app = QApplication(sys.argv) window = DefectDetectionApp() window.show() sys.exit(app.exec()) ``` 该代码创建了一个简单的窗口应用,包含一个标签和一个按钮,用户可以通过按钮选择图片并显示在界面上[^2]。 #### 4. 系统集成 将 YOLOv11 模型集成到 PySide6 界面中,可以通过调用训练好的模型对用户上传的图片进行推理。以下是一个简单的推理函数示例: ```python def detect_defects(image_path): model = YOLO('runs/train/exp/weights/best.pt') # 加载训练好的模型 results = model.predict(source=image_path, save=True) # 进行预测并保存结果 return results ``` 在 GUI 中调用此函数,将用户选择的图片路径传递给它,并在界面上显示检测结果即可实现完整的缺陷检测系统。 #### 5. 打包发布 使用 PyInstaller 可以轻松地将 Python 应用程序打包为独立的可执行文件。安装 PyInstaller 并打包应用程序的命令如下: ```bash pip install pyinstaller pyinstaller --onefile your_script.py ``` 打包完成后,可以在 `dist` 目录下找到生成的可执行文件,方便在没有 Python 环境的设备上运行[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值