Lesson 4 of 12
Plant Disease Detector
Build a plant disease detector using transfer learning — a practical application of CNNs that combines Computer Vision with agriculture.
Plant Disease Detection System
Plant Disease Detection System
import torch
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
import json
import os
class PlantDiseaseDetector:
"""
Detects plant diseases from leaf images using transfer learning.
Can be trained on the PlantVillage dataset (38 classes:
14 crop species × healthy and diseased variants).
"""
# Common PlantVillage classes (subset)
CLASSES = [
"Apple___Apple_scab",
"Apple___Black_rot",
"Apple___Cedar_apple_rust",
"Apple___healthy",
"Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot",
"Corn_(maize)___Common_rust_",
"Corn_(maize)___Northern_Leaf_Blight",
"Corn_(maize)___healthy",
"Tomato___Bacterial_spot",
"Tomato___Early_blight",
"Tomato___Late_blight",
"Tomato___healthy",
]
def __init__(self, model_path=None, num_classes=None):
self.num_classes = num_classes or len(self.CLASSES)
# Build model
self.model = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)
self.model.fc = torch.nn.Linear(self.model.fc.in_features, self.num_classes)
if model_path and os.path.exists(model_path):
self.model.load_state_dict(torch.load(model_path, map_location="cpu"))
print(f"Loaded model from: {model_path}")
else:
print("Using random weights — train before predicting")
self.model.eval()
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model = self.model.to(self.device)
# Preprocessing
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
def predict(self, image_path, top_k=3):
"""Predict the disease class for a leaf image."""
image = Image.open(image_path).convert("RGB")
tensor = self.transform(image).unsqueeze(0).to(self.device)
with torch.no_grad():
output = self.model(tensor)
probs = torch.nn.functional.softmax(output[0], dim=0)
top_probs, top_indices = torch.topk(probs, top_k)
results = []
for prob, idx in zip(top_probs, top_indices):
cls_name = self.CLASSES[idx.item()] if idx.item() < len(self.CLASSES) else f"Class {idx.item()}"
cls_clean = cls_name.replace("_", " ").replace(" ", " ")
results.append({
"class": cls_clean,
"confidence": prob.item(),
"healthy": "healthy" in cls_name.lower(),
})
print(f"\n=== Plant Disease Detection: {image_path} ===")
for i, r in enumerate(results):
status = "✓ HEALTHY" if r["healthy"] else "⚠ DISEASED"
print(f" #{i+1}: {r['class']}")
print(f" Confidence: {r['confidence']:.1%} | {status}")
top = results[0]
if top["healthy"]:
print("\nDiagnosis: Plant appears HEALTHY")
else:
print(f"\nDiagnosis: DISEASE DETECTED — {top['class']}")
print("Recommendation: Consult with an agricultural expert for treatment")
return results
def batch_predict(self, image_dir):
"""Predict for all images in a directory."""
from pathlib import Path
images = list(Path(image_dir).glob("*.jpg")) + list(Path(image_dir).glob("*.png"))
print(f"Processing {len(images)} images in {image_dir}")
summary = {"healthy": 0, "diseased": 0, "predictions": []}
for img_path in images:
preds = self.predict(str(img_path), top_k=1)
if preds:
if preds[0]["healthy"]:
summary["healthy"] += 1
else:
summary["diseased"] += 1
summary["predictions"].append({
"image": img_path.name,
"prediction": preds[0]["class"],
"confidence": preds[0]["confidence"],
})
print(f"\n=== Batch Analysis ===")
print(f"Healthy: {summary['healthy']} | Diseased: {summary['diseased']}")
return summary
# Example usage
detector = PlantDiseaseDetector() # Would load a trained model
# detector.predict("tomato_leaf.jpg")
print("Plant disease detector initialised")
print("Train with PlantVillage dataset (38 classes, 54K images) for real predictions")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment
Finished this lesson?
0 of 12 in Module 12