HomeCase studiesComputer Vision Crop Disease Detection Pipeline with...

Case study · Wageningen, Netherlands

Computer Vision Crop Disease Detection Pipeline with PyTorch, OpenCV, and Edge-Ready Python Services

Computer Vision Plant Pathology

Early fungal outbreaks and nutrient deficiencies look nearly identical to the naked eye during initial leaf spotting, yet misdiagnosis wastes fungicide sprays or forfeits entire greenhouse blocks. We engineered an AI crop disease detection platform in Wageningen powered by Python, PyTorch, and OpenCV across mobile scouting clients and a web pathology review portal. The system segments leaf lesions under harsh field lighting, runs calibrated multi-class classification with uncertainty rejection, and routes borderline cases to plant pathologists for active-learning relabeling.

Industry
Computer Vision Plant Pathology
Solution
A cross-platform leaf-scouting application, pathologist review workbench, and Python/PyTorch/OpenCV vision inference pipeline delivering calibrated crop disease diagnostics.
Platforms
Web & API · Cross-platform
Stack
Python · PyTorch · OpenCV · ONNX Runtime · FastAPI · React
Location
Wageningen, Netherlands · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in Wageningen, Netherlands. Names withheld by agreement.

Project Overview

In intensive horticulture and high-value arable production, a forty-eight-hour delay between initial foliar spotting and accurate pathogen identification determines whether a spot treatment contains an infection or an entire crop block requires eradication. Visual scouting guides help, yet early fungal sporulation, bacterial leaf spot, viral mottling, and micronutrient burn share overlapping chlorotic halos that routinely mislead even experienced growers.

Developed for plant pathology teams in Wageningen, this platform pairs a cross-platform mobile capture app with a PyTorch and OpenCV diagnostic engine and a React pathologist review workbench. Rather than returning opaque top-1 guesses, the system enforces image quality at capture time, segments symptomatic leaf tissue, reports calibrated confidence intervals, and escalates ambiguous specimens directly into human expert review.

Why Lab Vision Models Fail Outdoors

Academic plant-disease classifiers trained on clean, single-leaf white-background datasets degrade sharply the moment scouts carry them into working fields and glasshouses:

  • Cluttered backgrounds and harsh shadows: Soil clods, drip tape, canopy shade, and specular glare off wet foliage mislead naive whole-frame classifiers into memorizing background textures instead of lesion morphology.
  • Overconfident false positives: Standard softmax layers assign high probability even when presented with unknown pests, hail damage, or spray burn outside the training taxonomy.
  • Unusable field uploads: Motion blur from wind-blown leaves and out-of-focus macro shots waste cellular bandwidth and poison automated disease-mapping logs.
  • Dataset leakage across cultivars: Random image splits allow near-identical leaves from the same plant to appear in both training and test sets, masking brittle generalization across new varieties or regions.

Architectural Strategy

We built the platform as a closed-loop diagnostic pipeline rather than a static inference endpoint. OpenCV acts as a strict visual gatekeeper both on-device and in Python API workers, rejecting unusable frames and extracting normalized leaf regions of interest before PyTorch ever scores a pixel.

To maintain scientific accountability, PyTorch training and ONNX Runtime deployment are coupled to PostgreSQL dataset-lineage tables. Every prediction links immutably to the exact model checksum, calibration temperature, and segmentation mask version, enabling plant pathologists in React to audit Grad-CAM attribution maps and convert edge-case misses into clean retraining samples.

Core Capabilities

  • Guided Mobile & Tablet Leaf Capture: Real-time OpenCV sharpness, exposure, and leaf-centering indicators ensure usable macro photos on the first capture, with offline ONNX triage inside dead-zone greenhouses.
  • Multi-Task Lesion Segmentation & Classification: Jointly segments necrotic, chlorotic, and sporulating zones while scoring cultivar-specific fungal, bacterial, and viral classes.
  • Calibrated Uncertainty & Differential Diagnosis: Surfaces top candidate pathologies with calibrated confidence bands plus visual differential comparisons when symptoms overlap.
  • Pathologist Workbench & Grad-CAM Inspection: React interface lets specialists scrub saliency overlays, inspect parcel weather context, override labels, and push confirmed ground truth to training queues.
  • Spatial Outbreak Heatmaps: Aggregates verified diagnoses over PostGIS parcel coordinates to expose spreading disease fronts across rows or bays.

Technical Architecture

Scouts capture leaf photos through the cross-platform app, where a lightweight OpenCV preflight check verifies focus and framing before running local quantized ONNX inference for immediate field guidance. Once connected, lossless leaf crops and parcel metadata stream to the Python FastAPI backend.

Flow: Cross-Platform Field App (OpenCV Preflight + ONNX) → FastAPI Diagnostic API → OpenCV Background Suppression & Color Calibration → PyTorch Multi-Task Inference → PostgreSQL & Object Storage → React Pathologist Workbench

Asynchronous Celery workers handle heavy diagnostic tasks—computing Grad-CAM heatmaps, generating lesion-area percentages, and storing versioned thumbnails. Predictions falling below calibrated entropy thresholds automatically enqueue in the React review inbox so human pathologists resolve edge cases before treatment advisories finalize.

Technology Stack

Category Technology detail
Model Training & Architecture PyTorch (ConvNeXt & SegFormer multi-task pathology backbones)
Image Preprocessing & Vision OpenCV (blur rejection, specular glare masking, HSV leaf segmentation)
Cross-Platform Edge Runtime ONNX Runtime quantized FP16/INT8 bundles for field tablets
Inference & Review API Python FastAPI asynchronous REST & batch diagnostic endpoints
Pathologist Workbench UI React & TypeScript web portal with Grad-CAM heatmap overlays
Field Capture Client Cross-platform mobile app with real-time OpenCV framing guidance
Metadata & Annotation Store PostgreSQL with PostGIS parcel coordinates and label lineage tables
Artifact & Dataset Storage S3-compatible object storage with versioned Parquet manifest splits
Task & Retraining Queue Celery with Redis for batch high-res microscopy and model evaluation

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
High-resolution smartphone photos saturate mobile uploads in rural fields Run OpenCV lesion-region cropping and smart JPEG compression client-side while preserving native resolution strictly for the segmented leaf ROI; trades full-canopy context for fast, reliable synchronization.
Single giant vision transformers run too slowly on mid-range field tablets Split workloads between a distilled MobileNet/ConvNeXt ONNX bundle on-device for instant triage and full SegFormer/ConvNeXt ensembles server-side when connectivity permits.
Softmax scores overstate certainty on novel pathogens or herbicide drift Applied temperature scaling and energy-based out-of-distribution scoring in PyTorch; forces explicit "Expert Review Required" routing rather than risking hazardous misdiagnosis.
Pathologist labels take days during peak summer blight outbreaks Implemented confidence-weighted active sampling in PostgreSQL so specialists label high-disagreement clusters first instead of reviewing redundant high-certainty submissions.

Security & Reliability

Crop health records reveal proprietary genetics, yield vulnerabilities, and phytosanitary status across commercial breeding stations. FastAPI endpoints enforce tenant-scoped OAuth2 tokens and signed short-lived object URLs so raw field photos never sit behind public bucket paths. Image ingest sanitizes EXIF payloads while preserving explicit GPS parcel tokens authorized by the grower.

For model reliability, automated CI gates evaluate every candidate PyTorch checkpoint against locked cultivar-holdout benchmarks and synthetic lighting perturbations before promoting new ONNX artifacts. Production servers maintain warm previous-version model slots for instant rollback if calibration drift appears in live telemetry.

Performance & Scale

During spring emergence and humid late-blight windows, field teams submit bursts of multi-leaf inspections across entire estates. FastAPI services run batched GPU/CPU inference workers backed by ONNX Runtime execution providers, keeping tail response latencies predictable without spawning redundant Python processes per image.

In the React pathology workbench, large inspection galleries stream paginated pre-rendered lesion crops and vector contour overlays rather than raw multi-megabyte originals, keeping annotation triage smooth across thousands of weekly submissions.

Operational Outcomes

Integrating OpenCV quality gates, calibrated PyTorch inference, and human pathologist escalation established a trustworthy diagnostic workflow for growers and researchers:

  • Higher first-pass capture quality: Real-time focus and glare feedback eliminates unusable field photos before scouts walk away from suspect plants.
  • Safer treatment decisions: Explicit uncertainty thresholds and differential pathology cards prevent blind fungicide applications against abiotic nutrient or weather injury.
  • Transparent model accountability: Visual Grad-CAM overlays allow agronomists to verify that classifications rest on genuine lesion traits rather than soil or lighting artifacts.
  • Continuous regional adaptation: Verified pathologist corrections flow cleanly into group-isolated retraining datasets, keeping accuracy aligned with emerging pathogen strains.

01 — Questions

asked about this kind of project

How does the pipeline prevent field lighting, soil backgrounds, and motion blur from ruining PyTorch predictions?

Before inference ever runs, an OpenCV quality gate evaluates Laplacian variance for focus, detects blown-out specular highlights from wet leaves, and isolates the foreground leaf mask from cluttered soil or greenhouse benches. Blurry or poorly framed shots prompt the scout to retake immediately rather than guessing.

How do you handle visually similar abiotic stress—such as magnesium deficiency versus early blight?

Our PyTorch classification head outputs temperature-scaled calibrated probabilities alongside a dedicated 'uncertain / escalate' threshold. In addition, the FastAPI endpoint fuses leaf imagery with contextual crop metadata—growth stage, cultivar, and recent humidity—to separate nutritional disorders from infectious lesions.

Why export PyTorch models to ONNX Runtime instead of running full PyTorch on mobile or edge servers?

Quantized ONNX Runtime graphs eliminate Python interpreter overhead on cross-platform scouting tablets and cut server inference memory significantly. Scouts receive preliminary triage results offline inside greenhouses while full-resolution crops upload later for pathologist verification.

How can agronomists verify whether the neural network looked at the actual lesion instead of a background artifact?

Every server-analyzed submission computes a compact Grad-CAM saliency overlay stored alongside the diagnostic record in React. Pathologists inspect highlighted necrotic margins directly over the original leaf image before signing off on treatment recommendations.

How does the system avoid overfitting to lab-studio leaf photos that fail in real fields?

Training splits are strictly grouped by farm, greenhouse block, and capture session in PostgreSQL manifests so identical lighting conditions never leak between train and validation sets. Active-learning queues continuously feed real field failures back into curated retraining cycles.

What safeguards prevent unauthorized distribution of proprietary seed-breeding pathology datasets?

Uploaded leaf imagery strips EXIF camera serials while retaining controlled parcel tokens, encrypts raw frames at rest in scoped buckets, and enforces tenant-isolated dataset policies across annotation queues.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.