1

基于深度学习的蔬菜识别系统
模型mobilelnet
项目介绍:
软件:Pycharm+Anaconda
环境:python=3.9 opencv_python PyQt5
文件:
1.完整程序文件(.py等)
2.UI界面源文件、图标(.ui、.qrc、.py等)
功能: 系统实现了对于多种蔬菜的识别检测功能:包括通过选择图片进行实时识别;检测速度快、识别精度较高。
①选择图片识别蔬菜。

以下是基于 深度学习的蔬菜识别系统 的完整实现代码,使用 MobileNetV2 + PyTorch + PyQt5 构建,支持:
vegetable_recognition_system/ ├── UIProgram/ │ ├── MainProgram.py # 主界面 │ └── ui_mainwindow.py # UI 文件生成(由 .ui 转换) ├── models/ │ └── mobilenetv2.pth # 训练好的模型 ├── data/ │ ├── train/ # 训练数据集 │ └── test/ # 测试数据集 ├── utils/ │ ├── dataset.py # 数据加载 │ └── inference.py # 推理函数 ├── config.py # 参数配置 ├── requirements.txt # 依赖包 └── vegetable_info.json # 蔬菜知识库(名称+介绍) 123456789101112131415
conda create -n veg_recognition python=3.9 conda activate veg_recognition
bash
12 2. 安装依赖pip install torch torchvision opencv-python pyqt5 numpy pillow matplotlib
bash
1或使用 requirements.txt:
# requirements.txt torch==2.0.1 torchvision==0.15.2 opencv-python==4.8.0 pyqt5==5.15.9 numpy==1.24.3 pillow==9.5.0 matplotlib==3.6.3
txt
12345678pip install -r requirements.txt
bash
1
cucumber黄瓜
carrot胡萝卜
potato土豆
eggplant茄子
pumpkin南瓜
建议:从公开数据集(如 Kaggle)或自行采集图像,每类至少 100 张。
目录结构data/ ├── train/ │ ├── tomato/ │ ├── cucumber/ │ └── ... └── test/ ├── tomato/ ├── cucumber/ └── ... 123456789
# train.py import torch import torch.nn as nn import torch.optim as optim from torchvision import models, transforms from torch.utils.data import DataLoader from utils.dataset import VegetableDataset import os # 数据增强 transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.CenterCrop(224), transforms.RandomHorizontalFlip(), transforms.ColorJitter(brightness=0.2, contrast=0.2), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 加载数据 train_dataset = VegetableDataset(root_dir='data/train', transform=transform) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # 加载 MobileNetV2 model = models.mobilenet_v2(pretrained=True) num_classes = len(train_dataset.classes) model.classifier[1] = nn.Linear(model.classifier[1].in_features, num_classes) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) # 训练循环 for epoch in range(10): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() if batch_idx % 10 == 0: print(f'Epoch [{epoch+1}/10], Batch [{batch_idx}/{len(train_loader)}], Loss: {loss.item():.4f}') # 保存模型 torch.save(model.state_dict(), 'models/mobilenetv2.pth') print("✅ 模型已保存至 models/mobilenetv2.pth")
python
运行
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# utils/inference.py import torch import torchvision.transforms as transforms from PIL import Image import json class VegetableClassifier: def __init__(self, model_path='models/mobilenetv2.pth', class_names=None): self.model = models.mobilenet_v2(pretrained=False) num_classes = 6 self.model.classifier[1] = nn.Linear(self.model.classifier[1].in_features, num_classes) self.model.load_state_dict(torch.load(model_path)) self.model.eval() self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.model.to(self.device) self.transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) self.class_names = class_names or ['西红柿', '黄瓜', '胡萝卜', '土豆', '茄子', '南瓜'] def predict(self, image_path): img = Image.open(image_path).convert('RGB') input_tensor = self.transform(img).unsqueeze(0).to(self.device) with torch.no_grad(): output = self.model(input_tensor) _, predicted = torch.max(output, 1) confidence = torch.softmax(output, dim=1).max().item() return self.class_names[predicted.item()], confidence
python
运行
123456789101112131415161718192021222324252627282930313233{ "西红柿": "西红柿,又名番茄、洋柿子,古名六月柿、喜报三元。原产于秘鲁和墨西哥,最初称之为“狼桃”。果实营养丰富,具特殊风味。可以生食、煮食、加工制成番茄酱、汁或整果罐藏。西红柿是全世界栽培最为普遍的果菜之一。", "黄瓜": "黄瓜,一年生蔓生或攀援草本植物。茎细长,有棱,被刺毛。叶掌状,边缘有锯齿。花黄色,雌雄同株。果实为瓠果,长圆柱形,表面光滑,成熟时呈黄绿色或深绿色。", "胡萝卜": "胡萝卜,又称红萝卜,是一种根菜类蔬菜。其根部肥大,呈橙红色,富含β-胡萝卜素。原产地为阿富汗,现广泛种植于世界各地。常用于炒菜、炖汤或生吃。", "土豆": "土豆,又称马铃薯,是茄科植物的块茎。原产于南美洲安第斯山脉,现为全球重要的粮食作物之一。其块茎富含淀粉,可煮、蒸、炸、烤等多种方式食用。", "茄子": "茄子,又称矮瓜、落苏,是茄科植物的果实。果实呈椭圆形或长条形,紫色或白色,表面光滑。原产于印度,后传入中国。常用于炒、炖、烧等烹饪方式。", "南瓜": "南瓜,又称倭瓜、金瓜,是葫芦科植物的果实。果实大而扁圆,外皮橙黄色,肉质柔软,富含β-胡萝卜素。原产于美洲,现广泛种植于世界各地。可煮、蒸、烤、做汤等。" }
json
12345678# MainProgram.py import sys import os import json from PyQt5.QtWidgets import ( QApplication, QMainWindow, QLabel, QPushButton, QVBoxLayout, QWidget, QHBoxLayout, QFileDialog, QTextEdit, QGroupBox, QComboBox, QSpinBox ) from PyQt5.QtGui import QPixmap, QImage from PyQt5.QtCore import Qt from utils.inference import VegetableClassifier import threading class VegetableRecognitionSystem(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("基于深度学习的蔬菜识别系统") self.setGeometry(100, 100, 1200, 800) self.classifier = VegetableClassifier() self.info_json = json.load(open('vegetable_info.json', 'r')) self.init_ui() def init_ui(self): # 左侧:操作区 left_layout = QVBoxLayout() # 单张检测 single_group = QGroupBox("单张检测") self.single_label = QLabel("请选择图片文件") self.single_btn = QPushButton("") self.single_btn.clicked.connect(self.browse_single) self.single_path = QLabel("未选择文件") single_layout = QHBoxLayout() single_layout.addWidget(self.single_label) single_layout.addWidget(self.single_btn) single_layout.addWidget(self.single_path) single_group.setLayout(single_layout) # 批量检测 batch_group = QGroupBox("批量检测") self.batch_label = QLabel("点击选择文件夹") self.batch_btn = QPushButton("") self.batch_btn.clicked.connect(self.browse_batch) self.batch_path = QLabel("未选择文件夹") batch_layout = QHBoxLayout() batch_layout.addWidget(self.batch_label) batch_layout.addWidget(self.batch_btn) batch_layout.addWidget(self.batch_path) batch_group.setLayout(batch_layout) # 按钮 self.start_btn = QPushButton("开始检测") self.start_btn.clicked.connect(self.detect_single) self.batch_start_btn = QPushButton("批量检测") self.batch_start_btn.clicked.connect(self.detect_batch) self.export_btn = QPushButton("结果导出") self.export_btn.clicked.connect(self.export_results) left_layout.addWidget(single_group) left_layout.addWidget(batch_group) left_layout.addWidget(self.start_btn) left_layout.addWidget(self.batch_start_btn) left_layout.addWidget(self.export_btn) # 中间:图片显示区 self.image_label = QLabel("图片显示区域") self.image_label.setAlignment(Qt.AlignCenter) self.image_label.setStyleSheet("border: 1px solid black;") # 右侧:结果显示区 right_layout = QVBoxLayout() # 识别结果 result_group = QGroupBox("识别结果") self.class_label = QLabel("类别: ") self.conf_label = QLabel("置信度: ") result_layout = QVBoxLayout() result_layout.addWidget(self.class_label) result_layout.addWidget(self.conf_label) result_group.setLayout(result_layout) # 相关介绍 intro_group = QGroupBox("相关介绍") self.intro_text = QTextEdit() self.intro_text.setReadOnly(True) intro_group.setLayout(QVBoxLayout()) intro_group.layout().addWidget(self.intro_text) # 识别结果信息 info_group = QGroupBox("识别结果信息") self.table_widget = QTextEdit() self.table_widget.setReadOnly(True) info_group.setLayout(QVBoxLayout()) info_group.layout().addWidget(self.table_widget) right_layout.addWidget(result_group) right_layout.addWidget(intro_group) right_layout.addWidget(info_group) # 主布局 main_layout = QHBoxLayout() main_layout.addLayout(left_layout) main_layout.addWidget(self.image_label) main_layout.addLayout(right_layout) container = QWidget() container.setLayout(main_layout) self.setCentralWidget(container) def browse_single(self): file_name, _ = QFileDialog.getOpenFileName(self, "选择图片", "", "Images (*.jpg *.png)") if file_name: self.single_path.setText(file_name) self.display_image(file_name) def browse_batch(self): folder = QFileDialog.getExistingDirectory(self, "选择文件夹") if folder: self.batch_path.setText(folder) def detect_single(self): path = self.single_path.text() if not path: return class_name, conf = self.classifier.predict(path) self.class_label.setText(f"类别: <font color='red'>{class_name}</font>") self.conf_label.setText(f"置信度: <font color='red'>{conf:.2%}</font>") self.intro_text.setText(self.info_json[class_name]) self.table_widget.setText(f"序号t图像路径t识别类型t置信度n1t{path}t{class_name}t{conf:.2%}") def detect_batch(self): folder = self.batch_path.text() if not folder: return results = [] for file in os.listdir(folder): if file.lower().endswith(('.jpg', '.png')): path = os.path.join(folder, file) class_name, conf = self.classifier.predict(path) results.append({ 'file': path, 'class': class_name, 'conf': conf }) self.table_widget.setText("n".join([f"{i+1}t{r['file']}t{r['class']}t{r['conf']:.2%}" for i, r in enumerate(results)])) def display_image(self, path): img = cv2.imread(path) h, w = img.shape[:2] qimg = QImage(img.data, w, h, w * 3, QImage.Format_BGR888) self.image_label.setPixmap(QPixmap.fromImage(qimg).scaled(600, 400)) def export_results(self): with open('results.csv', 'w') as f: f.write("序号,图像路径,识别类型,置信度n") lines = self.table_widget.toPlainText().split('n') for line in lines: if line.strip(): parts = line.split('t') f.write(f"{parts[0]},{parts[1]},{parts[2]},{parts[3]}n") print("✅ 结果已导出为 results.csv")
python
运行
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161该系统实现了:
✔️ 使用 MobileNetV2 实现高精度蔬菜识别✔️ 支持单张/批量检测✔️ 图形化界面展示结果与知识介绍✔️ 可扩展为智能农业、超市商品识别系统相关知识
基于深度学习的蔬菜识别系统 采用模型mobilelnet 对于多种蔬菜的识别检测功能 智能农业、超市商品识别系统
探索花卉世界的智能助手:基于YOLOv5的花卉检测与识别系统
基于深度学习的病虫害智能化识别系统
基于深度学习的花识别检测方法研究.pptx
农业病虫害智能识别系统.docx
深度学习基于python+TensorFlow+Django的花朵识别系统
基于YOLOv8深度学习的智能小麦害虫检测识别系统【python源码+Pyqt5界面+数据集+训练代码】目标检测、深度学习实战
基于YOLOv8深度学习的200种鸟类智能检测与识别系统【python源码+Pyqt5界面+数据集+训练代码】目标检测、深度学习实战
基于YOLOv8深度学习的102种花卉智能识别系统【python源码+Pyqt5界面+数据集+训练代码】目标识别、深度学习实战
农作物病虫害检测识别系统
网址: 基于深度学习的蔬菜识别系统 采用模型mobilelnet 对于多种蔬菜的识别检测功能 智能农业、超市商品识别系统 https://m.huajiangbk.com/newsview2569494.html
| 上一篇: 1.1蔬菜的分类与识别 课件(共 |
下一篇: 用Pytorch实现水果分类,训 |