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.