YOLO26 Crop Disease Detection: Full-Stack System with FastAPI & Vue3

This article details a full-stack crop disease detection system using YOLO26 for object detection, FastAPI for backend services, and Vue3 for the frontend, covering architecture, database design, API endpoints, business logic, and deployment configuration.

java1234
java1234
java1234
YOLO26 Crop Disease Detection: Full-Stack System with FastAPI & Vue3

Project Overview

The system targets agricultural production and plant protection scenarios, performing object-detection-style pest and disease recognition on crop leaves (not simple image classification). Users can upload leaf images, videos, or use a webcam for real-time detection via a web management console. The backend uses YOLO26 for bounding-box detection, stores results, and automatically generates alerts based on configurable rules. A disease knowledge base (symptoms, hazards, control plans) and statistical analysis are also provided.

The system consists of three decoupled parts: client/ – Vue3 web management console (login, detection, records, alerts, knowledge base, statistics, profile). server/ – FastAPI backend (REST + WebSocket, JWT authentication, YOLO inference, file and alert handling). train_project/ – Offline training pipeline ( yolo26n.pt pre-trained → plantdiseases.yaml 30 classes → best.pt).

Recognition covers 13 crops (apple, pepper, corn, potato, tomato, grape, pumpkin, soybean, blueberry, cherry, peach, raspberry, strawberry) across 30 categories (including healthy and diseased leaves).

Business Logic

User Roles

Admin ( role=admin): full access – user management, model upload/default, alert rules, knowledge base editing, login/operation logs.

Regular user ( role=user): registration/login, image/video/realtime detection, detection records, alert handling, knowledge base viewing, model selection, profile, statistics.

Route guards: unauthenticated users redirect to /login; pages with meta.admin redirect non-admins to /home. Test accounts (plaintext password 123456): admin admin, users user01 / user02 / user03.

Functional Modules

Auth & Account : login, register (confirm password), logout; login writes to t_login_log.

Profile : avatar/nickname dropdown – profile (info edit with avatar upload) and password change.

Home Statistics : today’s detections, total detections, unhandled alerts, model/user counts; 7-day trend, top-10 categories, type distribution, alert levels, latest records (ECharts).

Smart Detection : image detection (sync), video detection (background thread + progress polling), webcam real-time detection (WebSocket).

Detection Records : paginated query, detail (bounding-box coordinates), delete, Excel export.

Alert Center : alert list handling/batch handling; admin configures alert rules (category, confidence threshold, level).

Disease Knowledge Base : view by crop/category – symptoms, hazards, control plans; admin editable.

Model Management : admin uploads .pt, sets default, enables/disables; regular users select active model (writes to t_user.active_model_id).

User Management : admin CRUD, enable/disable.

System Logs : login logs, operation logs (admin only).

Core Recognition Flow

Resolve model for current user: prefer active_model_id, else system default, else any enabled model. load_yolo caches YOLO weights by absolute path to avoid reloads.

Three detection entry points:

Image : upload → synchronous inference with bounding boxes → write record & details → match alerts → return result image.

Video : upload → background thread processes frame-by-frame → frontend polls progress.

Realtime : WebSocket pushes Base64 JPEG frames, backend returns detection boxes; optional disk persistence; realtime alerts deduplicated by time window.

Write t_detect_record (summary) and t_detect_detail (per-box class, confidence, coordinates). match_and_create_alarms: if detail confidence ≥ rule threshold for that category, write to t_alarm.

Files (original/result images, videos, avatars, models) stored under D:/uploads45, served statically via /uploads.

30 Recognition Categories

Classes 0–29 map to specific crop/disease combinations (e.g., 0: Apple Scab Leaf, 1: Apple Healthy Leaf, … 29: Grape Black Rot Leaf). Category definitions in train_project/plantdiseases.yaml and t_disease.class_id stay consistent.

Technology Stack

Frontend : Vue 3, Vite 8, Vue Router 4, Pinia, Element Plus, ECharts, Axios, Sass, dayjs.

Backend : Python 3, FastAPI, Uvicorn, SQLAlchemy 2, PyMySQL, Pydantic, python-jose (JWT HS256), python-multipart.

Database : MySQL 8, database db_plant_diseases, charset utf8mb4, port 3308 , user root/123456.

AI : Ultralytics YOLO26n, PyTorch, TorchVision, OpenCV, NumPy, Pillow.

Realtime : WebSocket (camera frame detection).

Export : openpyxl (detection records to Excel).

Training : Ultralytics + yolo26n.pt pre-trained, configured via plantdiseases.yaml (30 classes).

No WeChat Mini Program – web management console only.

System Architecture

Overall Architecture

Three-layer structure: presentation (Vue3) → service (FastAPI) → data & model (MySQL + file system + YOLO weights). Browser accesses Vue3 app; Vite proxies REST and WebSocket to FastAPI; FastAPI handles auth, inference, alerts, persistence; YOLO weights produced by offline training then uploaded to the business system.

System architecture diagram
System architecture diagram

Deployment & Runtime Architecture

Typical dev deployment: Browser → Vite (:5173) → Uvicorn/FastAPI (:8000) → MySQL (:3308) + local file directory + in-memory YOLO model cache.

Deployment architecture diagram
Deployment architecture diagram

Backend Layering

Request flows top-down: API routes → JWT dependencies → business services → ORM → MySQL & file/weight resources; response wrapped uniformly as { code, msg, data }.

Backend layers diagram
Backend layers diagram

API Route Layer : server/app/api/*.py – REST/WebSocket endpoints.

Auth Dependencies : core/security.py, core/deps.py – JWT parsing, get_current_user, require_admin.

Business Service Layer : service/yolo_service.py, alarm_service.py, file_service.py, utils/video.py – inference, alert matching, uploads, frame-by-frame video processing.

Data Access Layer : models/, schemas/, db/session.py – SQLAlchemy ORM, Pydantic input models, session management.

Base Resources : MySQL, D:/uploads45, .pt weight files.

Frontend Structure

client/src/
├── api/          Axios API wrappers (auth/user/model/detect/record/alarm/disease/stats/log)
├── layout/       Left menu + top bar (avatar dropdown: profile / logout)
├── router/       Routes & permission guards
├── stores/       Pinia user state (token, role, avatar)
├── views/        Business pages
│   ├── login/    Login, register
│   ├── home/     Home statistics charts
│   ├── detect/   Image / video / realtime detection
│   ├── record/   Detection records & details
│   ├── alarm/    Alert management, alert rules
│   ├── disease/  Disease knowledge base
│   ├── model/    Model management / selection
│   ├── user/     User management
│   ├── stats/    Statistical analysis
│   ├── log/      Login logs, operation logs
│   └── profile/  Profile (two-column: info + password)
└── utils/        Date formatting, etc.

Key API Endpoints

All endpoints prefixed with /api; unified response { code, msg, data } with success code === 200. /api/auth: POST /login, /register, /logout; GET /info. /api/user: GET /page; POST /create; PUT /{id}; DELETE /{id} (admin user management). /api/user: PUT /profile/info, /profile/password; POST /profile/avatar (profile). /api/model: GET /list; POST /upload, /select; PUT /{id}, /{id}/default; DELETE /{id}. /api/detect: POST /image, /video; GET /video/progress. /api/detect/realtime: WebSocket (query param token). /api/record: GET /page, /{id}, /export/excel; DELETE /{id}. /api/alarm: GET /page; PUT /{id}/handle; POST /batch-handle. /api/alarm (rules): GET /rule/list; POST /rule; PUT /rule/{id}; DELETE /rule/{id}. /api/disease: GET /page, /crops, /class/{id}, /{id}; PUT /{id}. /api/stats: GET /overview, /trend, /top-class, /type-ratio, /alarm-level, /latest. /api/log (admin): GET /login, /oper.

Communication Conventions

REST header: Authorization: Bearer <JWT>.

JWT payload contains user_id, username, role.

WebSocket cannot carry headers; token passed as query parameter.

Static resources: app.mount("/uploads", StaticFiles(UPLOAD_ROOT)).

CORS: allow_origins=["*"].

Business Processes (Mermaid Flowcharts)

The article includes flow diagrams for:

User login & permission

Image detection

Video detection

Realtime detection

Alert matching & handling

Model training & deployment

Login flow
Login flow
Image detection flow
Image detection flow
Video detection flow
Video detection flow
Realtime detection flow
Realtime detection flow
Alert matching flow
Alert matching flow
Model training & deployment flow
Model training & deployment flow

Database Design

Database: db_plant_diseases; table prefix t_; engine InnoDB, charset utf8mb4; no physical foreign keys – relationships maintained in application layer; schema script: server/sql/db_plant_diseases.sql.

Logical Relationships

t_user.active_model_id      → t_model.id
t_user.id                   → t_detect_record.user_id
t_model.id                  → t_detect_record.model_id
t_detect_record.id          → t_detect_detail.record_id
t_detect_record.id          → t_alarm.record_id
t_detect_detail.id          → t_alarm.detail_id
t_user.id                   → t_alarm.handler_id
t_disease.class_id          ↔ t_alarm_rule.class_id (YOLO category)
t_user.id                   → t_login_log.user_id / t_oper_log.user_id

Table Catalog

t_user

– user table t_model – YOLO model table t_detect_record – detection record table t_detect_detail – detection detail table (one record → multiple details) t_disease – disease knowledge base table (30 rows, one per YOLO class) t_alarm_rule – alert rule table (only for diseases needing alerts) t_alarm – alert record table t_login_log – login log table t_oper_log – operation log table

Key Table Schemas

t_user

PK: id; unique index uk_username(username). Fields: id (INT, PK), username (VARCHAR 50, unique), password (VARCHAR 100, plaintext per project convention), nickname, avatar, real_name, gender (default male), phone, email, role (admin/user, default user), status (1 enabled/0 disabled), active_model_id (FK to t_model), create_time, update_time.

t_model

PK: id. Fields: model_name, file_name, file_path, file_size, class_num (default 30), version, description, is_default (1/0), status (1 enabled/0 disabled), upload_user_id, create_time, update_time.

t_detect_record

PK: id; indexes idx_user_id, idx_detect_time. Fields: user_id, model_id, detect_type (image/video/realtime), source_name, source_path, result_path, target_count, top_class, top_confidence (DECIMAL 6,4), conf_threshold (default 0.2500), cost_ms, detect_time.

t_detect_detail

PK: id; index idx_record_id. One record per detected box. Fields: record_id, class_id, class_name, confidence, x1, y1, x2, y2 (DECIMAL 10,2).

t_disease

PK: id; unique index uk_class_id(class_id). Pre-filled 30 rows matching YOLO classes. Fields: class_id, class_name, crop_name, disease_name, is_healthy (1/0), symptom (TEXT), harm (TEXT), control_plan (TEXT), level (high/medium/low), image_path.

t_alarm_rule

PK: id; unique index uk_class_id(class_id). Only configured for diseases requiring alerts. Fields: class_id, class_name, conf_threshold (default 0.5000), alarm_level (high/medium/low), enabled (1/0), remark, create_time, update_time.

t_alarm

PK: id; indexes idx_status, idx_alarm_time. Fields: record_id, detail_id, class_name, confidence, alarm_level, alarm_time, status (unhandled/handled/ignored), handler_id, handle_time, handle_remark.

t_login_log & t_oper_log

Standard audit logs capturing user, IP, browser, OS, result, message, timestamp, and for operation logs: module, operation type (add/edit/delete/query/export/detect), request URL, params summary, cost_ms.

Directory & Code Mapping

plant_diseases/
├── 架构2.md                 # This document
├── image2/                  # Architecture images
│   ├── system-architecture.png
│   ├── deployment-architecture.png
│   ├── backend-layers.png
│   └── database-er.png
├── client/                  # Vue3 frontend
├── server/
│   ├── main.py              # FastAPI entry
│   ├── sql/db_plant_diseases.sql
│   └── app/
│       ├── api/             # Endpoints
│       ├── core/            # Config & JWT
│       ├── db/              # Session
│       ├── models/          # ORM
│       ├── schemas/         # Input models
│       ├── service/         # YOLO / alarm / file
│       └── utils/
└── train_project/           # YOLO26 offline training
    ├── plantdiseases.yaml
    ├── plantdiseases_train.py
    ├── plantdiseases_predict.py
    └── best.pt

Design Highlights

Detection paradigm : leaf pest/disease uses YOLO object detection (class, confidence, bounding box) not whole-image classification.

Training/inference separation : train_project only produces weights; production uploads .pt via model management, yolo_service caches for inference.

Alert & knowledge base decoupled : knowledge base covers all 30 classes; alert rules only for diseases needing warnings, thresholds tunable per severity (e.g., late blight lower threshold for early detection).

Three detection channels : image (sync), video (async), realtime (WebSocket) – all persist as record + detail + alert.

Clear permission boundaries : admin owns user management, alert rules, system logs; regular users access detection, records, knowledge base, statistics, profile.

Data layer conventions : db_ prefix for database, t_ for tables; no FOREIGN KEYs for easy test data import; passwords stored plaintext per project convention (demo only).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Computer VisionMySQLWebSocketFastAPIVue3Full-Stack DevelopmentYOLO26Crop Disease Detection
java1234
Written by

java1234

Former senior programmer at a Fortune Global 500 company, dedicated to sharing Java expertise. Visit Feng's site: Java Knowledge Sharing, www.java1234.com

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.