Skip to content

YOLOv8手机屏幕裂纹检测

任务描述

YOLOv8 手机屏幕裂纹检测

包含:

  • 环境安装
  • 数据集准备(自定义裂纹标注)
  • 模型训练(迁移学习,快速收敛)
  • 单图/批量/摄像头实时检测(ONNX 部署)
  • 模型导出(ONNX 格式)
  • Docker 一键部署
  • Node.js 端:调用 YOLO 服务

整体流程

    1. 准备标注好的裂纹数据集(自定义类别)
    1. 用 YOLOv8 预训练权重微调(迁移学习,小样本也能训)
    1. 训练完成后,用模型检测屏幕裂纹

第一步:安装环境

bash
pip install ultralytics opencv-python numpy

第二步:准备裂纹数据集

  • 数据集配置文件 screen_crack.yaml
# 数据集根路径
path: ./datasets/screen_crack

# 训练/验证集路径
train: train/images
val: val/images
test: test/images

# 类别:只有1类,裂纹
names:
  0: crack

第三步:训练裂纹检测模型

  • train_crack.py
python
from ultralytics import YOLO

def train_crack_model():
    # 加载 YOLOv8n 预训练权重(自动下载,迁移学习)
    # 小样本用 n/s 足够,精度要求高用 m
    model = YOLO("yolov8n.pt")

    # 开始训练
    results = model.train(
        data="screen_crack.yaml",   # 你的数据集配置
        epochs=100,                 # 训练轮数,小样本50-100足够
        imgsz=640,                  # 输入尺寸,裂纹小目标建议640+
        batch=8,                    # 批次大小
        device=0,                   # 有GPU改成 device=0
        patience=20,                # 早停,20轮不提升就停止
        project="crack_detect",     # 训练结果保存目录
        name="yolov8_crack",
        # 数据增强,提升小样本泛化能力
        augment=True,
        flipud=0.2,
        fliplr=0.5,
        mosaic=1.0,
        mixup=0.1
    )
    print("✅ 训练完成!最佳模型保存在:crack_detect/yolov8_crack/weights/best.pt")

if __name__ == "__main__":
    train_crack_model()

第四步:裂纹检测推理代码

  • 支持单图 / 批量 / 摄像头实时检测. detect_crack.py
python
from ultralytics import YOLO
import cv2
import os

# 加载你训练好的裂纹模型
model = YOLO("crack_detect/yolov8_crack/weights/best.pt")

# ------------------------------
# 1. 单张图片检测
# ------------------------------
def detect_single_image(img_path, save_path="result.jpg"):
    # 推理,置信度阈值调低,适配小裂纹
    results = model.predict(
        source=img_path,
        conf=0.25,    # 裂纹小,置信度阈值调低
        imgsz=640,
        save=False
    )

    # 读取原图
    img = cv2.imread(img_path)
    has_crack = False

    # 绘制检测框
    for r in results:
        for box in r.boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            conf = box.conf[0].item()
            cls = box.cls[0].item()

            # 画裂纹框
            cv2.rectangle(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
            cv2.putText(img, f"crack {conf:.2f}", (x1, y1-10),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,0,255), 2)
            has_crack = True

    # 保存结果
    cv2.imwrite(save_path, img)
    print(f"✅ 检测完成,结果保存到: {save_path}")
    print(f"🔍 检测结果: {'发现裂纹!' if has_crack else '未发现裂纹'}")
    return has_crack, img

# ------------------------------
# 2. 批量检测文件夹
# ------------------------------
def detect_batch_images(folder_path):
    for file in os.listdir(folder_path):
        if file.endswith((".jpg", ".png", ".jpeg")):
            print(f"处理: {file}")
            detect_single_image(
                os.path.join(folder_path, file),
                save_path=f"result_{file}"
            )

# ------------------------------
# 3. 摄像头实时检测(对着手机屏幕检测)
# ------------------------------
def detect_camera():
    cap = cv2.VideoCapture(0)  # 0=电脑摄像头
    print("📷 摄像头已开启,按 q 退出")

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret: break

        # 推理
        results = model.predict(source=frame, conf=0.25, imgsz=640, verbose=False)
        has_crack = False

        # 画框
        for r in results:
            for box in r.boxes:
                x1, y1, x2, y2 = map(int, box.xyxy[0])
                conf = box.conf[0].item()
                cv2.rectangle(frame, (x1, y1), (x2, y2), (0,0,255), 2)
                cv2.putText(frame, f"crack {conf:.2f}", (x1,y1-10),
                            cv2.FONT_HERSHEY_SIMPLEX,0.9,(0,0,255),2)
                has_crack = True

        # 顶部提示
        cv2.putText(frame, "CRACK DETECTED!" if has_crack else "NO CRACK",
                    (10,30), cv2.FONT_HERSHEY_SIMPLEX,1,
                    (0,0,255) if has_crack else (0,255,0), 2)

        cv2.imshow("Screen Crack Detection", frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

# ------------------------------
# 运行入口
# ------------------------------
if __name__ == "__main__":
    # 👉 选你要的模式:

    # 1. 单图检测
    # detect_single_image("test_screen.jpg")

    # 2. 批量检测
    # detect_batch_images("test_images/")

    # 3. 摄像头实时检测(对着手机屏幕)
    detect_camera()

使用说明

  • 训练:准备好标注数据后,运行 python train_crack.py
  • 检测:
    • 单图:取消注释 detect_single_image,传入你的图片路径
    • 批量:取消注释 detect_batch_images,传入图片文件夹
    • 实时摄像头:直接运行,打开摄像头,把手机屏幕对着摄像头,就能实时检测裂纹

效果优化

  • 小裂纹检测:把 imgsz 调到 800/1024,提升小目标精度
  • 样本少:多做数据增强,或者用 yolov8s.pt 代替 n,精度更高
  • 标注:标注裂纹的时候,尽量框紧裂纹,不要留太多空白
  • 推理:置信度阈值 conf 可以调到 0.2,漏检少一点

京ICP备2024093538号-1