基于深度学习YOLOv10的木材缺陷检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)

一、项目介绍

摘要

本项目基于YOLOv10算法开发了一套高效准确的木材缺陷检测系统,专门用于识别和分类木材表面常见的三种缺陷:裂纹(Crack)、死结(Dead Knot)和活结(Live Knot)。系统通过对木材表面图像进行实时分析,能够快速定位缺陷位置并判断其类型,为木材质量评估和分级提供自动化解决方案。项目使用包含2606张标注图像的数据集进行训练和验证,其中训练集2259张,验证集173张,测试集174张。实验结果表明,该系统在木材缺陷检测任务上达到了较高的准确率和召回率,能够满足工业生产中对木材质量检测的需求。

项目意义

木材缺陷检测在木材加工和质量控制领域具有重要意义。传统的人工检测方法效率低下、成本高昂且容易因疲劳导致误检漏检。本项目的实施将带来以下重要价值:

  1. 提高检测效率:自动化检测系统可以24小时不间断工作,单次检测时间可缩短至毫秒级,大幅提升木材生产线的检测吞吐量。

  2. 降低人工成本:减少对专业质检人员的依赖,长期使用可显著降低企业人力成本。

  3. 提升检测一致性:算法检测结果稳定可靠,避免了人工检测中因主观判断和疲劳导致的检测标准不一致问题。

  4. 数字化质量管理:检测结果可数字化记录和分析,便于质量追溯和生产工艺优化。

  5. 促进产业升级:为木材加工企业向智能制造转型提供关键技术支撑,提升产品竞争力。

目录

一、项目介绍

摘要

项目意义

二、项目功能展示

系统功能

图片检测

视频检测

摄像头实时检测

三、数据集介绍

数据集概述

数据集特点

数据集配置文件

数据集制作流程

四、项目环境配置

创建虚拟环境

pycharm中配置anaconda

安装所需要库

五、模型训练

训练代码

训练结果

六、核心代码

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


基于深度学习YOLOv10的木材缺陷检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)_哔哩哔哩_bilibili

基于深度学习YOLOv10的木材缺陷检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)

二、项目功能展示

系统功能

✅ 图片检测:可对图片进行检测,返回检测框及类别信息。

✅ 视频检测:支持视频文件输入,检测视频中每一帧的情况。

✅ 摄像头实时检测:连接USB 摄像头,实现实时监测。

参数实时调节(置信度和IoU阈值)

  • 图片检测

        该功能允许用户通过单张图片进行目标检测。输入一张图片后,YOLO模型会实时分析图像,识别出其中的目标,并在图像中框出检测到的目标,输出带有目标框的图像。 

  • 视频检测

        视频检测功能允许用户将视频文件作为输入。YOLO模型将逐帧分析视频,并在每一帧中标记出检测到的目标。最终结果可以是带有目标框的视频文件或实时展示,适用于视频监控和分析等场景。

  • 摄像头实时检测

        该功能支持通过连接摄像头进行实时目标检测。YOLO模型能够在摄像头拍摄的实时视频流中进行目标检测,实时识别并显示检测结果。此功能非常适用于安防监控、无人驾驶、智能交通等应用,提供即时反馈。

核心特点:

  • 高精度:基于YOLO模型,提供精确的目标检测能力,适用于不同类型的图像和视频。
  • 实时性:特别优化的算法使得实时目标检测成为可能,无论是在视频还是摄像头实时检测中,响应速度都非常快。
  • 批量处理:支持高效的批量图像和视频处理,适合大规模数据分析。

三、数据集介绍

数据集概述

本项目构建了一个专业化的木材缺陷图像数据集,共包含2606张高质量标注图像,按照8:1:1的比例划分为训练集(2259张)、验证集(173张)和测试集(174张)。数据集涵盖了三种典型的木材表面缺陷:

  1. 裂纹(Crack):木材表面或内部的断裂现象

  2. 死结(Dead Knot):树枝枯死后在树干中形成的深色结疤

  3. 活结(Live Knot):活树枝在树干中形成的结疤

数据集特点

  1. 多样性:数据集包含了不同树种(如松木、橡木、桦木等)、不同光照条件、不同拍摄角度和不同缺陷大小的样本,确保了模型的泛化能力。

  2. 高质量标注:所有图像均由专业质检人员标注,标注精度达到像素级,边界框紧密贴合缺陷区域。

  3. 平衡性:三类缺陷的样本数量经过平衡处理,避免了类别不平衡导致的模型偏差。

  4. 真实工业场景:大部分图像采集自实际木材加工生产线,包含真实的背景干扰和噪声,增强了模型的实用性。

  5. 多尺度缺陷:数据集中既包含大尺寸明显缺陷,也包含小尺寸难以察觉的缺陷,考验模型的多尺度检测能力。

数据集配置文件

数据集采用YOLO格式进行组织,配置文件内容如下:

# YOLOv10木材缺陷检测数据集配置文件
path: ../datasets/wood_defect
train: images/train
val: images/val
test: images/test
nc: 3
names: ['Crack', 'Dead Knot', 'Live Knot']

# 图像参数
img_size: 640  # 训练图像尺寸
batch_size: 16  # 训练批次大小
workers: 4  # 数据加载线程数
 

数据集制作流程

  1. 原始数据采集

    • 使用工业CCD相机在木材生产线上采集原始图像

    • 设置多角度光源确保缺陷清晰可见

    • 采集不同树种、不同等级的木材样本

  2. 数据清洗

    • 剔除模糊、过曝或欠曝的图像

    • 去除无缺陷的空白图像

    • 检查并删除标注错误的样本

  3. 数据标注

    • 使用LabelImg等标注工具手动标注缺陷区域

    • 为每个缺陷划定精确的边界框

    • 指定对应的缺陷类别标签

  4. 数据增强

    • 应用旋转、翻转、缩放等几何变换

    • 调整亮度、对比度、饱和度等色彩参数

    • 添加高斯噪声模拟工业环境干扰

    • 使用mosaic增强提升小目标检测能力

  5. 数据集划分

    • 按照8:1:1比例随机划分训练集、验证集和测试集

    • 确保各类别在各数据集中分布均衡

    • 检查并避免同一木材样本出现在不同数据集

  6. 格式转换

    • 将标注转换为YOLO格式的txt文件

    • 生成数据集索引文件

    • 创建数据集配置文件

四、项目环境配置

创建虚拟环境

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

终端输入

conda create -n yolov10 python==3.9

激活虚拟环境

conda activate yolov10
 

安装cpu版本pytorch

pip install torch torchvision torchaudio

pycharm中配置anaconda

安装所需要库

pip install -r requirements.txt

五、模型训练

训练代码

from ultralytics import YOLOv10

model_path = 'yolov10s.pt'
data_path = 'datasets/data.yaml'

if __name__ == '__main__':
    model = YOLOv10(model_path)
    results = model.train(data=data_path,
                          epochs=500,
                          batch=64,
                          device='0',
                          workers=0,
                          project='runs/detect',
                          name='exp',
                          )
根据实际情况更换模型
yolov10n.yaml (nano):轻量化模型,适合嵌入式设备,速度快但精度略低。
yolov10s.yaml (small):小模型,适合实时任务。
yolov10m.yaml (medium):中等大小模型,兼顾速度和精度。
yolov10b.yaml (base):基本版模型,适合大部分应用场景。
yolov10l.yaml (large):大型模型,适合对精度要求高的任务。
  • --batch 64:每批次64张图像。
  • --epochs 500:训练500轮。
  • --datasets/data.yaml:数据集配置文件。
  • --weights yolov10s.pt:初始化模型权重,yolov10s.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 YOLOv10
from UiMain import UiMainWindow
import time
import os
 
 
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 = YOLOv10(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("正在从摄像头检测...")
 
    def stop_detection(self):
        if self.detection_thread and self.detection_thread.isRunning():
            self.detection_thread.stop()
            self.detection_thread.quit()
            self.detection_thread.wait()
 
        if self.video_writer:
            self.video_writer.release()
            self.video_writer = None
 
        self.is_camera_running = False
        self.is_video_running = False
        self.update_status("检测已停止")
 
    def on_frame_received(self, original_frame, result_frame, detections):
        # 更新原始图像和结果图像
        self.display_image(self.original_image_label, original_frame)
        self.display_image(self.result_image_label, result_frame)
 
        # 保存当前结果帧用于后续保存
        self.last_detection_result = result_frame  # 新增:保存检测结果
 
        # 更新表格
        self.clear_results()
        for class_name, confidence, x, y in detections:
            self.add_detection_result(class_name, confidence, x, y)
 
        # 保存视频帧
        if self.video_writer:
            self.video_writer.write(cv2.cvtColor(result_frame, cv2.COLOR_RGB2BGR))
 
    def on_detection_finished(self):
        if self.video_writer:
            self.video_writer.release()
            self.video_writer = None
            self.update_status("视频检测完成,结果已保存")
        elif self.is_camera_running:
            self.update_status("摄像头检测已停止")
        else:
            self.update_status("图片检测完成")
 
    def save_result(self):
        if not hasattr(self, 'last_detection_result') or self.last_detection_result is None:
            QMessageBox.warning(self, "警告", "没有可保存的检测结果")
            return
 
        save_dir = "results"
        os.makedirs(save_dir, exist_ok=True)
        timestamp = time.strftime("%Y%m%d_%H%M%S")
 
        if self.is_camera_running or self.is_video_running:
            # 保存当前帧为图片
            save_path = os.path.join(save_dir, f"snapshot_{timestamp}.jpg")
            cv2.imwrite(save_path, cv2.cvtColor(self.last_detection_result, cv2.COLOR_RGB2BGR))
            self.update_status(f"截图已保存: {save_path}")
        else:
            # 保存图片检测结果
            save_path = os.path.join(save_dir, f"result_{timestamp}.jpg")
            cv2.imwrite(save_path, cv2.cvtColor(self.last_detection_result, cv2.COLOR_RGB2BGR))
            self.update_status(f"检测结果已保存: {save_path}")
 
    def closeEvent(self, event):
        self.stop_detection()
        event.accept()
 
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
 
    # 设置应用程序样式
    app.setStyle("Fusion")
 
    # 创建并显示主窗口
    window = MainWindow()
    window.show()
 
    sys.exit(app.exec_())

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

        完整全部资源文件(包括测试图片、视频,py文件,训练数据集、训练代码、界面代码等),这里已打包上传至博主的面包多平台,见可参考博客与视频,已将所有涉及的文件同时打包到里面,点击即可运行,完整文件截图如下:

基于深度学习YOLOv10的木材缺陷检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)_哔哩哔哩_bilibili

基于深度学习YOLOv10的木材缺陷检测系统(YOLOv10+YOLO数据集+UI界面+Python项目源码+模型)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人工智能_SYBH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值