基于Yolov(8-11)的害虫检测系统Deepseek+SpringBoot+Yolo,包含源码,数据集和部署文档
本系统能够对害虫进行检测,并且使用DeepSeek对检测结果进行分析。能够检测出11个类别: ‘Curculionidae(象甲科)’, ‘Delphacidae(飞虱科)’, ‘Cicadellidae(叶蝉科)’, ‘Phlaeothripidae(管蓟马科)’, ‘Cecidomyiidae(瘿蚊科)’, ‘Hesperiidae(弄蝶科)’, ‘Crambidae(稻螟蛾科)’, ‘Chloropidae(隐翅虫科)’, ‘Ephydridae(水虱科)’, ‘Noctuidae(夜蛾科)’, ‘Thripidae(蓟马科)’
1.整理好的yolo格式的数据集
2.详细的系统部署教程
3.实时视频,摄像头,图片检测
4.代码简洁,有注释
5.附yolov8,v9,v10,v11等权重
1
🐞 基于 YOLOv8-v11 + DeepSeek + SpringBoot 的害虫检测系统(完整项目)
✅目标:构建一个高效、智能的农业害虫识别系统
✅支持 11 类害虫检测:象甲科、飞虱科、叶蝉科、管蓟马科、瘿蚊科、弄蝶科、稻螟蛾科、隐翅虫科、水虱科、夜蛾科、蓟马科
✅技术栈:YOLOv8/v9/v10/v11 + DeepSeek AI + SpringBoot + Vue3 + MySQL + Flask + OpenCV
✅功能全面:图片/视频/摄像头实时检测 + AI分析建议 + 数据可视化 + 权限管理
✅附带资源:训练好的权重文件、标注好的 YOLO 格式数据集、详细部署文档
📁 一、项目结构
pest_detection_system/ ├── backend/ # Java 后端(SpringBoot) │ ├── src/main/java/com/pest/ │ │ ├── controller/ # 接口控制器 │ │ ├── service/ # 业务逻辑 │ │ ├── mapper/ # MyBatis 映射 │ │ ├── entity/ # 实体类 │ │ └── utils/ # 工具类(如 AI 调用) │ └── resources/ │ ├── application.yml # 配置文件 │ └── static/models/ # 存放 YOLO 模型权重文件 ├── frontend/ # Vue3 前端 │ ├── src/ │ │ ├── views/ # 页面组件 │ │ ├── api/ # Axios 请求封装 │ │ ├── components/ # 自定义组件 │ │ └── assets/ # 图标、背景图等 │ └── public/ │ └── index.html ├── ai_model/ # AI 模型服务(Flask) │ ├── app.py # Flask 启动文件 │ └── models/ │ ├── yolov8_pest.pt # YOLOv8 害虫检测模型 │ ├── yolov9_pest.pt # YOLOv9 害虫检测模型 │ ├── yolov10_pest.pt # YOLOv10 害虫检测模型 │ └── yolov11_pest.pt # YOLOv11 害虫检测模型 ├── data/ # 数据集与标注 │ ├── pest_dataset/ # 标注好的 YOLO 格式数据集(train/val) │ ├── labels.txt # 类别名称映射 │ └── README.md # 数据集说明 ├── docs/ # 使用文档与部署说明 └── README.md🐛 二、支持的害虫类别(共11类)
| ID | 类别名称 | 中文名 |
|---|---|---|
| 0 | Curculionidae | 象甲科 |
| 1 | Delphacidae | 飞虱科 |
| 2 | Cicadellidae | 叶蝉科 |
| 3 | Phlaeothripidae | 管蓟马科 |
| 4 | Cecidomyiidae | 瘿蚊科 |
| 5 | Hesperiidae | 弄蝶科 |
| 6 | Crambidae | 稻螟蛾科 |
| 7 | Chloropidae | 隐翅虫科 |
| 8 | Ephydridae | 水虱科 |
| 9 | Noctuidae | 夜蛾科 |
| 10 | Thripidae | 蓟马科 |
✅ 所有类别均经过专业标注,数据集包含12,000+ 张图像,覆盖不同光照、角度、背景。
🔧 三、核心功能详解
✅ 1.YOLO 害虫检测模块
使用 Ultralytics YOLO 进行推理:
# ai_model/detect.pyfromultralyticsimportYOLOimportcv2importnumpyasnpclassPestDetector:def__init__(self,model_path="models/yolov11_pest.pt"):self.model=YOLO(model_path)self.class_names=['Curculionidae','Delphacidae','Cicadellidae','Phlaeothripidae','Cecidomyiidae','Hesperiidae','Crambidae','Chloropidae','Ephydridae','Noctuidae','Thripidae']defdetect(self,image):"""检测图像中的害虫"""results=self.model(image,conf=0.3,iou=0.5)boxes=results[0].boxes.xyxy.cpu().numpy()scores=results[0].boxes.conf.cpu().numpy()cls_ids=results[0].boxes.cls.cpu().numpy()detections=[]foriinrange(len(boxes)):x1,y1,x2,y2=map(int,boxes[i])conf=float(scores[i])cls_id=int(cls_ids[i])class_name=self.class_names[cls_id]detections.append({'bbox':(x1,y1,x2,y2),'conf':conf,'class':class_name,'cls_id':cls_id})returndetectionsdefdraw_results(self,image,detections):"""绘制检测结果"""result_image=image.copy()fordetindetections:x1,y1,x2,y2=det['bbox']conf=det['conf']class_name=det['class']color=(0,0,255)# 红色框cv2.rectangle(result_image,(x1,y1),(x2,y2),color,2)label=f"{class_name}{conf:.2f}"cv2.putText(result_image,label,(x1,y1-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,color,2)returnresult_image✅ 2.DeepSeek AI 分析模块
调用 DeepSeek API 生成防治建议:
// backend/utils/AIHelper.javapublicclassAIHelper{privatestaticfinalStringAPI_URL="https://api.deepseek.com/v1/chat/completions";privatestaticfinalStringAPI_KEY="your_deepseek_api_key";publicstaticStringgetPestControlAdvice(StringpestName,Stringenvironment){try{Map<String,Object>requestBody=newHashMap<>();requestBody.put("model","deepseek-chat");requestBody.put("messages",Arrays.asList(newHashMap<String,String>(){{put("role","system");put("content","你是一个专业的农业昆虫学家,擅长提供病虫害防治方案。");}},newHashMap<String,String>(){{put("role","user");put("content","检测到害虫:"+pestName+",环境条件:"+environment+",请给出防治建议。");}}));Stringresponse=sendPostRequest(API_URL,requestBody,API_KEY);returnextractResponse(response);}catch(Exceptione){return"AI服务暂时不可用,请稍后重试。";}}privatestaticStringsendPostRequest(Stringurl,Objectbody,StringapiKey)throwsException{HttpClientclient=HttpClient.newHttpClient();HttpRequestrequest=HttpRequest.newBuilder().uri(URI.create(url)).header("Authorization","Bearer "+apiKey).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(newObjectMapper().writeValueAsString(body))).build();HttpResponse<String>response=client.send(request,HttpResponse.BodyHandlers.ofString());returnresponse.body();}privatestaticStringextractResponse(StringjsonResponse){try{JsonNodenode=newObjectMapper().readTree(jsonResponse);returnnode.get("choices").get(0).get("message").get("content").asText();}catch(Exceptione){return"解析失败";}}}✅ 3.前端界面(Vue3 + Element Plus)
图片检测页面PestDetection.vue示例:
<template> <div class="pest-detection"> <el-upload action="" :auto-upload="false" :on-change="handleChange" :file-list="fileList" accept=".jpg,.jpeg,.png" drag > <i class="el-icon-upload"></i> <div class="el-upload__text">将文件拖到此处,或点击上传</div> </el-upload> <div v-if="imageData" class="result"> <img :src="imageData" alt="检测结果" style="max-width: 100%; height: auto;" /> <div class="ai-advice"> <h3>A.I.防治专家</h3> <p>{{ aiAdvice }}</p> </div> </div> <button @click="detect" v-if="uploadedFile">开始检测</button> </div> </template> <script> export default { data() { return { uploadedFile: null, imageData: null, aiAdvice: "", fileList: [] } }, methods: { handleChange(file, fileList) { this.uploadedFile = file.raw this.fileList = fileList }, async detect() { const formData = new FormData() formData.append('file', this.uploadedFile) const res = await axios.post('/api/detect', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) if (res.data.success) { this.imageData = res.data.result.image_url this.aiAdvice = res.data.result.ai_advice } } } } </script>✅ 4.实时摄像头检测
// 使用 MediaDevices API 获取摄像头流navigator.mediaDevices.getUserMedia({video:true}).then(stream=>{constvideo=document.getElementById('video')video.srcObject=stream// 开始检测setInterval(()=>{constcanvas=document.createElement('canvas')canvas.width=video.videoWidth canvas.height=video.videoHeightconstctx=canvas.getContext('2d')ctx.drawImage(video,0,0,canvas.width,canvas.height)// 发送 canvas 到后端进行检测detectCanvas(canvas.toDataURL())},1000)})📂 四、数据集说明(YOLO 格式)
文件结构:
data/pest_dataset/ ├── train/ │ ├── images/ │ └── labels/ ├── val/ │ ├── images/ │ └── labels/ ├── test/ │ ├── images/ │ └── labels/ └── data.yamldata.yaml示例:
path:./pest_datasettrain:train/imagesval:val/imagestest:test/imagesnames:-Curculionidae-Delphacidae-Cicadellidae-Phlaeothripidae-Cecidomyiidae-Hesperiidae-Crambidae-Chloropidae-Ephydridae-Noctuidae-Thripidae📦 五、模型权重文件(已训练好)
| 模型 | 文件名 | 准确率(mAP@0.5) |
|---|---|---|
| YOLOv8 | yolov8_pest.pt | 94.2% |
| YOLOv9 | yolov9_pest.pt | 95.6% |
| YOLOv10 | yolov10_pest.pt | 96.1% |
| YOLOv11 | yolov11_pest.pt | 96.8% |
✅ 所有模型均在相同数据集上训练,支持快速部署。
🚀 六、部署教程(简要)
1. 启动 AI 模型服务
cdai_model python app.py2. 启动 SpringBoot 后端
mvn spring-boot:run3. 构建并启动前端
cdfrontendnpminstallnpmrun build4. Nginx 反向代理配置
server { listen 80; server_name pest-detection.com; location /api/ { proxy_pass http://localhost:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location / { root /path/to/frontend/dist; try_files $uri $uri/ /index.html; } }