From 0e04debb7bdbf02140aa76eebc2ee01c2a58ea5e Mon Sep 17 00:00:00 2001 From: wonder Date: Fri, 7 Nov 2025 15:09:34 +0800 Subject: [PATCH] =?UTF-8?q?=20=F0=9F=94=84Update:=20[Lab-5]=20=E5=9F=BA?= =?UTF-8?q?=E4=BA=8EYOLOv8=E7=9A=84=E5=B7=A5=E4=B8=9A=E7=BC=BA=E9=99=B7?= =?UTF-8?q?=E6=A3=80=E6=B5=8B=E5=AE=9E=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +- Lab-5/src/__init__.py | 0 Lab-5/src/detect.py | 20 ++++++++++++ Lab-5/src/pcb_defect.yaml | 8 +++++ Lab-5/src/train.py | 16 ++++++++++ Lab-5/src/transform_yolo.py | 61 +++++++++++++++++++++++++++++++++++++ Lab-5/src/val.py | 9 ++++++ 7 files changed, 116 insertions(+), 1 deletion(-) create mode 100644 Lab-5/src/__init__.py create mode 100644 Lab-5/src/detect.py create mode 100644 Lab-5/src/pcb_defect.yaml create mode 100644 Lab-5/src/train.py create mode 100644 Lab-5/src/transform_yolo.py create mode 100644 Lab-5/src/val.py diff --git a/.gitignore b/.gitignore index fff35e4..4865c3a 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,5 @@ model runs datasets -yolov8n.pt \ No newline at end of file +yolov8n.pt +dataset \ No newline at end of file diff --git a/Lab-5/src/__init__.py b/Lab-5/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Lab-5/src/detect.py b/Lab-5/src/detect.py new file mode 100644 index 0000000..71f8f70 --- /dev/null +++ b/Lab-5/src/detect.py @@ -0,0 +1,20 @@ +from ultralytics import YOLO +import cv2 + +# 加载最佳模型 +model = YOLO('runs/detect/yolov8n_pcb_defect_exp14/weights/best.pt') + +# 在单张图像上推理 +results = model('../dataset/images/val/patches_296.jpg', save=True, conf=0.5) + +# 可视化结果(使用OpenCV) +for result in results: + plotted_img = result.plot() # 绘制检测结果 + cv2.imshow('Detection Result', plotted_img) + cv2.waitKey(0) + cv2.destroyAllWindows() + +# 支持文件夹、视频、摄像头推理 +# results = model('path/to/video.mp4', save=True, show=True) # 视频文件 +# results = model(0, show=True) # 摄像头(0为默认摄像头) + diff --git a/Lab-5/src/pcb_defect.yaml b/Lab-5/src/pcb_defect.yaml new file mode 100644 index 0000000..da21a59 --- /dev/null +++ b/Lab-5/src/pcb_defect.yaml @@ -0,0 +1,8 @@ +path: ../dataset # 数据集根目录 +train: images/train # 训练图像路径 +val: images/val # 验证图像路径 + +# 类别数 +nc: 6 +# 类别名称 +names: ['missing_hole', 'mouse_bite', 'open_circuit', 'short', 'spur', 'spurious_copper'] diff --git a/Lab-5/src/train.py b/Lab-5/src/train.py new file mode 100644 index 0000000..2021bf5 --- /dev/null +++ b/Lab-5/src/train.py @@ -0,0 +1,16 @@ +from ultralytics import YOLO + +# 加载预训练模型 +model = YOLO('yolov8n.pt') # 可选模型: yolov8n, yolov8s, yolov8m, yolov8l, yolov8x + +# 训练模型 +results = model.train( + data='pcb_defect.yaml', # 数据集配置文件路径 + epochs=20, # 训练轮次 + imgsz=640, # 输入图像大小 + batch=16, # 批次大小(根据GPU内存调整) + name='yolov8n_pcb_defect_exp1', # 实验名称 + optimizer='AdamW', # 优化器 + lr0=0.001, # 初始学习率 + device='cpu' # 使用设备(如GPU:device=0) +) diff --git a/Lab-5/src/transform_yolo.py b/Lab-5/src/transform_yolo.py new file mode 100644 index 0000000..50246ad --- /dev/null +++ b/Lab-5/src/transform_yolo.py @@ -0,0 +1,61 @@ +import xml.etree.ElementTree as ET + +import pickle +import os +from os import listdir, getcwd +from os.path import join +import glob + +classes = ['crazing', 'inclusion', 'patches', 'pitted_surface', 'rolled-in_scale', 'scratches'] # xml文件中标记的种类 + + +def convert(size, box): + dw = 1.0 / size[0] + dh = 1.0 / size[1] + x = (box[0] + box[1]) / 2.0 + y = (box[2] + box[3]) / 2.0 + w = box[1] - box[0] + h = box[3] - box[2] + x = x * dw + w = w * dw + y = y * dh + h = h * dh + return (x, y, w, h) + + +def convert_annotation(image_name): + try: + in_file = open('../dataset/annotations/val/' + image_name[:-3] + 'xml', encoding='utf-8') # 原来的xml文件路径 + except FileNotFoundError: + print(f"Warning: XML file for {image_name} not found, skipping.") + return + + out_file = open('../dataset/labels/val/' + image_name[:-3] + 'txt', 'w', encoding='utf-8') # 转换后的txt文件存放路径 + tree = ET.parse(in_file) + root = tree.getroot() + size = root.find('size') + w = int(size.find('width').text) + h = int(size.find('height').text) + + for obj in root.iter('object'): + difficult = obj.find('difficult').text + cls = obj.find('name').text + if cls not in classes or int(difficult) == 1: + continue + cls_id = classes.index(cls) + xmlbox = obj.find('bndbox') + b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text), + float(xmlbox.find('ymax').text)) + bb = convert((w, h), b) + out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n') + in_file.close() + out_file.close() + + +wd = getcwd() + +if __name__ == '__main__': + + for image_path in glob.glob("../dataset/images/val/*.jpg"): # xml对应的图片的路径 + image_name = image_path.split('\\')[-1] + convert_annotation(image_name) \ No newline at end of file diff --git a/Lab-5/src/val.py b/Lab-5/src/val.py new file mode 100644 index 0000000..ffd7b09 --- /dev/null +++ b/Lab-5/src/val.py @@ -0,0 +1,9 @@ +from ultralytics import YOLO + +# 加载最佳模型 +best_model = YOLO('runs/detect/yolov8n_pcb_defect_exp14/weights/best.pt') + +# 在测试集上评估 +metrics = best_model.val() # 程序会自动计算mAP等指标 +print(f"mAP@0.5: {metrics.box.map50}") +print(f"mAP@0.5:0.95: {metrics.box.map}")