File size: 7,652 Bytes
d6088ea
800c083
d6088ea
 
 
964aba1
a4ff8d9
76468cf
 
 
 
 
 
 
 
 
 
 
b3321cc
d6088ea
 
8290e98
76468cf
 
 
3a0d2d4
b3321cc
76468cf
 
f926bb8
76468cf
 
 
4ba5664
d6088ea
 
76468cf
 
d6088ea
 
 
9b2501a
6a3d01f
d6088ea
a4ff8d9
 
1a93018
8290e98
 
 
 
d6088ea
 
 
 
6a3d01f
d6088ea
a4ff8d9
8290e98
 
1a93018
8290e98
1a93018
8290e98
1a93018
8290e98
1a93018
8290e98
d6088ea
 
 
 
a4ff8d9
8290e98
800c083
76468cf
a4ff8d9
8290e98
d6088ea
 
 
8290e98
800c083
8290e98
 
 
76468cf
3a0d2d4
76468cf
 
 
 
 
 
3a0d2d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76468cf
 
 
 
 
 
 
 
 
d6088ea
 
 
 
 
 
 
 
 
 
 
 
 
 
1a93018
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import streamlit as st
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
from PIL import Image

# Load the models
try:
    corn_model = load_model('corn_model_mobilenetv2.h5')
    cassava_model = load_model('cassava_disease_model.h5')
    leaf_nonleaf_model = load_model('model_checkpoint')  # Binary classifier
except Exception as e:
    st.error(f"Error loading models: {e}")
    st.stop()

# Function to preprocess an image
def preprocess_image(img, target_size):
    img = img.resize(target_size)
    img = img.convert("RGB")
    img = image.img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = img / 255.0  # Normalize image
    return img

# Function to check if the image is a leaf or non-leaf
def is_not_leaf_image(img, threshold=0.01):
    img = img.convert("RGB")
    img = preprocess_image(img, (128, 128))  # Resize for binary classifier
    prediction = leaf_nonleaf_model.predict(img)
    return prediction[0][0] > threshold  # Assuming binary classifier outputs probability for class 1 (leaf)

# Function to predict an uploaded image
def predict_image(img, model, class_names):
    img = preprocess_image(img, (128, 128) if model == corn_model else (224, 224))
    prediction = model.predict(img)
    predicted_class = np.argmax(prediction)
    confidence = np.max(prediction) * 100
    return predicted_class, class_names[predicted_class], confidence

# Define pages
def home_page():
    st.title("Maize and Cassava Crop Disease Identification")
    st.image("1093908406.jpg", use_column_width=True)
    st.write("""
        Welcome to the Crop Disease Identification App. This tool aims at helping local farmers
        identify diseases in maize and cassava crops by analyzing images of leaves.
        
        Use the navigation menu to explore the app:
        - **Home:** Overview of the app
        - **About:** Information about the app and its purpose
        - **Prediction:** Upload an image and get a disease diagnosis along with recommendations
    """)

def about_page():
    st.title("About")
    st.image("IMG_20240727_143208_444.jpg", use_column_width=True)
    st.write("""
        This application is designed to assist farmers in diagnosing common diseases in maize and cassava crops.
        By utilizing deep learning models trained on thousands of leaf images, the app can accurately identify
        diseases such as "blight, common rust and gray leaf spot" in maize and "Bacterial blight, green mottle, brown streak and mosaic" in cassava.
        The models were built using Convolutional Neural Networks (CNNs), trained on publicly available datasets and tested on locally obtained images..
        The goal is to provide quick and accurate disease identification to help mitigate crop losses and improve yields.
        
        If you have any questions or feedback, please reach out to the developer.
        
        E-mail: olorunnisholato7@gmail.com
        
        Thank you for using the Crop Disease Identification App!
    """)

def prediction_page():
    st.title("Crop Disease Prediction")

    # Model selection
    crop_type = st.selectbox("Select the crop:", ["Maize", "Cassava"])
    model, class_names = get_model_and_classes(crop_type)

    # File uploader for image input
    uploaded_file = st.file_uploader("Upload an image of the leaf...", type=["jpg", "jpeg", "png"])

    if uploaded_file is not None:
        # Load the uploaded image
        img = Image.open(uploaded_file)
        st.image(img, caption='Uploaded Image', use_column_width=True)
        st.write("")

        # Check if the image is a leaf
        if is_not_leaf_image(img):
            st.error("The uploaded image does not appear to be a leaf. Please upload a clear image of a leaf.")
        else:
            # Predict button
            if st.button('Predict'):
                with st.spinner("Classifying..."):
                    predicted_class, class_name, confidence = predict_image(img, model, class_names)
                    st.write(f"Predicted Class: {class_name}")

            # Recommendation based on the predicted class
            if class_name == 'Healthy' or class_name == 'Cassava_healthy':
                st.success("The leaf is healthy. No action needed.")
            else:
                recommendations = {
                    'Blight': "Recommendation: Immediately remove and destroy infected plants to prevent the spread of the disease.  Implement a rotation plan that avoids planting corn for at least two years in affected fields.  Apply a fungicide that is effective against blight, such as those containing chlorothalonil or mancozeb, at the early signs of disease.Consider planting blight-resistant corn varieties in future planting seasons.",
                    'Common_Rust': "Recommendation: Use resistant varieties and apply fungicides if necessary.  If rust is detected early, apply a fungicide like azoxystrobin or tebuconazole to control the spread.  Clear out any crop debris from previous seasons, as rust spores can survive in old plant material.  Avoid overhead irrigation to reduce leaf wetness, which can promote rust development.",
                    'Gray_Leaf_Spot': "Recommendation: Ensure proper crop rotation and apply fungicides.   Regularly monitor fields during humid conditions, as Gray Leaf Spot thrives in such environments.   Use fungicides like pyraclostrobin or propiconazole at the onset of symptoms.   Ensure balanced nitrogen levels; excessive nitrogen can exacerbate Gray Leaf Spot.   Consider tillage practices that bury crop residues, reducing the amount of fungal spores in the soil.",
                    'Cassava_bacterial_blight': "Recommendation: Use disease-free planting material and remove affected plants.   Remove and destroy infected plants to prevent the spread.   Avoid excessive irrigation and ensure proper drainage to reduce waterlogging, which can exacerbate CBB.   Sterilize tools and equipment to avoid spreading bacteria from infected plants.",
                    'Cassava_brown_streak_disease': "Recommendation: Plant CBSD-resistant cassava varieties, such as those developed through breeding programs.    Consider harvesting earlier than usual to reduce yield loss if CBSD symptoms are present.    Manage whiteflies, the primary vector for CBSD, by using insecticides or planting barrier crops.   Isolate infected fields from healthy ones to prevent the spread of the virus",
                    'Cassava_green_mottle': "Recommendation: Ensure good field sanitation and use resistant varieties.   Select varieties known for resistance to CGM.   Control weeds that may serve as hosts for the CGM virus.",
                    'Cassava_mosaic_disease': "Recommendation: Use resistant varieties and practice good field hygiene."
                }
                st.warning(recommendations[class_name])

# Helper function to get model and class names
def get_model_and_classes(crop_type):
    if crop_type == "Maize":
        return corn_model, ['Blight', 'Common_Rust', 'Gray_Leaf_Spot', 'Healthy']
    elif crop_type == "Cassava":
        return cassava_model, ['Cassava_bacterial_blight', 'Cassava_brown_streak_disease', 'Cassava_green_mottle', 'Cassava_healthy', 'Cassava_mosaic_disease']
    else:
        return None, None

# Main app
def main():
    st.sidebar.title("Navigation")
    page = st.sidebar.radio("Go to", ["Home", "About", "Prediction"])

    if page == "Home":
        home_page()
    elif page == "About":
        about_page()
    elif page == "Prediction":
        prediction_page()

if __name__ == "__main__":
    main()