当前位置: 首页 > news >正文

利用深度学习目标检测框架yolov8YOLO8训练使用草莓成熟度 数据集

利用深度学习目标检测框架yolov8YOLO8训练使用草莓成熟度 数据集

共1049张草莓图片,已将图片分为训练集和验证集,其中训练集(train)734张,验证集(valid)210张,测试集105张

yolo格式标签(.txt)文件,xml标签文件

有未成熟(low),欠成熟(medium),成熟(high)三种类别

备注:文章里所有代码仅供参考!=
实现一个基于 YOLOv8 的草莓成熟度检测系统。以下是详细的步骤:

  1. 数据准备:确保数据集格式正确。
  2. 环境部署:安装必要的库。
  3. 模型训练:使用 YOLOv8 训练目标检测模型。
  4. 评估模型:评估训练好的模型性能。
  5. PyQt5 GUI 开发:创建一个简单的 GUI 来加载和运行模型进行实时预测。

数据准备

同学呀:假设你已经有一个包含 1049 张草莓图片的数据集,并且标注格式为 YOLO 格式的 TXT 文件。

数据集结构示例
dataset/ ├── images/ │ ├── train/ │ │ ├── image1.jpg │ │ ├── image2.jpg │ │ └── ... │ ├── valid/ │ │ ├── image3.jpg │ │ ├── image4.jpg │ │ └── ... │ └── test/ │ ├── image5.jpg │ ├── image6.jpg │ └── ... ├── labels/ │ ├── train/ │ │ ├── image1.txt │ │ ├── image2.txt │ │ └── ... │ ├── valid/ │ │ ├── image3.txt │ │ ├── image4.txt │ │ └── ... │ └── test/ │ ├── image5.txt │ ├── image6.txt │ └── ... └── dataset.yaml

dataset.yaml内容如下:

train:./images/trainval:./images/validtest:./images/testnc:3names:['low','medium','high']

每个图像对应的标签文件是一个文本文件,每行表示一个边界框,格式为:

<class_id> <x_center> <y_center> <width> <height>

环境部署说明

确保你已经安装了必要的库,如上所述。

安装依赖
# 创建虚拟环境(可选)conda create-nstrawberry_detection_envpython=3.8conda activate strawberry_detection_env# 安装PyTorchpipinstalltorch==1.9torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu111# 安装其他依赖pipinstallopencv-python pyqt5 ultralytics scikit-learn pandas matplotlib seaborn onnxruntime xml.etree.ElementTree

模型训练权重和指标可视化展示

我们将使用 YOLOv8 进行目标检测任务。

下载 YOLOv8 仓库
gitclone https://github.com/ultralytics/ultralytics.gitcdultralytics pipinstall-rrequirements.txt
训练 YOLOv8
[<title="Training YOLOv8 for Strawberry Maturity Detection">]importosfrompathlibimportPath# Define pathsdataset_path='path/to/dataset'weights_path='runs/detect/exp/weights/best.pt'# Create dataset.yamlyaml_content=f""" train:{Path(dataset_path)/'images/train'}val:{Path(dataset_path)/'images/valid'}test:{Path(dataset_path)/'images/test'}nc: 3 names: ['low', 'medium', 'high'] """withopen(Path(dataset_path)/'dataset.yaml','w')asf:f.write(yaml_content)# Train YOLOv8!yolo task=detect mode=train data={Path(dataset_path)/'dataset.yaml'}model=yolov8n.pt imgsz=256epochs=100batch=16name=strawberry_exp

请将path/to/dataset替换为实际的数据集路径。

模型评估

我们将使用 YOLOv8 提供的评估功能来评估训练好的模型性能。

评估 YOLOv8 模型
[<title="Evaluating YOLOv8 Model for Strawberry Maturity Detection">]fromultralyticsimportYOLO# Load the trained modelmodel_path='runs/detect/strawberry_exp/weights/best.pt'# Evaluate the modelmodel=YOLO(model_path)results=model.val()# Print evaluation resultsmetrics=results.metricsprint(metrics)

请将path/to/dataset替换为实际的数据集路径。

使用说明

  1. 配置路径

    • path/to/dataset设置为存放数据集的目录路径。
    • 确保runs/detect/strawberry_exp/weights/best.pt是训练好的 YOLOv8 模型权重路径。
  2. 运行脚本

    • 在终端中运行train_yolov8.py脚本来训练模型。
    • 在终端中运行evaluate_yolov8.py来评估模型性能。
  3. 注意事项

    • 确保所有必要的工具箱已安装,特别是 PyTorch 和 ultralytics。
    • 根据需要调整参数,如epochsimgsz

PyQt5 GUI 开发

我们将使用 PyQt5 创建一个简单的 GUI 来加载和运行 YOLOv8 模型进行实时预测。

主窗口代码main_window.py
[<title="PyQt5 Main Window for Strawberry Maturity Detection">]importsysimportcv2importnumpyasnpfromPyQt5.QtWidgetsimportQApplication,QMainWindow,QLabel,QPushButton,QVBoxLayout,QWidget,QFileDialogfromPyQt5.QtGuiimportQImage,QPixmapfromPyQt5.QtCoreimportQt,QTimerfromultralyticsimportYOLOclassMainWindow(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle("Strawberry Maturity Detection System")self.setGeometry(100,100,800,600)self.model=YOLO('runs/detect/strawberry_exp/weights/best.pt')self.initUI()definitUI(self):self.central_widget=QWidget()self.setCentralWidget(self.central_widget)self.layout=QVBoxLayout()self.image_label=QLabel(self)self.image_label.setAlignment(Qt.AlignCenter)self.layout.addWidget(self.image_label)self.load_image_button=QPushButton("Load Image",self)self.load_image_button.clicked.connect(self.load_image)self.layout.addWidget(self.load_image_button)self.load_video_button=QPushButton("Load Video",self)self.load_video_button.clicked.connect(self.load_video)self.layout.addWidget(self.load_video_button)self.start_detection_button=QPushButton("Start Detection",self)self.start_detection_button.clicked.connect(self.start_detection)self.layout.addWidget(self.start_detection_button)self.stop_detection_button=QPushButton("Stop Detection",self)self.stop_detection_button.clicked.connect(self.stop_detection)self.layout.addWidget(self.stop_detection_button)self.central_widget.setLayout(self.layout)self.cap=Noneself.timer=QTimer()self.timer.timeout.connect(self.update_frame)defload_image(self):options=QFileDialog.Options()file_name,_=QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()","","Images (*.png *.xpm *.jpg *.jpeg);;All Files (*)",options=options)iffile_name:self.image_path=file_name self.display_image(file_name)defdisplay_image(self,path):pixmap=QPixmap(path)scaled_pixmap=pixmap.scaled(self.image_label.width(),self.image_label.height(),Qt.KeepAspectRatio)self.image_label.setPixmap(scaled_pixmap)defload_video(self):options=QFileDialog.Options()file_name,_=QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()","","Videos (*.mp4 *.avi);;All Files (*)",options=options)iffile_name:self.video_path=file_name self.cap=cv2.VideoCapture(self.video_path)self.start_detection()defstart_detection(self):ifself.capisnotNoneandnotself.timer.isActive():self.timer.start(30)# Update frame every 30 msdefstop_detection(self):ifself.timer.isActive():self.timer.stop()self.cap.release()self.image_label.clear()defupdate_frame(self):ret,frame=self.cap.read()ifret:processed_frame=self.process_frame(frame)rgb_image=cv2.cvtColor(processed_frame,cv2.COLOR_BGR2RGB)h,w,ch=rgb_image.shape bytes_per_line=ch*w qt_image=QImage(rgb_image.data,w,h,bytes_per_line,QImage.Format_RGB888)pixmap=QPixmap.fromImage(qt_image)scaled_pixmap=pixmap.scaled(self.image_label.width(),self.image_label.height(),Qt.KeepAspectRatio)self.image_label.setPixmap(scaled_pixmap)else:self.stop_detection()defprocess_frame(self,frame):results=self.model(frame)forresultinresults:boxes=result.boxes.cpu().numpy()forboxinboxes:r=box.xyxy[0].astype(int)cls=int(box.cls[0])conf=box.conf[0]label=self.model.names[cls]text=f'{label}:{conf:.2f}'color_map={0:(0,0,255),# low1:(0,255,255),# medium2:(0,255,0)# high}color=color_map.get(cls,(255,255,255))# Default to white if class ID is unknowncv2.rectangle(frame,(r[0],r[1]),(r[2],r[3]),color,2)cv2.putText(frame,text,(r[0],r[1]-10),cv2.FONT_HERSHEY_SIMPLEX,0.9,color,2)returnframeif__name__=="__main__":app=QApplication(sys.argv)window=MainWindow()window.show()sys.exit(app.exec_())

使用说明

  1. 配置路径

    • path/to/dataset设置为存放数据集的目录路径。
    • 确保runs/detect/strawberry_exp/weights/best.pt是训练好的 YOLOv8 模型权重路径。
  2. 运行脚本

    • 在终端中运行train_yolov8.py脚本来训练模型。
    • 在终端中运行evaluate_yolov8.py来评估模型性能。
    • 在终端中运行main_window.py来启动 GUI 应用程序。
    • 点击“Load Image”按钮加载图像。
    • 点击“Load Video”按钮加载视频。
    • 点击“Start Detection”按钮开始检测。
    • 点击“Stop Detection”按钮停止检测。
  3. 注意事项

    • 确保所有必要的工具箱已安装,特别是 PyTorch 和 PyQt5。
    • 根据需要调整参数,如epochsimgsz

示例

假设你的数据文件夹结构如下:

dataset/ ├── images/ │ ├── train/ │ │ ├── image1.jpg │ │ ├── image2.jpg │ │ └── ... │ ├── valid/ │ │ ├── image3.jpg │ │ ├── image4.jpg │ │ └── ... │ └── test/ │ ├── image5.jpg │ ├── image6.jpg │ └── ... ├── labels/ │ ├── train/ │ │ ├── image1.txt │ │ ├── image2.txt │ │ └── ... │ ├── valid/ │ │ ├── image3.txt │ │ ├── image4.txt │ │ └── ... │ └── test/ │ ├── image5.txt │ ├── image6.txt │ └── ... └── dataset.yaml

并且每个.txt文件中都有正确的 YOLO 标签。运行main_window.py后,你可以通过点击按钮来加载图像或视频并进行草莓成熟度检测。

总结

构建一个完整的基于 YOLOv8 的草莓成熟度检测系统,包括数据集准备、环境部署、模型训练、指标可视化展示、评估和 PyQt5 GUI 开发。以下是所有相关的代码文件:

  1. 训练 YOLOv8 脚本(train_yolov8.py)
  2. 评估 YOLOv8 模型脚本(evaluate_yolov8.py)
  3. PyQt5 主窗口代码(main_window.py)
http://www.jsqmd.com/news/1003929/

相关文章:

  • Page Assist:在浏览器中无缝使用本地AI模型的终极指南
  • erm:去除语音语气词的本地工具,解决手动删除痛苦!
  • Pandas多维聚合实战:构建可切片、上卷、下钻的数据立方体
  • VS2010一键编译的eXosip2 4.0.0 + osip2 4.0.0完整工程包(含Win32/MFC支持)
  • AI-产品经理实战项目必修课
  • 2026年包头保安岗亭选购指南:从材质到服务的多维度行业观察 - 优质品牌商家
  • 3步搭建浏览器本地AI助手:Page Assist完整指南
  • Linux ioc_timer_fn iocost定时器与hweight更新
  • 虚拟化软件替代方案:如何在3个步骤内找到最适合你的开源解决方案?
  • 2026年台州杭州岗亭选购指南:区域服务、技术适配与行业趋势深度分析 - 优质品牌商家
  • 2026年北京公司注册代理机构综合能力分析:服务范围、团队经验与真实案例解读 - 优质品牌商家
  • 2026河北油管厂家排行揭秘,这样选才不踩坑
  • 六盘水余生黄金回收实测 2026卖金价格指南 - 余生黄金回收
  • Cadence Virtuoso IC 618版图新手避坑:从DRC/LVS报错到电源环(Guard Ring)的正确画法
  • 吐血整理!支付宝小程序从“搜不到”到“排第一”的秘诀
  • 世界从来不是单一逻辑的产物,而是“可推导的骨架”与“不可推导的血肉”共同编织的复合体。
  • IC697BEM731Z控制器模块
  • 告别卡顿!在Uni-app里用海康H5Player播放WS视频流,保姆级接入教程(含RenderJS避坑)
  • 女性生理期健康护理常识:科学认知与日常养护建议
  • STM32F103ZE精英板ADC多路电压采集工程(含双电机实时监测与LCD显示)
  • 2026年你必须知道的5种DeFi智能合约漏洞——从100个真实案例看资产安全
  • 终极指南:如何使用Waifu2x-Extension-GUI让模糊图片视频变高清
  • 5分钟快速搭建OBS局域网直播系统:obs-rtspserver完全指南
  • 寄快递哪个平台最便宜?2026全网寄件渠道省钱对比 - 快递物流资讯
  • 如何让微信网页版重新可用:wechat-need-web技术方案深度解析
  • WinForm下可交互SVG图形控件:支持标注定位、元素锁定与操作回退
  • 从Arduino到ESP32:手把手教你调试I2C通信,搞定‘地址无响应’和波形毛刺
  • 计算机毕业设计之基于Python的校园书院预约系统的设计与实现
  • 保姆级教程:用Python一键下载处理CTU-13僵尸网络检测数据集(附完整代码)
  • Linux iocost_model校准权重与线性回归参数