1. 引言
1.1 研究背景与意义
农作物虫害是制约农业产量与质量的重要因素。据FAO报告,全球每年因病虫害造成的粮食损失高达 20%–40%。传统人工巡查与经验诊断具有时效性差、成本高与专业人才不足等缺陷。近年来,计算机视觉特别是目标检测技术在农业检测领域展现出高效性与部署可能性;与此同时,大语言模型在知识检索与文本生成方面的能力,为“检测→诊断→决策”闭环提供了可行路径。
1.2 研究现状与挑战
现有研究多集中于图像分类或单一检测模型改进,且在小目标、多尺度目标与复杂背景下仍存在识别瓶颈;此外,如何将视觉检测结果与农业防治知识(包含化学防治、生物防治、农艺管理等)有效对接并生成可操作的结构化建议,仍是亟待解决的问题。为此,本文提出将注意力机制嵌入 YOLOv8
架构以提升检测性能,并设计统一的 LLM
接入与提示词体系以输出专业化防治建议。
2. 系统总体设计
2.1 项目结构与核心模块
Pest-detection/
├── main.py # 主程序入口与GUI逻辑
├── UI.py # PyQt5界面定义文件
├── train.py # 模型训练脚本
├── val.py # 模型验证脚本
├── config/ # 配置管理
│ ├── configs.yaml # 系统主配置文件
│
├── tool/ # 工具模块
│ ├── parser.py # 配置解析器(EasyDict)
│ └── tools.py # 图像处理与结果格式化工具
├── prompts/ # 提示词管理系统
│ ├── core/
│ │ └── prompt_manager.py # 提示词管理器
│ └── templates/ # 各厂商LLM提示词模板
│ ├── default_prompt.txt # 默认提示词
│ ├── zhipu_prompt.txt # 智谱AI提示词
│ ├── qwen_prompt.txt # 阿里千问提示词
│ ├── qianfan_prompt.txt # 百度千帆提示词
│ ├── deepseek_prompt.txt # DeepSeek提示词
│ ├── doubao_prompt.txt # 豆包提示词
│ └── openai_prompt.txt # OpenAI提示词
├── ultralytics/ # 改进的YOLO框架
│ ├── cfg/models/v8/
│ │ ├── yolov8s.yaml # 标准YOLOv8s配置
│ │ └── det_self/
│ │ └── yolov8-attention-SE.yaml # SEAttention增强版
│ └── nn/modules_self/
│ └── attention/
│ └── SE.py # SEAttention模块实现
├── weights/ # 训练权重存储
│ ├── yolov8s/ # 标准模型权重与训练记录
│ └── yolov8-attention-SE/ # SEAttention模型权重与记录
├── dataset/ # 数据集(YOLO格式)
│ ├── train/
│ ├── val/
│ ├── test/
│ └── data.yaml # 数据集元信息
├── docs/ # 部署文档与配置
│ └── docker/
│ ├── Dockerfile # CPU版本容器构建
│ ├── Dockerfile.gpu # GPU版本容器构建
│ └── docker-compose.yml # 容器编排配置
├── output/ # 检测结果归档目录
├── logs/ # 系统运行日志
└── requirements.txt # Python依赖清单
系统采用模块化设计,主要包括:数据管理与标注模块、视觉检测模块(YOLOv8-SEAttention)
、LLM
决策模块(AIClient + PromptManager)
、用户交互与部署模块(桌面 GUI
、容器化/云端部署)。
- 检测→诊断→决策闭环:检测模块提供边界框与类别置信度,决策模块结合作物类型、病发部位、生态条件等上下文信息生成分级防治建议。
- 统一 LLM 抽象层:通过
AIClient
抽象不同的API
,便于按需切换或并行调用多家模型并做结果融合。 - 提示词工程:为保证建议的专业性与可操作性,构建面向农业防治的提示词模板库,可按模型特性定制
2.2 SENet网络结构
SE
块是一种创新性架构单元,它通过动态调整通道特征来增强网络的表征能力。实验证明,SENet
在多个数据集和任务上都取得了领先的性能表现。该设计还揭示了传统架构在建模通道特征依赖关系方面的局限性。SE
块的这一特性有望拓展到其他需要高区分度特征的任务中。此外,SE
块生成的特征重要性指标还可应用于模型压缩等场景,如网络剪枝。
论文地址
:https://arxiv.org/pdf/1709.01507.pdf
代码地址
:https://github.com/hujie-frank/SENet
2.3 YOLOV8中集成SEAttention
-
在
ultralytics/nn
目录下,新建SEAttention.py
文件,内容如下:
import numpy as np import torch from torch import nn from torch.nn import initclass SEAttention(nn.Module):def __init__(self, channel=512, reduction=16):super().__init__()self.avg_pool = nn.AdaptiveAvgPool2d(1)self.fc = nn.Sequential(nn.Linear(channel, channel // reduction, bias=False),nn.ReLU(inplace=True),nn.Linear(channel // reduction, channel, bias=False),nn.Sigmoid())def init_weights(self):for m in self.modules():if isinstance(m, nn.Conv2d):init.kaiming_normal_(m.weight, mode='fan_out')if m.bias is not None:init.constant_(m.bias, 0)elif isinstance(m, nn.BatchNorm2d):init.constant_(m.weight, 1)init.constant_(m.bias, 0)elif isinstance(m, nn.Linear):init.normal_(m.weight, std=0.001)if m.bias is not None:init.constant_(m.bias, 0)def forward(self, x):b, c, _, _ = x.size()y = self.avg_pool(x).view(b, c)y = self.fc(y).view(b, c, 1, 1)return x * y.expand_as(x)
-
在
ultralytics/nn/tasks.py
中,导入SEAttention
模块
-
在
ultralytics/nn/task.py
中的parse_model
函数添加如下代码,作用是解析模型结构
elif m in {SEAttention}:args = [ch[f], *args]
-
yolov8-attention-SE.yaml
# Ultralytics YOLO 🚀, AGPL-3.0 license # YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect# Parameters nc: 80 # number of classes scales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'# [depth, width, max_channels]n: [0.33, 0.25, 1024] # YOLOv8n summary: 225 layers, 3157200 parameters, 3157184 gradients, 8.9 GFLOPss: [0.33, 0.50, 1024] # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients, 28.8 GFLOPsm: [0.67, 0.75, 768] # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients, 79.3 GFLOPsl: [1.00, 1.00, 512] # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPsx: [1.00, 1.25, 512] # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs# YOLOv8.0n backbone backbone:# [from, repeats, module, args]- [-1, 1, Conv, [64, 3, 2]] # 0-P1/2- [-1, 1, Conv, [128, 3, 2]] # 1-P2/4- [-1, 3, C2f, [128, True]]- [-1, 1, Conv, [256, 3, 2]] # 3-P3/8- [-1, 6, C2f, [256, True]]- [-1, 1, Conv, [512, 3, 2]] # 5-P4/16- [-1, 6, C2f, [512, True]]- [-1, 1, Conv, [1024, 3, 2]] # 7-P5/32- [-1, 3, C2f, [1024, True]]- [-1, 1, SPPF, [1024, 5]] # 9- [-1, 1, SEAttention, [16]]# YOLOv8.0n head head:- [-1, 1, nn.Upsample, [None, 2, 'nearest']]- [[-1, 6], 1, Concat, [1]] # cat backbone P4- [-1, 3, C2f, [512]] # 12- [-1, 1, nn.Upsample, [None, 2, 'nearest']]- [[-1, 4], 1, Concat, [1]] # cat backbone P3- [-1, 3, C2f, [256]] # 15 (P3/8-small)- [-1, 1, Conv, [256, 3, 2]]- [[-1, 13], 1, Concat, [1]] # cat head P4- [-1, 3, C2f, [512]] # 18 (P4/16-medium)- [-1, 1, Conv, [512, 3, 2]]- [[-1, 10], 1, Concat, [1]] # cat head P5- [-1, 3, C2f, [1024]] # 21 (P5/32-large)- [[16, 19, 22], 1, Detect, [nc]] # Detect(P3, P4, P5)
此处注意修改层数的变化,层数是从0开始数的,由于此处是添加到了第10层,因此后面层数都发生了变化。10层以后的相关层数都需要加1。具体修改内容如下:
-
数据集
本数据集共包含 18976 张图像,涵盖了 102 类常见农作物害虫种类,覆盖水稻、小麦、玉米、棉花、果树及其他经济作物中高发的害虫类别。每一类图片均标注了对应虫害名称,适用于图像分类、目标检测及深度学习任务。
数据集涵盖的虫害包括但不限于:
- 水稻类害虫:稻纵卷叶螟、稻螟蛉、稻飞虱、稻蓟马、稻瘿蚊、稻水象甲等;
- 小麦类害虫:麦蜘蛛、麦蚜、麦叶甲、小麦吸浆虫等;
- 玉米类害虫:玉米螟、粘虫、蚜虫等;
- 棉花、豆类及果树类害虫:红蜘蛛、盲蝽象、蓟马、介壳虫、实蝇、木蠹蛾、潜叶蛾等;
- 广义农业害虫:斑潜蝇、跳甲、象鼻虫、绿盲蝽、地老虎、灰象甲等;
- 外来入侵害虫与区域性高发种类:荔枝蝽、黄脊竹蝗、美国白蛾、落叶卷叶蛾、中华稻蝗等。
数据集 图片总数 标注框总数 train 15180 17791 val 1897 2230 test 1899 2263 总计 18976 22284 chinese_name: {"rice_leaf_roller": "水稻卷叶螟","rice_leaf_caterpillar": "稻纵卷叶螟","paddy_stem_maggot": "稻茎潜蝇","asiatic_rice_borer": "亚洲玉米螟","yellow_rice_borer": "黄螟","rice_gall_midge": "稻瘿蚊","Rice_Stemfly": "水稻茎飞虱","brown_plant_hopper": "褐飞虱","white_backed_plant_hopper": "白背飞虱","small_brown_plant_hopper": "小褐飞虱","rice_water_weevil": "稻水象甲","rice_leafhopper": "稻叶蝉","grain_spreader_thrips": "谷斑蓟马","rice_shell_pest": "稻壳虫","grub": "蛴螬","mole_cricket": "蝼蛄","wireworm": "金针虫","white_margined_moth": "白边夜蛾","black_cutworm": "黑尾切叶虫","large_cutworm": "大切叶虫","yellow_cutworm": "黄切叶虫","red_spider": "红蜘蛛","corn_borer": "玉米螟","army_worm": "草地螟","aphids": "蚜虫","Potosiabre_vitarsis": "光肩星天牛","peach_borer": "桃蛀螟","english_grain_aphid": "麦长管蚜","green_bug": "绿盲蝽","bird_cherry-oataphid": "麦二叉蚜","wheat_blossom_midge": "小麦花蓟马","penthaleus_major": "麦长足螨","longlegged_spider_mite": "长腿蜘蛛螨","wheat_phloeothrips": "小麦裂管蓟马","wheat_sawfly": "小麦锯蜂","cerodonta_denticornis": "角锯潜蝇","beet_fly": "甜菜蝇","flea_beetle": "跳甲","cabbage_army_worm": "甘蓝夜蛾","beet_army_worm": "甜菜夜蛾","Beet_spot_flies": "甜菜斑蝇","meadow_moth": "草地蛾","beet_weevil": "甜菜象甲","sericaorient_alismots_chulsky": "东方萤叶甲","alfalfa_weevil": "苜蓿象甲","flax_budworm": "亚麻蕾虫","alfalfa_plant_bug": "苜蓿盲蝽","tarnished_plant_bug": "花盲蝽","Locustoidea": "蝗虫","lytta_polita": "丽缘红姬甲","legume_blister_beetle": "豆类芫菁","blister_beetle": "芫菁","therioaphis_maculata_Buckton": "斑点蚜","odontothrips_loti": "豆蓟马","Thrips": "蓟马","alfalfa_seed_chalcid": "苜蓿种子小蜂","Pieris_canidia": "菜粉蝶","Apolygus_lucorum": "绿盲蝽","Limacodidae": "斑鳞蛾科","Viteus_vitifoliae": "葡萄根瘤蚜","Colomerus_vitis": "葡萄瘿螨","Brevipoalpus_lewisi_McGregor": "刘氏短角螨","oides_decempunctata": "十星叶甲","Polyphagotars_onemus_latus": "宽翅粉虱","Pseudococcus_comstocki_Kuwana": "康氏粉蚧","parathrene_regalis": "皇家长尾蛾","Ampelophaga": "葡萄天蛾","Lycorma_delicatula": "斑衣蜡蝉","Xylotrechus": "枯叶甲","Cicadella_viridis": "绿蝉","Miridae": "盲蝽科","Trialeurodes_vaporariorum": "温室白粉虱","Erythroneura_apicalis": "顶端红斑叶蝉","Papilio_xuthus": "柑橘凤蝶","Panonchus_citri_McGregor": "柑橘全爪螨","Phyllocoptes_oleiverus_ashmead": "橄榄瘿螨","Icerya_purchasi_Maskell": "吹绵介壳虫","Unaspis_yanonensis": "薛氏介壳虫","Ceroplastes_rubens": "红蜡介壳虫","Chrysomphalus_aonidum": "圆盾蚧","Parlatoria_zizyphus_Lucus": "枣圆盾蚧","Nipaecoccus_vastalor": "葡萄粉蚧","Aleurocanthus_spiniferus": "柑橘粉虱","Tetradacus_c_Bactrocera_minax": "大实蝇","Dacus_dorsalis(Hendel)": "东方果实蝇","Bactrocera_tsuneonis": "桔小实蝇","Prodenia_litura": "斜纹夜蛾","Adristyrannus": "金带夜蛾","Phyllocnistis_citrella_Stainton": "柑橘潜叶蛾","Toxoptera_citricidus": "柑橘黑蚜","Toxoptera_aurantii": "柑橘蚜","Aphis_citricola_Vander_Goot": "柑橘棉蚜","Scirtothrips_dorsalis_Hood": "花蓟马","Dasineura_sp": "瘿蚊属","Lawana_imitata_Melichar": "拟卷叶蝉","Salurnis_marginella_Guerr": "小缘天牛","Deporaus_marginatus_Pascoe": "边缘象鼻虫","Chlumetia_transversa": "柑橘夜蛾","Mango_flat_beak_leafhopper": "芒果扁喙叶蝉","Rhytidodera_bowrinii_white": "皱头天牛","Sternochetus_frigidus": "坚果象甲","Cicadellidae": "叶蝉科",'无目标': '无目标' }
数据预处理与增强:为提升模型泛化能力,采用了多种数据增强策略:
-
几何变换: 随机旋转(-15°-15°)、缩放(0.8~1.2)、翻转
# 随机旋转-15°~15°、缩放0.8~1.2、随机翻转,输入输出640x640import random from typing import Tuple import cv2 import numpy as npdef aug_random_rotate_scale_flip_640(image_bgr: np.ndarray,angle_range: Tuple[float, float] = (-15.0, 15.0),scale_range: Tuple[float, float] = (0.8, 1.2),flip_horizontal_prob: float = 0.5,flip_vertical_prob: float = 0.0,border_mode: int = cv2.BORDER_REFLECT_101 ) -> np.ndarray:"""输入/输出均为 BGR uint8,尺寸固定为 640x640。"""image_bgr = cv2.resize(image_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)h, w = image_bgr.shape[:2]angle_deg = random.uniform(*angle_range)scale = random.uniform(*scale_range)matrix = cv2.getRotationMatrix2D((w / 2.0, h / 2.0), angle_deg, scale)out = cv2.warpAffine(image_bgr, matrix, (w, h), flags=cv2.INTER_LINEAR, borderMode=border_mode)if random.random() < flip_horizontal_prob:out = cv2.flip(out, 1)if random.random() < flip_vertical_prob:out = cv2.flip(out, 0)return out
-
颜色变换: 亮度调整(±20%)、对比度调整(±20%)、色相偏移(±10°)
# 亮度±20%、对比度±20%、色相±10°,输入输出640x640import random import cv2 import numpy as npdef aug_random_brightness_contrast_hue_640(image_bgr: np.ndarray,brightness_delta_ratio: float = 0.2, # 作用于V通道contrast_delta_ratio: float = 0.2, # 绕全局均值缩放hue_delta_deg: float = 10.0 # ±10° ) -> np.ndarray:"""输入/输出均为 BGR uint8,尺寸固定为 640x640。"""image_bgr = cv2.resize(image_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)h, s, v = cv2.split(hsv)# H: 0~179,对应0~360°,10°≈5单位max_shift_units = hue_delta_deg * (180.0 / 360.0)h_shift = int(round(random.uniform(-max_shift_units, max_shift_units)))h = ((h.astype(np.int32) + h_shift) % 180).astype(np.uint8)# 亮度(V通道缩放)brightness_factor = random.uniform(1.0 - brightness_delta_ratio, 1.0 + brightness_delta_ratio)v = np.clip(v.astype(np.float32) * brightness_factor, 0, 255).astype(np.uint8)hsv_adj = cv2.merge([h, s, v])bgr = cv2.cvtColor(hsv_adj, cv2.COLOR_HSV2BGR)# 对比度(BGR)alpha = random.uniform(1.0 - contrast_delta_ratio, 1.0 + contrast_delta_ratio)bgr_f = bgr.astype(np.float32)mean_val = float(bgr_f.mean())contrasted = (bgr_f - mean_val) * alpha + mean_valreturn np.clip(contrasted, 0, 255).astype(np.uint8)
-
混合增强: Mosaic、CutMix、MixUp等先进增强技术
# Mosaic:4图拼接为一图,输出640x640import random from typing import List, Tuple import cv2 import numpy as npdef _resize_to(image_bgr: np.ndarray, size_wh: Tuple[int, int]) -> np.ndarray:w, h = size_whreturn cv2.resize(image_bgr, (w, h), interpolation=cv2.INTER_LINEAR)def aug_mosaic_640(images_bgr: List[np.ndarray]) -> np.ndarray:"""输入:长度为4的 BGR 图像列表(任意尺寸)。输出:BGR uint8 640x640。"""assert len(images_bgr) == 4, "Mosaic需要4张图像"W, H = 640, 640cx = random.randint(int(0.25 * W), int(0.75 * W))cy = random.randint(int(0.25 * H), int(0.75 * H))canvas = np.zeros((H, W, 3), dtype=np.uint8)tile_sizes = [(cx, cy), (W - cx, cy), (cx, H - cy), (W - cx, H - cy)]placements = [(0, 0, cx, cy), (cx, 0, W, cy), (0, cy, cx, H), (cx, cy, W, H)]for i in range(4):tw, th = tile_sizes[i]x0, y0, x1, y1 = placements[i]resized = _resize_to(images_bgr[i], (tw, th))canvas[y0:y1, x0:x1] = resizedreturn canvas
# MixUp:两图线性混合,输出640x640from typing import Tuple import cv2 import numpy as npdef aug_mixup_640(img1_bgr: np.ndarray,label1: np.ndarray,img2_bgr: np.ndarray,label2: np.ndarray,alpha: float = 0.2 ) -> Tuple[np.ndarray, np.ndarray]:"""label 支持 one-hot 或概率分布向量。输出:混合后的图像(640x640)与标签。"""img1_bgr = cv2.resize(img1_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)img2_bgr = cv2.resize(img2_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)lam = np.random.beta(alpha, alpha) if alpha > 0 else 1.0img1_f = img1_bgr.astype(np.float32) / 255.0img2_f = img2_bgr.astype(np.float32) / 255.0mixed_img = lam * img1_f + (1.0 - lam) * img2_fmixed_img = np.clip(mixed_img * 255.0, 0, 255).astype(np.uint8)mixed_label = lam * label1 + (1.0 - lam) * label2return mixed_img, mixed_label
# CutMix:矩形区域替换,按面积加权标签,输出640x640import math from typing import Tuple import cv2 import numpy as npdef _rand_bbox(width: int, height: int, lam: float) -> Tuple[int, int, int, int]:cut_w = int(width * math.sqrt(1.0 - lam))cut_h = int(height * math.sqrt(1.0 - lam))cx = np.random.randint(0, width)cy = np.random.randint(0, height)x1 = np.clip(cx - cut_w // 2, 0, width)y1 = np.clip(cy - cut_h // 2, 0, height)x2 = np.clip(cx + cut_w // 2, 0, width)y2 = np.clip(cy + cut_h // 2, 0, height)return int(x1), int(y1), int(x2), int(y2)def aug_cutmix_640(img1_bgr: np.ndarray,label1: np.ndarray,img2_bgr: np.ndarray,label2: np.ndarray,alpha: float = 1.0 ) -> Tuple[np.ndarray, np.ndarray]:"""label 支持 one-hot 或概率分布向量。输出:混合后的图像(640x640)与标签。"""img1_bgr = cv2.resize(img1_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)img2_bgr = cv2.resize(img2_bgr, (640, 640), interpolation=cv2.INTER_LINEAR)h, w = img1_bgr.shape[:2]lam = np.random.beta(alpha, alpha) if alpha > 0 else 1.0x1, y1, x2, y2 = _rand_bbox(w, h, lam)out = img1_bgr.copy()out[y1:y2, x1:x2] = img2_bgr[y1:y2, x1:x2]box_area = max(0, x2 - x1) * max(0, y2 - y1)lam_adj = 1.0 - box_area / float(w * h)mixed_label = lam_adj * label1 + (1.0 - lam_adj) * label2return out, mixed_label
-
自适应增强: 基于类别平衡的重采样策略
import random from typing import List, Optional import numpy as npdef compute_class_counts(targets: List[int], num_classes: Optional[int] = None) -> np.ndarray:if num_classes is None:num_classes = int(max(targets)) + 1 if len(targets) > 0 else 0counts = np.zeros(num_classes, dtype=np.int64)for t in targets:counts[t] += 1return countsdef make_weight_list_for_targets(targets: List[int]) -> List[float]:counts = compute_class_counts(targets)weights_per_class = {cls: (1.0 / cnt if cnt > 0 else 0.0) for cls, cnt in enumerate(counts.tolist())}return [weights_per_class[t] for t in targets]def balanced_resample_indices(targets: List[int],num_samples: Optional[int] = None,seed: Optional[int] = None ) -> List[int]:"""依据类别频次的倒数作为权重,有放回抽样返回索引。"""rng = random.Random(seed)weights = make_weight_list_for_targets(targets)total_w = float(sum(weights))if total_w <= 0:return list(range(len(targets))) if num_samples is None else list(range(min(len(targets), num_samples)))probs = [w / total_w for w in weights]prefix = []acc = 0.0for p in probs:acc += pprefix.append(acc)def draw_one() -> int:u = rng.random()lo, hi = 0, len(prefix) - 1while lo < hi:mid = (lo + hi) // 2if prefix[mid] >= u:hi = midelse:lo = mid + 1return lon = len(targets) if num_samples is None else int(num_samples)return [draw_one() for _ in range(n)]
说明: 所有图像增强函数都保证输出为
640x640(BGR, uint8)
。如需批量使用,可在各自脚本中读取图像后调用对应函数。
-
train.py
训练模型#coding:utf-8from ultralytics import YOLO# 加载预训练模型model = YOLO("ultralytics/cfg/models/v8/det_self/yolov8s-attention-SE.yaml").load('yolov8n.pt')# Use the modelif __name__ == '__main__':# Use the modelresults = model.train(data='datasets/TomatoData/data.yaml', epochs=250, batch=4) # 训练模型# 将模型转为onnx格式# success = model.export(format='onnx')
-
训练结果曲线
注:损失函数等训练结果细节在此不再赘述!!!
2.4 LLM 决策模块设计
AIClient
抽象与并发调用:实现 AIClient
统一接口以封装不同服务商(智谱、阿里千问、百度千帆等)API
;支持并行/异步调用并对多模型回复进行融合与一致性校验。
class AIClient:def __init__(self, model_config):self.provider = model_config.get('provider')self.api_base = model_config.get('api_base')self.model = model_config.get('model')self.api_key = model_config.get('api_key')def get_advice(self, pest_info, timeout=30):if self.provider == 'zhipu':return self._call_zhipu_api(pest_info, timeout)elif self.provider == 'qwen':return self._call_qwen_api(pest_info, timeout)# ... 其他提供商
2.5 PromptManager 与模板化提示词
设计多层提示词模板:诊断上下文(检测结果、置信度、作物/生长阶段)、专家规则(处方型防治措施、药剂剂量/施用方法)、环境约束(禁用药物、当地法规)。模板支持按模型能力选取以控制响应长度与专业深度。
class PromptManager:def __init__(self, prompts_dir="prompts"):self.templates_dir = os.path.join(prompts_dir, "templates")self.prompts = {}self._load_prompts()def get_prompt(self, model_name):"""获取指定模型的专业化提示词"""return self.prompts.get(model_name, self.prompts['default'])
# 例如:deepseek_prompt.txt你是DeepSeek农业技术研究院的首席科学家,专注于深度学习和人工智能在农业领域的应用。请基于检测结果撰写一份1500字的《农作物病虫害深度防治技术报告》,要求:【报告结构】
1. 病虫害深度识别分析(300字)- 深度学习特征:神经网络识别、特征提取、准确率分析- 危害程度评估:多维度评估、影响分析、损失量化- 发展趋势预测:AI预测模型、风险评估、防控策略2. 深度防治技术体系(600字)- 机器学习算法:监督学习、无监督学习、强化学习应用- 计算机视觉技术:图像识别、目标检测、分割技术- 自然语言处理:知识图谱、智能问答、专家系统- 大数据分析:数据挖掘、模式识别、预测分析3. 智能化防治方案(300字)- AI决策系统:智能推荐、自动决策、优化算法- 自动化设备:智能机器人、自动化系统、远程控制- 精准防控技术:精准施药、变量管理、智能监控4. 技术实施与展望(300字)- 技术集成方案:系统架构、算法优化、性能提升- 投资成本分析:研发成本、部署成本、维护成本- 未来发展趋势:技术演进、应用前景、发展方向【写作要求】
- 体现DeepSeek技术特色,突出深度学习和AI应用
- 技术先进且实用,有具体的技术参数和算法
- 数据支撑充分,提供量化分析结果
- 字数必须达到1500字,内容详实具体
- 每个技术方案都要有具体的实施步骤和参数
- 提供技术发展趋势和投资建议
2.6 异步调用与超时保护
实现线程安全的异步LLM
调用:
class AdviceWorker(QThread):success = pyqtSignal(str)error = pyqtSignal(str)def run(self):try:advice = self.ai_client.get_advice(self.pest_info, self.timeout)self.success.emit(advice)except Exception as e:self.error.emit(str(e))
3. 用户界面设计
基于PyQt5
的现代化GUI
界面,支持:
- 多源输入管理(图片/视频/摄像头/目录)
- 实时检测结果可视化
- 检测参数动态调整
AI
建议异步获取与展示- 结果导出与归档管理
3.1 运行时架构与数据流
- UI 层:
MyMainWindow(QMainWindow, Ui_MainWindow)
负责交互、显示、路径选择、定时帧处理(QTimer 20ms)。 - 推理层:使用
YOLO(weights).predict(img, imgsz, conf, device, classes)
返回框、类别与置信度;tool.tools.format_data
统一为[name, score, [x1,y1,x2,y2]]
。 - 可视化:
tool.tools.draw_info
渲染检测框与标签;resize_with_padding
保持纵横比填充显示。 - AI 决策:
AIClient
采用策略模式封装多家 API;AdviceWorker(QThread)
异步拉取文本建议;prompts.core.prompt_manager
负责模板加载。 - 输出归档:用户点击“保存结果”后,系统在
output/
下以中文类别名合成目录,保存结果 JPG 与“防治方案.txt”。
### 农作物病虫害综合防治技术报告#### 1. 病虫害识别与诊断**形态特征描述:** 本次检测到的蚜虫,经形态特征鉴定,为麦长管蚜(Sitobion avenae)。成虫体型微小,长2-3.5毫米,体色黄绿色,触角5节,前翅膜质,无色或淡色。卵长约0.2毫米,椭圆形,产于叶片背面。幼虫无翅,绿色,体长约2毫米,体节明显。**危害症状分析:** 麦长管蚜主要危害麦类作物,成虫和若虫聚集在叶片、茎秆和穗部吸取汁液,导致叶片变黄、卷曲,严重时叶片干枯死亡。茎秆受害后,生长受阻,穗部受害后,产量下降,籽粒不饱满。**发生规律总结:** 麦长管蚜一年发生10-20代,以卵在麦株越冬。春季气温回升至10℃以上时开始孵化,世代重叠现象严重。喜温暖湿润环境,在干旱条件下,发生量会减少。#### 2. 综合防治技术方案**农业防治:** - 栽培管理:选择抗蚜虫品种,合理密植,促进植株生长。 - 品种选择:选用抗性较强的品种,如“豫麦18”等。 - 轮作制度:与非禾本科作物轮作,减少蚜虫发生。 - 田间卫生:清除田间杂草,减少蚜虫越冬场所。**生物防治:** - 天敌利用:保护和利用蚜虫的天敌,如瓢虫、草蛉等。 - 生物农药:使用生物农药,如苦参碱、印楝素等。 - 生态调控:调整田间生态环境,减少蚜虫的发生。 - 生物多样性保护:维护生物多样性,增加天敌数量。**物理防治:** - 诱杀技术:使用黄色板或蓝色板诱杀成虫。 - 隔离措施:建立隔离带,防止蚜虫扩散。 - 环境调控:利用温湿度调节,降低蚜虫繁殖率。 - 物理屏障:使用网罩、纱网等物理屏障阻止蚜虫侵入。**化学防治:** - 药剂选择:选用高效低毒的农药,如吡虫啉、啶虫脒等。 - 施药技术:采用喷雾、喷粉、喷烟等方法施药。 - 抗性管理:合理轮换使用农药,避免抗药性产生。 - 安全间隔期:施药后7-10天,确保农药降解。#### 3. 精准用药指导**推荐农药清单:** 1. 吡虫啉:高效低毒,适用于防治多种蚜虫。 2. 啶虫脒:广谱杀虫剂,对蚜虫有较好的防治效果。 3. 苦参碱:生物农药,对蚜虫有强烈的触杀和胃毒作用。 4. 印楝素:生物农药,对蚜虫有良好的防治效果。 5. 阿维菌素:广谱杀虫剂,对蚜虫有触杀和胃毒作用。**用药剂量与时机:** - 吡虫啉:每亩用量10-20克,稀释倍数500-1000倍,最佳施药时间为蚜虫孵化盛期。 - 啶虫脒:每亩用量20-30克,稀释倍数500-1000倍,最佳施药时间为蚜虫盛发期。 - 苦参碱:每亩用量30-50克,稀释倍数1000-2000倍,最佳施药时间为蚜虫发生初期。 - 印楝素:每亩用量30-50克,稀释倍数1000-2000倍,最佳施药时间为蚜虫发生初期。 - 阿维菌素:每亩用量10-20克,稀释倍数500-1000倍,最佳施药时间为蚜虫盛发期。**轮换用药策略:** - 抗性管理:合理轮换使用不同作用机理的农药,减少抗药性产生。 - 药剂组合:根据实际情况,合理组合使用不同农药。 - 交替使用方案:交替使用不同作用机理的农药,如先使用吡虫啉,再使用啶虫脒。#### 4. 技术要点与注意事项**关键技术要点:** - 操作要点:严格按照农药使用说明进行操作,确保施药均匀。 - 技术难点:防治蚜虫需要及时发现和防治,避免造成大面积危害。 - 成功关键因素:合理选择防治方法,科学用药,加强田间管理。**安全防护措施:** - 人员防护:施药人员应穿戴防护服、手套、口罩等。 - 环境安全:施药时注意风向,避免药液飘移到非靶区。 - 残留控制:严格按照安全间隔期使用农药,确保农产品安全。**效果评估方法:** - 防治效果指标:观察叶片黄化、卷曲等症状的减少情况。 - 评估时间:施药后7-10天进行效果评估。 - 改进措施:根据效果评估结果,调整防治策略。通过以上综合防治技术方案,可以有效控制麦长管蚜的发生和危害,确保农作物产量和品质。
4. 安装与部署
4.1 环境要求
- 操作系统:Windows 10/11(推荐)、Ubuntu 20.04+;macOS 可运行但 PyQt/显示依赖需额外处理
- Python:3.8~3.10(建议 3.10)
- GPU(可选):NVIDIA 显卡与匹配 CUDA 驱动
4.2 依赖安装(本地)
以下为分平台的完整指令。建议先准备虚拟环境并升级 pip。
4.2.1 Windows(PowerShell)
# 1) 创建与激活虚拟环境
python -m venv .venv
. .venv/Scripts/Activate.ps1
python -m pip install --upgrade pip# 2) 安装依赖(优先使用项目内 requirements)
pip install -r requirements.txt# 2.1) 如需CPU版PyTorch(若requirements未固定或需替换)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu# 2.2) 如需GPU版PyTorch(示例:CUDA 11.8)
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118# 3) 首次运行(GUI)
python main.py
# cmd命令差异
:: cmd环境激活
.venv\Scripts\activate
python -m pip install --upgrade pip
4.2.2 Ubuntu/Debian(apt)
# 0) 系统依赖(OpenCV/Qt运行库等)
sudo apt-get update
sudo apt-get install -y \python3 python3-venv python3-pip \build-essential git curl ca-certificates \libgl1 libglib2.0-0 libxext6 libxrender1 libsm6# 1) 虚拟环境
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip# 2) 安装依赖
pip install -r requirements.txt
# 可选:CPU/GPU PyTorch
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118# 3) 首次运行(无头服务器可参考4.3)
python main.py
4.2.3 CentOS/RHEL(yum/dnf)
# 0) 系统依赖
sudo yum -y update || sudo dnf -y update
sudo yum install -y \python3 python3-pip python3-venv \gcc gcc-c++ make git curl \mesa-libGL mesa-libGLU libXext libXrender libSM# 1) 虚拟环境
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip# 2) 安装依赖
pip install -r requirements.txt
# 可选:CPU/GPU PyTorch
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu
# pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118# 3) 运行
python main.py
4.2.4 Ubuntu/CentOS
# 系统依赖(Ubuntu 示例)
sudo apt-get update && sudo apt-get install -y \python3 python3-pip python3-venv build-essential \libgl1-mesa-glx libglib2.0-0 libxext6 libxrender1 libsm6 \libxrandr2 libasound2 libgtk-3-0 libgstreamer1.0-0 \libgstreamer-plugins-base1.0-0# Python 虚拟环境
python3 -m venv pest-env
source pest-env/bin/activate
pip install --upgrade pip# 获取代码并安装
git clone https://github.com/xxx/pest-detection.git # 测试阶段还未开源
cd pest-detection
pip install -r requirements.txt# 可选:PyQt5 安装问题
sudo apt-get install -y python3-pyqt5 || pip install PyQt5==5.15.9# 运行
python main.py
4.2.5 macOS
# Homebrew 安装
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"brew install python3 qt5 opencv
export PATH="/usr/local/opt/qt5/bin:$PATH"python3 -m venv pest-env
source pest-env/bin/activategit clone https://github.com/xxx/pest-detection.git # 测试阶段还未开源
cd pest-detection
pip install -r requirements.txt
4.3 服务器(无头)部署
sudo apt-get update && sudo apt-get install -y python3 python3-pip python3-venv xvfbpython3 -m venv pest-env
source pest-env/bin/activate# 获取项目与依赖
git clone https://github.com/xxxx/pest-detection.git # 测试阶段还没开源
cd pest-detection
pip install -r requirements.txt
pip install opencv-python-headless# 启动脚本
cat > start_pest_detection.sh << 'EOF'
#!/bin/bash
cd /path/to/pest-detection
source pest-env/bin/activate
export QT_X11_NO_MITSHM=1
export DISPLAY=:99
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
python main.py
EOF
chmod +x start_pest_detection.sh# 后台运行(screen/tmux 二选一)
screen -S pest-detection -dm bash -lc './start_pest_detection.sh'
4.3.1 systemd 服务
sudo tee /etc/systemd/system/pest-detection.service << EOF
[Unit]
Description=Pest Detection System
After=network.target[Service]
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/pest-detection
Environment=PATH=/home/ubuntu/pest-detection/pest-env/bin
Environment=DISPLAY=:99
ExecStartPre=/usr/bin/Xvfb :99 -screen 0 1024x768x24
ExecStart=/home/ubuntu/pest-detection/pest-env/bin/python main.py
Restart=always
RestartSec=10[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
sudo systemctl enable --now pest-detection
4.4 Docker 部署(docs/docker)
4.4.1 CPU 镜像
# 构建(在项目根目录)
docker build -f docs/docker/Dockerfile -t pest-detection:cpu .
# 运行
docker run -it --rm --name pest-cpu -v $(pwd):/app pest-detection:cpu
4.4.2 GPU 镜像(CUDA 11.8)
# 安装 nvidia-docker2 并重启 docker 后:
docker build -f docs/docker/Dockerfile.gpu -t pest-detection:gpu .
docker run --rm --gpus all pest-detection:gpu nvidia-smidocker run -it --rm --name pest-gpu --gpus all -v $(pwd):/app pest-detection:gpu
4.4.3 Docker Compose(CPU/GPU)
cd docs/docker
# 启动 CPU
docker-compose up pest-cpu -d
# 启动 GPU
docker-compose up pest-gpu -d
# 查看状态
docker-compose ps
# 查看日志
docker-compose logs -f pest-cpu
5. 局限性与风险
- 样本不平衡:部分罕见类别样本仍不足,未来需扩充数据或采用少样本学习/数据合成策略。
LLM
专业性验证:生成建议仍需农业专家复核,避免误导性处方。- 成本与网络依赖:频繁调用远程
LLM
会带来成本与延迟,需结合需求制定混合策略(云+边缘)。
6. 未来发展方向
6.1 技术发展方向
为持续提升系统的智能化水平与诊断精度,未来将重点推进以下技术路径:
- 多模态融合:融合可见光图像、红外影像及环境传感器(如温湿度、光照、土壤数据)等多源信息,构建多模态联合分析模型,实现更精准、全面的病害识别与环境关联诊断。
- 边缘计算:研发轻量化神经网络模型,优化推理效率,支持在嵌入式设备或移动终端上的低功耗、离线部署,满足田间实时响应需求。
- 联邦学习:构建基于联邦学习的分布式训练框架,在不共享原始数据的前提下实现多方协同建模,有效保护农户与机构的数据隐私。
- 时序分析:引入时间序列建模能力,结合历史监测数据,对病害发生与蔓延趋势进行动态预测,助力早期预警与主动防控。
6.2 应用拓展方向
面向多样化农业场景,系统将向更广泛的应用形态延伸:
- 移动端适配:开发用户友好的智能手机应用程序(
App
),支持拍照识别、实时诊断与管理记录,提升技术的可及性与便携性。 - 无人机集成:对接无人机遥感平台,实现大范围农田的自动巡航与高清图像采集,提升监测效率与覆盖能力。
- IoT融合:深度集成农业物联网(
IoT
)系统,实现与智能灌溉、温室控制等设备的联动,构建闭环智慧农业解决方案。 - 区块链溯源:结合区块链技术,建立农产品生长全过程的可信数据链,实现病害防控信息的可追溯,增强食品安全保障。
6.3 生态系统构建
推动技术落地与规模化应用,需构建开放协同的产业生态:
- 数据共享平台:建设开放、标准化的农作物病害图像与案例数据库,鼓励科研机构与企业共享数据资源,促进模型迭代与技术创新。
- 专家网络:搭建人机协同的专家支持系统,融合AI诊断结果与农业专家经验,提供权威、可解释的防治建议。
- 标准制定:积极参与农业AI相关技术标准与数据规范的制定,推动行业规范化发展。
- 国际合作:加强与“一带一路”沿线国家及国际农业组织的合作,输出中国智慧农业解决方案,提升全球影响力。
7. Conclusion
本文提出了一种基于YOLOv8-SEAttention融合多模态大语言模型的农作物病虫害智能检测与防治决策支持系统。通过技术创新和工程实践,系统实现了从"检测识别"到"智能决策"的全链路闭环,为智慧农业提供了完整的解决方案。
主要成果包括:
- 提出了YOLOv8-SEAttention融合架构,在102类病虫害检测任务上取得 89.2% 的 mAP@0.5,相比基线提升3.5个百分点
- 设计了统一的多LLM集成框架,支持智谱、千问、千帆等主流中文大模型
- 构建了专业化的提示词工程体系,显著提升AI建议的专业性和实用性
- 开发了完整的应用系统,支持多环境部署和实际应用
本系统不仅在检测精度上有显著提升,更重要的是通过LLM集成实现了从"工具
"到"专家助手
"的角色转变,为推动农业AI技术产业化应用提供了有价值的参考。