Agriculture plays an important role in food production, but crops can be affected by fungal infections, bacterial diseases, and other plant health problems. Identifying symptoms early can help farmers investigate problems and take appropriate action. However, manually inspecting every plant can be difficult, especially when a farm contains a large number of crops.
Artificial intelligence and computer vision offer an interesting way to study this problem. A machine-learning model can analyse photographs of plant leaves and classify them into categories it has learned during training.
In this project, you will develop a Crop Disease Detection System Using Convolutional Neural Networks (CNN) with Python and TensorFlow. The application accepts a leaf image, processes it using a trained model, and displays the predicted crop or disease category.
1. Project Overview
The Crop Disease Detection System is an image-classification application designed to recognise selected healthy and diseased plant-leaf categories. It uses a CNN to learn visual patterns such as colour differences, spots, leaf texture, and other features represented in the training images.
For example, a model trained on tomato leaf images may learn to distinguish between the healthy and disease categories included in its dataset. When a user uploads a new image, the model predicts the most likely category among its trained classes.
2. Project Objectives
- Collect and prepare a labelled plant-leaf image dataset.
- Understand image preprocessing and classification.
- Build a CNN-based image classification model.
- Train the model using labelled leaf images.
- Evaluate model performance on unseen test images.
- Develop a simple interface for uploading leaf photographs.
- Display predicted categories and confidence scores.
- Study the limitations of using controlled datasets in real-world conditions.
3. Technologies Required
| Technology | Purpose |
|---|---|
| Python | Main programming language |
| TensorFlow / Keras | Building and training the CNN model |
| NumPy | Numerical operations |
| Matplotlib | Displaying images and training graphs |
| Pillow | Loading and processing images |
| Scikit-learn | Evaluation metrics and confusion matrix |
| Streamlit | Creating the web application interface |
You can use Google Colab or a local Python environment for model training. A GPU can make training faster, particularly when using larger image datasets.
4. Dataset for Crop Disease Detection
A labelled image dataset is required to train the model. One commonly used research dataset is PlantVillage, which contains images of healthy and diseased leaves from multiple crop species.
Published research describes PlantVillage as containing more than 54,000 images across 14 crop species and 38 healthy or diseased categories. It is useful for building an educational image-classification prototype.
Where to obtain the dataset
You can explore the following resources:
- PlantVillage Dataset on GitHub
- TensorFlow Image Classification Tutorial
- TensorFlow Transfer Learning Tutorial
Dataset folder structure
Organise the images into separate folders, with each folder representing one class. For example:
PlantVillage/├── Tomato___healthy/├── Tomato___Early_blight/├── Tomato___Late_blight/├── Potato___healthy/├── Potato___Early_blight/└── Potato___Late_blight/
This is an illustrative subset of possible classes. Your actual folder names and number of categories should match the dataset you download.
Before training, inspect the dataset to check for missing images, incorrect labels, duplicate photographs, and class imbalance. Keep the test data separate from the training process.
5. How the Crop Disease Detection System Works
The application follows an image-classification workflow:
- Image upload: The user selects a photograph of a plant leaf.
- Image preprocessing: The photograph is resized to the input dimensions required by the model.
- Pixel normalisation: Pixel values are scaled according to the model’s preprocessing requirements.
- Feature extraction: CNN layers learn visual features from the image.
- Classification: The final classification layer calculates scores for the trained categories.
- Prediction: The application identifies the category with the highest predicted score.
- Result display: The predicted label and confidence information are shown to the user.
Input: A photograph of a tomato leaf
Processing: Image resizing and normalisation
Model: Trained CNN image classifier
Output: Predicted category from the model’s supported classes
Additional information: Model confidence score and an advisory message to verify the result.
6. Understanding CNN for Crop Disease Detection
A Convolutional Neural Network is a deep-learning architecture commonly used for image classification. It learns visual patterns directly from image data instead of requiring every feature to be manually designed.
A basic CNN contains several types of layers:
Convolutional layer
Applies filters to an image to learn visual patterns such as edges, shapes, and textures.
Activation layer
Introduces non-linearity into the model. ReLU is a commonly used activation function in hidden CNN layers.
Pooling layer
Reduces the spatial dimensions of feature maps and helps make the representation more compact.
Flatten or global pooling layer
Converts extracted image features into a representation that can be used by the classification layers.
Dense classification layer
Uses the extracted features to produce scores for the available disease or healthy categories.
For a multiclass classification task, a softmax output is commonly used to produce a distribution of class scores.
7. Suggested Project Folder Structure
crop-disease-detection/├── app.py├── train_model.py├── predict.py├── preprocessing.py├── models/│ └── crop_disease_model.keras├── dataset/│ ├── train/│ ├── validation/│ └── test/├── class_names.json├── requirements.txt└── README.md
This structure separates model training, image preprocessing, prediction, and the user interface. You can adjust the folder arrangement according to your implementation.
8. Install the Required Python Libraries
Create a virtual environment and install the required packages.
pip install tensorflow numpy matplotlib pillow scikit-learn streamlit
Keep track of the package versions used in your working environment. This makes it easier to reproduce the project on another computer.
9. Build and Train the CNN Model
The following is a basic TensorFlow/Keras example. It assumes your dataset has already been organised into class-specific folders. The code creates training, validation, and test datasets, trains a CNN, and saves the model and class names.
Example training code
import json
import tensorflow as tf
from tensorflow.keras import layers, models
DATA_DIR = "dataset"
IMAGE_SIZE = (128, 128)
BATCH_SIZE = 32
SEED = 42
train_ds = tf.keras.utils.image_dataset_from_directory(
DATA_DIR,
validation_split=0.30,
subset="training",
seed=SEED,
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE
)
remaining_ds = tf.keras.utils.image_dataset_from_directory(
DATA_DIR,
validation_split=0.30,
subset="validation",
seed=SEED,
image_size=IMAGE_SIZE,
batch_size=BATCH_SIZE
)
class_names = train_ds.class_names
# Split the remaining data into validation and test sets.
val_batches = tf.data.experimental.cardinality(
remaining_ds
)
test_ds = remaining_ds.take(val_batches // 2)
val_ds = remaining_ds.skip(val_batches // 2)
AUTOTUNE = tf.data.AUTOTUNE
train_ds = train_ds.prefetch(AUTOTUNE)
val_ds = val_ds.prefetch(AUTOTUNE)
test_ds = test_ds.prefetch(AUTOTUNE)
num_classes = len(class_names)
data_augmentation = models.Sequential([
layers.RandomFlip("horizontal"),
layers.RandomRotation(0.1),
layers.RandomZoom(0.1)
])
model = models.Sequential([
layers.Input(shape=(128, 128, 3)),
data_augmentation,
layers.Rescaling(1.0 / 255),
layers.Conv2D(
32, 3, activation="relu"
),
layers.MaxPooling2D(),
layers.Conv2D(
64, 3, activation="relu"
),
layers.MaxPooling2D(),
layers.Conv2D(
128, 3, activation="relu"
),
layers.MaxPooling2D(),
layers.GlobalAveragePooling2D(),
layers.Dense(128, activation="relu"),
layers.Dropout(0.3),
layers.Dense(num_classes, activation="softmax")
])
model.compile(
optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=3,
restore_best_weights=True
)
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=20,
callbacks=[early_stopping]
)
model.evaluate(test_ds)
model.save("crop_disease_model.keras")
with open("class_names.json", "w") as file:
json.dump(class_names, file)
print("Model training and saving completed.")
This is a baseline implementation, not a guaranteed high-accuracy model. The example uses a random split of images. If the dataset contains multiple images of the same plant or recording session, use a grouped split where possible to reduce data leakage.
10. Improve Performance Using Transfer Learning
Training a CNN from scratch can require a large amount of labelled data and computing resources. Transfer learning offers another approach: start with a model that has already learned general image features and adapt it to your plant-leaf categories.
MobileNetV2 is one possible pretrained architecture to explore. It can be useful for student projects where training resources are limited.
A typical transfer-learning workflow is:
- Load a pretrained MobileNetV2 model without its original classification head.
- Freeze the pretrained feature-extraction layers initially.
- Add a new classification head matching your plant-disease classes.
- Train the new classification layers.
- Optionally unfreeze selected upper layers and fine-tune with a low learning rate.
- Compare the results against your baseline CNN using the same test set.
Follow the preprocessing requirements of the selected pretrained model. For MobileNetV2, use its appropriate preprocessing function rather than applying an unrelated pixel scaling method.
11. Create a Web Application Using Streamlit
After training the model, you can build a simple interface that allows users to upload a leaf image and view the model’s prediction.
Install Streamlit if you have not already done so, then create an app.py file.
Example application code
import json
import streamlit as st
import tensorflow as tf
import numpy as np
from PIL import Image
st.set_page_config(
page_title="Crop Disease Classifier",
page_icon="🌿"
)
@st.cache_resource
def load_model():
return tf.keras.models.load_model(
"crop_disease_model.keras"
)
with open("class_names.json", "r") as file:
class_names = json.load(file)
model = load_model()
st.title("Crop Disease Detection")
st.write(
"Upload a plant-leaf image to see the "
"model's predicted category."
)
uploaded_file = st.file_uploader(
"Choose a leaf image",
type=["jpg", "jpeg", "png"]
)
if uploaded_file is not None:
image = Image.open(uploaded_file).convert("RGB")
st.image(
image,
caption="Uploaded leaf image",
use_container_width=True
)
resized = image.resize((128, 128))
image_array = np.array(resized, dtype=np.float32)
image_array = np.expand_dims(
image_array, axis=0
)
predictions = model.predict(image_array)
scores = predictions[0]
best_index = int(np.argmax(scores))
best_score = float(scores[best_index])
st.subheader("Model Prediction")
st.write(class_names[best_index])
st.write(
f"Model score: {best_score:.2%}"
)
if best_score < 0.60:
st.warning(
"The model is uncertain. Try a clearer "
"image and verify the result with an "
"agricultural expert."
)
else:
st.info(
"This is a model prediction, not a "
"confirmed plant disease diagnosis."
)
Run the application using:
streamlit run app.py
The example assumes the saved model uses the same 128 × 128 image size and preprocessing steps as the training code. Keep these settings consistent between training and prediction.
12. Main Modules of the Project
| Module | Function |
|---|---|
| Image Upload | Accepts plant-leaf images from users. |
| Image Preprocessing | Resizes and prepares images for the model. |
| Dataset Management | Organises labelled images into categories. |
| CNN Training | Trains the image-classification model. |
| Disease Classification | Predicts the most likely trained category. |
| Result Display | Shows prediction and model score. |
| Model Evaluation | Measures performance on unseen images. |
13. Testing and Model Evaluation
Testing is essential because a model can perform well on training images but fail on new photographs. Evaluate your model using images that were not used for training or model selection.
Use the following metrics to understand its performance:
| Metric | Purpose |
|---|---|
| Accuracy | Measures the proportion of correct predictions. |
| Precision | Measures how many predictions for a class were correct. |
| Recall | Measures how many actual samples of a class were detected. |
| F1-score | Combines precision and recall. |
| Confusion Matrix | Shows which classes are being confused. |
| Inference Time | Measures how long the model takes to produce a prediction. |
Check performance separately for each class. A high overall accuracy can hide poor results for less frequent disease categories.
14. Important Challenges and Limitations
Plant disease classification is not simply a matter of identifying spots on a leaf. Real agricultural images contain different lighting conditions, backgrounds, leaf positions, camera qualities, and overlapping symptoms.
- Dataset limitations: A model trained on controlled-background images may struggle with outdoor photographs.
- Class imbalance: Some disease categories may have more training examples than others.
- Similar symptoms: Different plant diseases can produce visually similar symptoms.
- Image quality: Blurry, dark, or obstructed images can reduce prediction quality.
- Overfitting: A model may memorise training patterns instead of learning features that generalise.
- Unseen categories: A standard classifier may assign an unfamiliar leaf or non-leaf image to one of its known classes.
15. Future Enhancements
You can ex


