Skip to content

Repository files navigation

🌿 Plant Disease Detection System

Python TensorFlow Keras Streamlit FastAPI

NumPy Pandas scikit--learn Matplotlib Seaborn Pillow OpenCV

License Accuracy Status Permission Required

An AI-powered plant disease detection system using deep learning to identify 38 different plant diseases with 98.55% accuracy.

Model Accuracy

πŸ“Š Project Overview

This project implements a deep learning model based on MobileNetV2 architecture to detect and classify plant diseases from leaf images. The system can identify diseases across 14 different plant species with high accuracy.

Key Features

  • βœ… 98.55% Classification Accuracy
  • βœ… 99.89% Top-3 Accuracy
  • βœ… 38 Disease Classes across 14 plant species
  • βœ… Real-time Detection (<2 seconds per image)
  • βœ… Web-based UI using Streamlit
  • βœ… REST API for integration

🎯 Supported Plants & Diseases

The model can detect diseases in the following crops:

Crop Number of Classes Diseases Detected
πŸ… Tomato 10 Bacterial Spot, Early Blight, Late Blight, Leaf Mold, Septoria Leaf Spot, Spider Mites, Target Spot, Mosaic Virus, Yellow Leaf Curl Virus, Healthy
πŸ₯” Potato 3 Early Blight, Late Blight, Healthy
🍎 Apple 4 Black Rot, Apple Scab, Cedar Rust, Healthy
πŸ‡ Grape 4 Black Rot, Esca (Black Measles), Leaf Blight, Healthy
🌽 Corn/Maize 4 Cercospora Leaf Spot, Common Rust, Northern Leaf Blight, Healthy
🌢️ Pepper (Bell) 2 Bacterial Spot, Healthy
πŸ’ Cherry 2 Powdery Mildew, Healthy
πŸ‘ Peach 2 Bacterial Spot, Healthy
πŸ“ Strawberry 2 Leaf Scorch, Healthy
🍊 Orange 1 Huanglongbing (Citrus Greening)
πŸŽƒ Squash 1 Powdery Mildew
🫐 Blueberry 1 Healthy
πŸ«› Raspberry 1 Healthy
🫘 Soybean 1 Healthy

Total: 38 Classes

πŸ“ Dataset Information

PlantVillage Dataset

  • Total Images: 54,305
  • Image Resolution: 224Γ—224 pixels (resized)
  • Format: JPG
  • Classes: 38 disease categories

Data Split

Split Images Percentage
Training 37,985 70%
Validation 8,158 15%
Test 8,162 15%

Directory Structure

data/
β”œβ”€β”€ sample_test_images/    # 76 sample images (2 per class) - included in repo
β”œβ”€β”€ processed/             # Full dataset (not in repo - download separately)
β”‚   β”œβ”€β”€ train/            # 37,985 images
β”‚   β”œβ”€β”€ val/              # 8,158 images
β”‚   └── test/             # 8,162 images
└── raw/                   # Original PlantVillage dataset

πŸ“¦ Sample Data in Repository
This repository includes data/sample_test_images/ with 76 sample images (2 per class) for quick testing and demonstration purposes.

πŸ“₯ Full Dataset Download
The complete PlantVillage dataset (1.8GB, 54,305 images) is not included in this repository due to GitHub's file size limitations. To download the full dataset, run:

python download_dataset.py

This will download and organize the complete training, validation, and test datasets.

πŸ—οΈ Model Architecture

Base Model

  • Architecture: MobileNetV2
  • Technique: Transfer Learning + Fine-tuning
  • Input Size: 224Γ—224Γ—3
  • Output: 38 classes (softmax)
  • Parameters: ~3.5M
  • Model Size: 25 MB

Training Configuration

Parameter Value
Base Learning Rate 0.0001
Optimizer Adam
Loss Function Categorical Crossentropy
Batch Size 32
Initial Epochs 20
Fine-tuning Epochs 10
Total Training Time ~7 hours

Data Augmentation

  • Random rotation (Β±20Β°)
  • Width/Height shift (Β±0.1)
  • Horizontal flip
  • Zoom (Β±0.1)
  • Fill mode: nearest

πŸ“ˆ Performance Metrics

Overall Performance

Metric Score
Validation Accuracy 98.55%
Top-3 Accuracy 99.89%
Training Accuracy 99.01%
Test Accuracy 94.88%

Performance by Class Tier

Tier Accuracy Range Number of Classes
Perfect 100% 6 classes
Excellent 95-99% 23 classes
Good 85-95% 7 classes
Fair <85% 2 classes

Per-Class Accuracy

Rank Class Accuracy Correct Total
1 Apple - Black Rot 100.00% 93 93
2 Peach - Healthy 100.00% 54 54
3 Orange - Huanglongbing 100.00% 826 826
4 Grape - Healthy 100.00% 64 64
5 Grape - Leaf Blight 100.00% 162 162
6 Squash - Powdery Mildew 100.00% 276 276
7 Soybean - Healthy 99.48% 760 764
8 Corn - Common Rust 99.44% 178 179
9 Corn - Healthy 99.43% 174 175
10 Cherry - Healthy 99.22% 127 128
11 Peach - Bacterial Spot 99.13% 342 345
12 Strawberry - Leaf Scorch 98.80% 165 167
13 Raspberry - Healthy 98.21% 55 56
14 Cherry - Powdery Mildew 98.10% 155 158
15 Grape - Esca (Black Measles) 98.08% 204 208
16 Apple - Healthy 97.98% 242 247
17 Tomato - Bacterial Spot 97.81% 312 319
18 Tomato - Yellow Leaf Curl Virus 97.26% 782 804
19 Strawberry - Healthy 97.10% 67 69
20 Pepper Bell - Bacterial Spot 96.00% 144 150
21 Pepper Bell - Healthy 95.95% 213 222
22 Tomato - Healthy 95.82% 229 239
23 Apple - Cedar Apple Rust 95.24% 40 42
24 Grape - Black Rot 94.92% 168 177
25 Apple - Apple Scab 94.74% 90 95
26 Blueberry - Healthy 93.36% 211 226
27 Potato - Early Blight 92.67% 139 150
28 Tomato - Late Blight 91.64% 263 287
29 Corn - Cercospora Leaf Spot 89.61% 69 77
30 Potato - Late Blight 89.33% 134 150
31 Tomato - Mosaic Virus 89.29% 50 56
32 Tomato - Leaf Mold 88.81% 127 143
33 Corn - Northern Leaf Blight 85.14% 126 148
34 Tomato - Septoria Leaf Spot 84.59% 225 266
35 Tomato - Spider Mites 78.57% 198 252
36 Tomato - Target Spot 78.20% 165 211
37 Tomato - Early Blight 64.67% 97 150
38 Potato - Healthy 60.87% 14 23

Best Performing: Apple - Black Rot (100%)
Needs Improvement: Potato - Healthy (60.87% - limited samples)

Analysis of Lower-Performing Classes

Understanding why certain classes have lower accuracy helps improve future iterations:

1. Potato - Healthy (60.87%)

  • Primary Issue: Severe class imbalance
  • Sample Size: Only 23 test images (smallest in dataset)
  • Confusion: Often misclassified as Potato Early Blight or Late Blight
  • Reason: Healthy potato leaves can show early signs of stress that resemble disease onset
  • Recommendation: Needs more training samples for robust performance

2. Tomato - Early Blight (64.67%)

  • Visual Similarity: Early Blight symptoms (concentric rings) overlap with Late Blight and Septoria Leaf Spot
  • Disease Progression: Different stages of Early Blight look significantly different
  • Multiple Lesion Types: Can present as small spots or large necrotic areas
  • Confusion Matrix: Often confused with Tomato Late Blight and Septoria Leaf Spot
  • Challenge: Requires fine-grained feature discrimination

3. Tomato - Target Spot (78.20%)

  • Symptom Similarity: Circular lesions similar to Early Blight and Bacterial Spot
  • Variable Appearance: Lesions vary greatly in size and color development
  • Limited Dataset: Fewer distinct visual patterns compared to other classes
  • Background Noise: Often occurs with other diseases simultaneously

4. Tomato - Spider Mites (78.57%)

  • Subtle Symptoms: Early damage appears as tiny white/yellow stippling
  • Not Directly Visible: Actual mites not visible in leaf images
  • Progressive Damage: Early, mid, and late-stage damage look completely different
  • Confusion: Resembles nutrient deficiency or environmental stress
  • Special Case: Pest damage rather than disease, requires different visual cues

5. Tomato - Septoria Leaf Spot (84.59%)

  • Small Lesions: Numerous tiny circular spots can blend together
  • Similar Patterns: Overlaps with Bacterial Spot and Leaf Mold symptoms
  • Variable Stages: Early small spots vs. late coalescent lesions differ greatly

6. Corn - Northern Leaf Blight (85.14%)

  • Elongated Lesions: Long cigar-shaped lesions can vary in size (1-6 inches)
  • Color Variation: Gray-green to tan coloring overlaps with other corn diseases
  • Confusion: Often mistaken for Cercospora Leaf Spot due to similar lesion shapes

Common Factors Affecting Accuracy

  1. Class Imbalance

    • Classes with <50 test samples show reduced performance
    • Potato Healthy (23), Tomato Mosaic Virus (56) have limited data
  2. Visual Similarity

    • Tomato diseases share many overlapping symptoms
    • Spot-like lesions across multiple classes create confusion
  3. Disease Progression

    • Early vs. late stage symptoms look dramatically different
    • Model trained on mixed stages may struggle with edge cases
  4. Dataset Characteristics

    • PlantVillage images are lab-controlled
    • Real-world field conditions may introduce more variation
  5. Multi-Disease Presence

    • Some images may show early signs of multiple diseases
    • Healthy classifications most challenging due to subtle stress indicators

Improvement Strategies

To address these limitations:

  • Collect more samples for underrepresented classes (especially Potato Healthy)
  • Implement focal loss to handle class imbalance
  • Add disease progression-aware augmentation
  • Use ensemble methods for similar-looking diseases
  • Implement hierarchical classification (plant β†’ health status β†’ specific disease)

πŸš€ Getting Started

Prerequisites

Python 3.8+
TensorFlow 2.x
Streamlit

Installation

  1. Clone the repository
git clone https://github.com/Faheem8585/plant_disease_detection.git
cd plant-disease-detection
  1. Install dependencies
pip install -r requirements.txt
  1. Download the dataset (optional)
python download_dataset.py

Usage

Web Interface (Streamlit)

streamlit run ui/app.py

Then open http://localhost:8501 in your browser.

API Server

uvicorn api.main:app --reload

API will be available at http://localhost:8000

Quick Test

python quick_test.py

πŸ’» Project Structure

plant-disease-detection/
β”œβ”€β”€ api/                    # FastAPI REST API
β”‚   β”œβ”€β”€ main.py
β”‚   └── routes.py
β”œβ”€β”€ configs/                # Configuration files
β”‚   β”œβ”€β”€ model_config.yaml
β”‚   β”œβ”€β”€ preprocessing_config.yaml
β”‚   └── training_config.yaml
β”œβ”€β”€ data/                   # Dataset directory
β”‚   β”œβ”€β”€ processed/         # Processed train/val/test splits
β”‚   └── raw/               # Raw PlantVillage dataset
β”œβ”€β”€ logs/                   # Training logs
β”œβ”€β”€ models/                 # Saved models
β”‚   └── pretrained_replacement.h5  # Best model (98.55%)
β”œβ”€β”€ notebooks/              # Jupyter notebooks for experiments
β”œβ”€β”€ results/                # Training results and visualizations
β”œβ”€β”€ src/                    # Source code
β”‚   β”œβ”€β”€ data/              # Data loading and preprocessing
β”‚   β”œβ”€β”€ inference/         # Model inference
β”‚   β”œβ”€β”€ models/            # Model architectures
β”‚   β”œβ”€β”€ training/          # Training scripts
β”‚   └── utils/             # Utility functions
β”œβ”€β”€ tests/                  # Unit tests
β”œβ”€β”€ ui/                     # Streamlit web interface
β”‚   └── app.py
β”œβ”€β”€ analyze_per_class.py    # Per-class accuracy analysis
β”œβ”€β”€ download_dataset.py     # Dataset downloader
β”œβ”€β”€ quick_start.py          # Quick start training script
β”œβ”€β”€ quick_test.py          # Quick inference test
β”œβ”€β”€ train_better_model.py  # Main training script
β”œβ”€β”€ visualize_predictions.py  # Prediction visualizer
β”œβ”€β”€ requirements.txt        # Python dependencies
└── README.md              # This file

πŸ”§ Training Your Own Model

python train_better_model.py

Training parameters can be adjusted in configs/training_config.yaml.

πŸ“Š Results Visualization

View training history and predictions:

python visualize_predictions.py

Analyze per-class performance:

python analyze_per_class.py

🌐 Web Interface Features

  • Image Upload: Drag & drop or browse for plant leaf images
  • Real-time Prediction: Get results in <2 seconds
  • Confidence Scores: See prediction confidence and top-3 alternatives
  • Treatment Recommendations: Basic guidance for detected diseases
  • Responsive Design: Works on desktop and mobile devices

πŸ”¬ API Endpoints

POST /predict

Upload an image and get disease prediction.

Request:

{
  "image": "<base64_encoded_image>"
}

Response:

{
  "crop": "Tomato",
  "disease": "Early Blight",
  "confidence": 0.97,
  "top_predictions": [...]
}

⚠️ Limitations

  • Best performance on clear, well-lit leaf images
  • Trained on PlantVillage dataset (controlled conditions)
  • May have reduced accuracy on field images with:
    • Multiple diseases present
    • Environmental damage
    • Poor lighting or unusual angles
  • Not a replacement for professional diagnosis
  • Use as initial screening tool only

πŸ“ Citation

If you use this project, please cite the PlantVillage dataset:

Hughes, D.P. and Salathe, M. (2015). 
"An open access repository of images on plant health to enable the 
development of mobile disease diagnostics." 
arXiv preprint arXiv:1511.08060.

πŸ“œ Usage & Permissions

Using This Code

⚠️ Permission Required
If you wish to use, modify, or redistribute this code or trained model, you must:

  1. Request Permission: Contact the author for explicit permission before use
  2. Provide Attribution: Cite this work in your project, paper, or application
  3. Acknowledge Source: Include a clear reference to this repository

How to Cite This Work

If you use this code or model in your research or project, please cite as:

@software{plant_disease_detection_2024,
  author = {Faheem},
  title = {Plant Disease Detection System using Deep Learning},
  year = {2024},
  url = {https://github.com/Faheem8585/plant_disease_detection},
  note = {MobileNetV2-based transfer learning model achieving 98.55% accuracy on 38 plant disease classes}
}

Or in text format:

Faheem (2024). Plant Disease Detection System using Deep Learning. 
GitHub repository: https://github.com/Faheem8585/plant_disease_detection

Contact for Permission

For permission requests or collaborations, please open an issue on this repository or contact via GitHub.

Educational Use

This project is available for:

  • βœ… Learning and education (with proper citation)
  • βœ… Academic research (with permission and citation)
  • βœ… Personal projects (with attribution)
  • ❌ Commercial use (requires explicit written permission)

πŸ“„ License

This project is licensed under a custom license requiring permission and attribution. While the code is publicly available, you must:

  • Obtain permission before use
  • Provide proper citation and acknowledgment
  • Not use commercially without explicit permission

See the repository for full terms.

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Submit a pull request

For major changes, please open an issue first to discuss proposed changes.

πŸ“§ Contact

For questions, permission requests, or feedback:


Note: This system is designed for educational and research purposes. Always consult with agricultural professionals for treatment decisions.

Β© 2024 Faheem. All rights reserved.

About

🌿 AI-powered plant disease detection system using MobileNetV2 transfer learning. Detects 38 plant diseases across 14 crops with 98.55% accuracy. Built with TensorFlow, Keras, and Streamlit. Includes trained model, sample dataset, and web interface.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages