如何使用YOLOv8训练这套——苹果成熟度好坏腐烂检测数据集 4类 5000张 带标注 voc yolo 实现可视化及评估
label| pic_ num n| box_ num
good apple:(321,695)
soso_ apple:(323,604)
rotten_ apple: (4075, 10834)
disease_ apple: (553, 1247)
total: (5190, 13380)
如何基于苹果成熟度和腐烂检测数据集构建一个使用YOLOv8进行目标检测的系统。以下是详细的步骤和完整的代码示例。
首先确保你已经安装了必要的库,包括PyTorch、YOLOv8和其他相关库。
pip install torch torchvision opencv-python-headless matplotlib pillow PyQt5 ultralytics
将你的数据集组织成YOLOv8所需的格式。假设你的数据集目录结构如下:
dataset/
├── images/
│ ├── train/
│ │ ├── image1.jpg
│ │ └── ...
│ └── val/
│ ├── image1.jpg
│ └── ...
└── labels/
├── train/
│ ├── image1.txt
│ └── ...
└── val/
├── image1.txt
└── ...
每个图像文件对应一个标签文件,标签文件包含对象的类别ID和边界框坐标(x_center, y_center, width, height),归一化到[0, 1]范围。
创建一个data.yaml
文件来定义数据集路径和类别信息。
# dataset/data.yaml
train: ./images/train
val: ./images/val
nc: 4
names: ['good_apple', 'soso_apple', 'rotten_apple', 'disease_apple']
使用YOLOv8训练模型。假设你已经在项目目录下。
yolo task=detect mode=train model=yolov8n.pt data=../dataset/data.yaml epochs=50 imgsz=640 batch=16 name=apple_detection
训练完成后,你可以使用以下命令评估模型性能。
yolo task=detect mode=val model=runs/detect/apple_detection/weights/best.pt data=../dataset/data.yaml
使用PyQt5构建一个简单的GUI应用程序,允许用户上传图像并查看检测结果。
[<title="Apple Maturity and Rot Detection GUI using YOLOv8">]
import sys
import torch
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QFileDialog, QMessageBox
from PyQt5.QtGui import QPixmap, QImage
from PIL import Image
import cv2
class AppleDetectionApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Apple Maturity and Rot Detection Using YOLOv8")
self.setGeometry(100, 100, 800, 600)
self.original_image_label = QLabel(self)
self.detected_image_label = QLabel(self)
self.upload_button = QPushButton("Upload Image", self)
self.upload_button.clicked.connect(self.upload_image)
self.process_button = QPushButton("Process Image", self)
self.process_button.clicked.connect(self.process_image)
self.process_button.setEnabled(False)
layout = QVBoxLayout()
layout.addWidget(self.original_image_label)
layout.addWidget(self.detected_image_label)
layout.addWidget(self.upload_button)
layout.addWidget(self.process_button)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
# Load pre-trained model
self.model = torch.hub.load('ultralytics/yolov8', 'custom', path='runs/detect/apple_detection/weights/best.pt')
def upload_image(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "QFileDialog.getOpenFileName()", "", "Images (*.png *.xpm *.jpg);;All Files (*)", options=options)
if file_name:
self.image_path = file_name
pixmap = QPixmap(file_name)
self.original_image_label.setPixmap(pixmap.scaled(350, 350))
self.process_button.setEnabled(True)
def process_image(self):
if hasattr(self, 'image_path'):
image = Image.open(self.image_path).convert('RGB')
results = self.model(image)
detected_image = results.render()[0]
detected_pixmap = QPixmap.fromImage(self.convert_to_qimage(detected_image))
self.detected_image_label.setPixmap(detected_pixmap.scaled(350, 350))
else:
QMessageBox.warning(self, "Warning", "Please upload an image first.")
def convert_to_qimage(self, pil_image):
if pil_image.mode == "RGB":
format = QImage.Format_RGB888
elif pil_image.mode == "RGBA":
format = QImage.Format_RGBA8888
else:
raise ValueError(f"Unsupported image mode: {pil_image.mode}")
qimage = QImage(pil_image.tobytes(), pil_image.width, pil_image.height, format)
return qimage
if __name__ == "__main__":
app = QApplication(sys.argv)
window = AppleDetectionApp()
window.show()
sys.exit(app.exec_())
data.yaml
文件定义数据集路径和类别信息。apple_detection_gui.py
,然后运行该脚本:python apple_detection_gui.py