引言

水果新鲜程度直接影响其口感和营养价值。为了提高水果品质管理的效率和准确性,本文介绍了一种基于深度学习的水果新鲜程度检测系统。该系统包括用户界面,利用YOLO(You Only Look Once)v8/v7/v6/v5模型进行水果新鲜程度检测,并提供了完整的实现步骤和详细代码。

系统架构
  1. 环境搭建
  2. 数据收集和预处理
  3. 模型训练
  4. 系统实现
  5. 用户界面设计
环境搭建

在开始实现水果新鲜程度检测系统之前,我们需要搭建一个合适的开发环境。本文假设使用Python 3.8或以上版本。

安装基础依赖

首先,安装基础的Python依赖包:

pip install numpy pandas matplotlib opencv-python
  • 1.
安装深度学习框架

我们使用YOLO模型进行水果新鲜程度检测,因此需要安装相关的深度学习框架,如PyTorch或TensorFlow。本文使用PyTorch和Ultralytics的YOLO库。

pip install torch torchvision torchaudio
pip install ultralytics
  • 1.
  • 2.
安装用户界面库

为了实现用户界面,本文使用PyQt5。

pip install PyQt5
  • 1.
验证安装

确保所有包都安装成功,可以通过以下命令验证:

import torch
import cv2
import PyQt5
import ultralytics

print("All packages installed successfully.")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
数据收集和预处理
数据集

为了训练一个高精度的水果新鲜程度检测模型,我们需要一个包含各种水果及其不同新鲜程度图片的数据集。可以使用以下途径收集数据:

  • 公开数据集:如Kaggle上的相关数据集。
  • 自定义数据集:通过互联网、市场、农场等途径收集图片。
数据标注

使用工具如LabelImg对数据进行标注。标注内容包括水果的位置(bounding box)和标签(新鲜/不新鲜)。

# 训练数据集文件结构示例
dataset/
  ├── images/
  │   ├── train/
  │   └── val/
  └── labels/
      ├── train/
      └── val/
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
模型训练

YOLO模型有多个版本,本文选取YOLOv8作为示范,其他版本可以通过相似方法实现。

配置YOLO数据集

首先,创建一个YAML文件来配置数据集信息:

# dataset.yaml
train: path/to/train/images
val: path/to/val/images

nc: 2
names: ['Fresh', 'Not_Fresh']
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
模型训练代码

使用YOLOv8进行模型训练,假设数据已经按照YOLO的格式进行预处理和标注。

from ultralytics import YOLO

# 加载预训练的YOLOv8模型
model = YOLO('yolov8.yaml')

# 配置训练参数
model.train(data='path/to/dataset.yaml', epochs=50, imgsz=640, batch=16)

# 保存训练后的模型
model.save('best.pt')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
系统实现
水果新鲜程度检测

利用训练好的模型进行水果新鲜程度检测,并实现视频流的实时检测。

import cv2
from ultralytics import YOLO

# 加载训练好的模型
model = YOLO('best.pt')

# 打开视频流
cap = cv2.VideoCapture('path/to/video.mp4')

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

    # 检测水果新鲜程度
    results = model(frame)
    for result in results:
        bbox = result['bbox']
        label = result['label']
        confidence = result['confidence']
        
        # 画框和标签
        cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
        cv2.putText(frame, f'{label} {confidence:.2f}', (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    
    # 显示视频
    cv2.imshow('Fruit Freshness Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
用户界面设计

用户界面采用PyQt5实现,提供视频播放和水果新鲜程度检测结果显示。

安装PyQt5
pip install PyQt5
  • 1.
界面代码



import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QFileDialog
from PyQt5.QtGui import QPixmap, QImage
import cv2
from ultralytics import YOLO

class FruitFreshnessUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
        
        self.model = YOLO('best.pt')
        
    def initUI(self):
        self.setWindowTitle('Fruit Freshness Detection System')
        
        self.layout = QVBoxLayout()
        
        self.label = QLabel(self)
        self.layout.addWidget(self.label)
        
        self.button = QPushButton('Open Video', self)
        self.button.clicked.connect(self.open_video)
        self.layout.addWidget(self.button)
        
        self.setLayout(self.layout)
    
    def open_video(self):
        options = QFileDialog.Options()
        video_path, _ = QFileDialog.getOpenFileName(self, "Open Video", "", "All Files (*);;MP4 Files (*.mp4)", options=options)
        
        if video_path:
            self.detect_freshness(video_path)
    
    def detect_freshness(self, video_path):
        cap = cv2.VideoCapture(video_path)
        
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            
            results = self.model(frame)
            for result in results:
                bbox = result['bbox']
                label = result['label']
                confidence = result['confidence']
                
                cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
                cv2.putText(frame, f'{label} {confidence:.2f}', (bbox[0], bbox[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
            
            # 将frame转换为QImage
            height, width, channel = frame.shape
            bytesPerLine = 3 * width
            qImg = QImage(frame.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
            
            self.label.setPixmap(QPixmap.fromImage(qImg))
            cv2.waitKey(1)
        
        cap.release()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = FruitFreshnessUI()
    ex.show()
    sys.exit(app.exec_())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
结论与声明

本文介绍了一个基于深度学习的水果新鲜程度检测系统,详细描述了从环境搭建、数据收集和标注、模型训练、系统实现到用户界面设计的全过程。通过结合YOLO模型和PyQt5,我们可以实现一个实时、精确的水果新鲜程度检测系统,为水果品质管理提供有力支持。