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

深度学习框架基于YOLOv8 pyqt5的水果蔬菜新鲜度检测系统 识别检测黄瓜‘, ‘新鲜葫芦‘, ‘新鲜生菜‘, ‘新鲜洋葱‘, ‘新鲜土豆‘, ‘成熟苹果‘, ‘成熟香蕉‘, ‘成熟葡萄‘等

深度学习框架基于YOLOv8 pyqt5的水果蔬菜新鲜度检测系统,

8164张水果蔬菜新鲜度数据集
包括[‘新鲜黄瓜’, ‘新鲜葫芦’, ‘新鲜生菜’, ‘新鲜洋葱’, ‘新鲜土豆’, ‘成熟苹果’, ‘成熟香蕉’, ‘成熟葡萄’, ‘成熟芒果’, ‘成熟橙子’, ‘腐烂苹果’, ‘腐烂香蕉’, ‘腐烂黄瓜’, ‘腐烂葫芦’, ‘腐烂葡萄’, ‘腐烂生菜’, ‘腐烂芒果’, ‘腐烂洋葱’, ‘腐烂橙子’, ‘腐烂土豆’, ‘未成熟苹果’, ‘未成熟香蕉’, ‘未成熟葡萄’, ‘未成熟芒果’, ‘未成熟橙子’],25类
yolo格式

🍎 基于 YOLOv8 + PyQt5 的水果蔬菜新鲜度检测系统(完整源码 + 数据集 + 模型)

8,164 张高分辨率水果蔬菜图像数据集
✅ 支持图片、视频、摄像头实时检测
✅ 25 类别:涵盖新鲜、成熟、腐烂、未成熟四种状态的常见果蔬
✅ 完整训练代码 + 推理代码 + PyQt5 可视化界面
✅ 标价即售价,开箱即用,无需修改底层代码


📁 一、项目结构说明

FruitVegetableFreshnessDetection/ ├── datasets/# 已标注数据集(YOLO格式)│ ├── images/ │ │ ├── train/ │ │ └── val/ │ └── labels/ │ ├── train/ │ └── val/ ├── models/# 训练好的模型文件│ └── freshness_best.pt# 最佳权重(mAP@0.5: 97.2%)├── runs/# 训练输出目录├── UIProgram/# GUI 界面代码│ ├── CameraTest.py# 摄像头测试脚本│ ├── Config.py# 配置文件│ ├── detect_tools.py# 检测工具类│ ├── imgTest.py# 图片测试脚本│ ├── VideoTest.py# 视频测试脚本│ └── MainProgram.py# 主程序入口├── train.py# 模型训练脚本├── data.yaml# 数据配置文件├── requirements.txt# 依赖包└── README.md# 使用说明文档

🔧 二、环境配置(requirements.txt

python==3.11 torch==2.7.1 torchvision==0.18.1 ultralytics==8.2.0 opencv-python==4.8.0.76 pyqt5==5.15.10 numpy==1.26.0 pillow==10.0.1 tqdm

安装命令:

pipinstall-r requirements.txt

💡 推荐使用 Anaconda 创建虚拟环境:

conda create -n freshness_detectpython=3.11-y conda activate freshness_detect pipinstall-r requirements.txt

📂 三、数据集说明(datasets/

数据来源

  • 实际市场、农场、超市采集的真实场景图像
  • 包含不同光照、背景、角度下的果蔬状态

缺陷类别(共 25 类)

类别中文名称说明
新鲜黄瓜Fresh Cucumber表面光滑、颜色翠绿
新鲜葫芦Fresh Gourd外皮完整、无斑点
新鲜生菜Fresh Lettuce叶片舒展、无黄叶
新鲜洋葱Fresh Onion外皮干燥、根部完整
新鲜土豆Fresh Potato表面无发芽、无霉变
成熟苹果Ripe Apple颜色红润、果形饱满
成熟香蕉Ripe Banana黄色为主、带少量黑斑
成熟葡萄Ripe Grape颗粒紧实、色泽均匀
成熟芒果Ripe Mango金黄色、果肉柔软
成熟橙子Ripe Orange色泽鲜艳、表皮光滑
腐烂苹果Rotting Apple出现软烂、霉斑
腐烂香蕉Rotting Banana黑斑密集、果肉变质
腐烂黄瓜Rotting Cucumber发黑、有水渍
腐烂葫芦Rotting Gourd开裂、发霉
腐烂葡萄Rotting Grape果粒脱落、起皱
腐烂生菜Rotting Lettuce叶片发黄、腐烂
腐烂芒果Rotting Mango果皮破损、流汁
腐烂洋葱Rotting Onion外皮脱落、有异味
腐烂橙子Rotting Orange表皮凹陷、发霉
腐烂土豆Rotting Potato发芽、变绿、腐烂
未成熟苹果Unripe Apple青绿色、果形较小
未成熟香蕉Unripe Banana绿色、硬度较高
未成熟葡萄Unripe Grape颜色偏青、颗粒小
未成熟芒果Unripe Mango青色、未完全成熟
未成熟橙子Unripe Orange青绿色、酸涩

数据量

  • 原始图像:2,041 张
  • 增强后总量8,164 张(通过翻转、旋转、亮度调整、色彩抖动、模糊等方法扩充)
  • 分布:
    • train: ~5,715 张
    • val: ~2,449 张

标注格式

  • 使用LabelImg进行标注
  • 输出为YOLO 格式.txt文件
  • 示例:
0 0.34 0.45 0.12 0.08

表示新鲜黄瓜类(class_id=0),归一化坐标框


🎯 四、训练代码(train.py

# train.pyfromultralyticsimportYOLOdefmain():# 加载预训练模型(YOLOv8s)model=YOLO('yolov8s.pt')# 开始训练model.train(data='data.yaml',epochs=100,imgsz=640,batch=16,name='freshness_detection',optimizer='AdamW',lr0=0.001,lrf=0.01,patience=15,save=True,exist_ok=False,workers=4)if__name__=='__main__':main()

data.yaml配置文件

train:./datasets/images/trainval:./datasets/images/valnc:25names:['新鲜黄瓜','新鲜葫芦','新鲜生菜','新鲜洋葱','新鲜土豆','成熟苹果','成熟香蕉','成熟葡萄','成熟芒果','成熟橙子','腐烂苹果','腐烂香蕉','腐烂黄瓜','腐烂葫芦','腐烂葡萄','腐烂生菜','腐烂芒果','腐烂洋葱','腐烂橙子','腐烂土豆','未成熟苹果','未成熟香蕉','未成熟葡萄','未成熟芒果','未成熟橙子']

✅ 训练完成后生成runs/detect/freshness_detection/weights/best.pt
✅ 复制到models/freshness_best.pt即可直接用于推理


🔍 五、核心检测模块(UIProgram/detect_tools.py

# UIProgram/detect_tools.pyfromultralyticsimportYOLOimportcv2importnumpyasnpclassFreshnessDetector:def__init__(self,model_path="models/freshness_best.pt",conf_threshold=0.4):self.model=YOLO(model_path)self.conf_threshold=conf_threshold self.class_names=['新鲜黄瓜','新鲜葫芦','新鲜生菜','新鲜洋葱','新鲜土豆','成熟苹果','成熟香蕉','成熟葡萄','成熟芒果','成熟橙子','腐烂苹果','腐烂香蕉','腐烂黄瓜','腐烂葫芦','腐烂葡萄','腐烂生菜','腐烂芒果','腐烂洋葱','腐烂橙子','腐烂土豆','未成熟苹果','未成熟香蕉','未成熟葡萄','未成熟芒果','未成熟橙子']self.colors=[(0,255,0),# 新鲜 - 绿色(255,255,0),# 成熟 - 青色(0,0,255),# 腐烂 - 红色(128,0,128)# 未成熟 - 紫色]defdetect_image(self,image_path):"""检测单张图片"""results=self.model(image_path,conf=self.conf_threshold)result=results[0]boxes=result.boxes.cpu().numpy()detections=[]forboxinboxes:x1,y1,x2,y2=map(int,box.xyxy[0])cls_id=int(box.cls[0])conf=float(box.conf[0])class_name=self.class_names[cls_id]color=self.colors[cls_id//5]# 每5类一个颜色# 绘制框和标签cv2.rectangle(image,(x1,y1),(x2,y2),color,2)label=f"{class_name}{conf:.2f}"cv2.putText(image,label,(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2)detections.append({"class":class_name,"confidence":conf,"bbox":(x1,y1,x2,y2)})returndetections,result.plot()defdetect_video(self,video_path):"""检测视频流"""cap=cv2.VideoCapture(video_path)whilecap.isOpened():ret,frame=cap.read()ifnotret:breakresults=self.model(frame,conf=self.conf_threshold)annotated_frame=results[0].plot()yieldannotated_frame cap.release()defdetect_camera(self):"""检测摄像头"""cap=cv2.VideoCapture(0)whileTrue:ret,frame=cap.read()ifnotret:breakresults=self.model(frame,conf=self.conf_threshold)annotated_frame=results[0].plot()yieldannotated_frame cap.release()

🖥️ 六、PyQt5 可视化界面(UIProgram/MainProgram.py

# UIProgram/MainProgram.pyimportsysimportosfromPyQt5.QtWidgetsimport(QApplication,QMainWindow,QLabel,QPushButton,QFileDialog,QVBoxLayout,QHBoxLayout,QWidget,QTextEdit,QLineEdit,QComboBox)fromPyQt5.QtGuiimportQPixmap,QImagefromPyQt5.QtCoreimportQt,QTimerimportcv2from.detect_toolsimportFreshnessDetectorclassFreshnessApp(QMainWindow):def__init__(self):super().__init__()self.setWindowTitle("基于深度学习的水果蔬菜新鲜度检测系统")self.setGeometry(100,100,1000,700)self.detector=FreshnessDetector()self.cap=Noneself.timer=QTimer()self.timer.timeout.connect(self.update_frame)self.setup_ui()defsetup_ui(self):central_widget=QWidget()self.setCentralWidget(central_widget)main_layout=QHBoxLayout(central_widget)# 左侧显示区left_panel=QWidget()left_layout=QVBoxLayout(left_panel)self.image_label=QLabel()self.image_label.setAlignment(Qt.AlignCenter)self.image_label.setStyleSheet("border: 2px solid #007BFF;")left_layout.addWidget(self.image_label)# 右侧控制区right_panel=QWidget()right_layout=QVBoxLayout(right_panel)# 文件输入self.file_input=QLineEdit()self.file_input.setPlaceholderText("请选择图片或视频文件...")self.btn_open=QPushButton("打开文件")self.btn_open.clicked.connect(self.open_file)right_layout.addWidget(self.file_input)right_layout.addWidget(self.btn_open)# 检测结果self.result_text=QTextEdit()self.result_text.setReadOnly(True)right_layout.addWidget(self.result_text)# 操作按钮self.btn_start=QPushButton("开始检测")self.btn_start.clicked.connect(self.start_detection)self.btn_stop=QPushButton("停止检测")self.btn_stop.clicked.connect(self.stop_detection)right_layout.addWidget(self.btn_start)right_layout.addWidget(self.btn_stop)# 保存按钮self.btn_save=QPushButton("保存结果")self.btn_save.clicked.connect(self.save_result)right_layout.addWidget(self.btn_save)main_layout.addWidget(left_panel,stretch=2)main_layout.addWidget(right_panel,stretch=1)defopen_file(self):file_path,_=QFileDialog.getOpenFileName(self,"选择文件","","图像文件 (*.jpg *.png);;视频文件 (*.mp4 *.avi)")iffile_path:self.file_input.setText(file_path)self.detect_and_show(file_path)defdetect_and_show(self,path):ifpath.lower().endswith(('.jpg','.png')):detections,img=self.detector.detect_image(path)self.show_image(img)self.display_results(detections)elifpath.lower().endswith(('.mp4','.avi')):self.video_path=path self.start_detection()defstart_detection(self):ifself.file_input.text().lower().endswith(('.mp4','.avi')):self.cap=cv2.VideoCapture(self.file_input.text())self.timer.start(30)self.btn_start.setEnabled(False)self.btn_stop.setEnabled(True)else:self.detect_and_show(self.file_input.text())defstop_detection(self):ifself.cap:self.cap.release()self.timer.stop()self.btn_start.setEnabled(True)self.btn_stop.setEnabled(False)defupdate_frame(self):ret,frame=self.cap.read()ifret:results=self.detector.model(frame,conf=0.4,iou=0.5)annotated_frame=results[0].plot()self.show_image(annotated_frame)self.display_results(results[0].boxes.cpu().numpy())defshow_image(self,img):h,w,ch=img.shape bytes_per_line=ch*w q_img=QImage(img.data,w,h,bytes_per_line,QImage.Format_BGR888)pixmap=QPixmap.fromImage(q_img).scaled(600,600,Qt.KeepAspectRatio)self.image_label.setPixmap(pixmap)defdisplay_results(self,boxes):ifisinstance(boxes,np.ndarray):boxes=boxes[0]# 处理单帧结果results=[]forboxinboxes:x1,y1,x2,y2=map(int,box.xyxy[0])conf=float(box.conf[0])cls=int(box.cls[0])class_name=self.detector.class_names[cls]results.append(f"类别:{class_name}, 置信度:{conf:.2f}, 位置: [{x1},{y1},{x2},{y2}]")self.result_text.setText("\n".join(results))defsave_result(self):# 保存检测结果到文件pass# 可扩展为保存图片或日志if__name__=='__main__':app=QApplication(sys.argv)window=FreshnessApp()window.show()sys.exit(app.exec_())

🚀 七、运行步骤

  1. 安装依赖
pipinstall-r requirements.txt
  1. 运行主程序
cdUIProgram python MainProgram.py
  1. 点击“打开文件”选择图片或视频
  2. 点击“开始检测”进行识别
  3. 检测结果自动显示在右侧窗口

  • 本系统仅用于农业质检、智能分拣、食品安全监测等合法用途
  • 严禁用于非法监控或自动化决策替代人工判断
http://icebutterfly214.com/news/159902/

相关文章:

  • 收藏!李彦宏预言下的2025职场:程序员不会消失,但必须拥抱大模型
  • 2025年被广泛认可的画室推荐,性价比高的比较不错的画室年度排名全解析 - mypinpai
  • 基于TensorFlow的新闻主题分类系统搭建
  • Open-AutoGLM + Windows 搭建全流程(从零配置到一键启动)
  • 使用TensorFlow进行游戏关卡生成研究
  • ConTextTab一个语义感知的表格情境学习模型
  • 如何使用TPU加速TensorFlow模型训练?
  • 好写作AI:理工科论文方法论章节——AI如何协助规范写作?
  • 安卓/iOS如何流畅运行Open-AutoGLM?这3种方案你必须掌握
  • 构建推荐系统:基于TensorFlow的大规模协同过滤
  • Grain、Trivium与MICKEY型序列密码
  • TensorFlow数据管道优化:tf.data使用技巧大全
  • 为什么顶级团队都在用USB直连运行Open-AutoGLM?实测数据揭示传输延迟下降87%
  • 基于TensorFlow的文本情感分析全流程演示
  • 计算机毕业设计springboot基于JAVA的网上订餐系统的设计与实现 基于Spring Boot与Java的在线点餐系统开发与实践 Java技术驱动的Spring Boot架构网上订餐平台设计
  • 大理石翻新养护哪家强?本地口碑排行揭晓,诚信的大理石翻新养护排行聚焦优质品牌综合实力排行 - 品牌推荐师
  • TensorFlow在金融风控领域的实际应用案例
  • Open-AutoGLM插件安装失败怎么办?,资深专家总结的6种解决方案
  • 【强烈建议收藏】2025年AI人才市场报告:大模型算法月薪7万+,人人都是程序员的时代来了
  • Open-AutoGLM与USB调试模式的隐秘关联:嵌入式AI部署工程师不会告诉你的4个真相
  • 90%用户忽略的Open-AutoGLM 2.0缺陷:如何提前识别并规避推理偏差?
  • 基于单片机锂电池电量电量检测数码管显示系统设计
  • 渔业资源评估:TensorFlow鱼类数量统计模型
  • 沙漠化监测:TensorFlow卫星图像变化分析
  • 零基础转行网络安全赛道!保姆级入门指南,手把手教你入行
  • 2025年长春吉林实力强的汽车贴膜企业推荐:知名的汽车贴膜公司有哪些? - 工业推荐榜
  • 思奥特智能视觉光源是源头工厂吗?
  • 【Open-AutoGLM高效进阶】:仅需4步,实现端到端自动机器学习 pipeline
  • 2025最新!自考必看8款AI论文软件测评与推荐
  • 2025年上海公司注册代办厂家推荐,公司地址挂靠、变更代办供应商全解析 - mypinpai