Spaces:
Sleeping
Sleeping
File size: 5,276 Bytes
a57f092 8ee45cf a57f092 |
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 135 136 137 138 139 |
import gradio as gr
import tensorflow as tf
import numpy as np
import PIL.Image
# Class names for prediction
CLASS_NAMES = ['Alphida', 'Army worm', 'Bacterial blight', 'Healthy leaf', 'Leaf spot', 'Powdery Mildew']
# Load the pre-trained model
def load_model():
try:
model = tf.keras.models.load_model('cotton_plant_disease_classifier.h5')
return model
except Exception as e:
print(f"Error loading model: {e}")
return None
# Prepare the image for prediction
def prepare_image(image):
# Resize the image
img = image.resize((180, 180))
# Convert to numpy array
img_array = np.array(img)
# Expand dimensions to create a batch
img_array = np.expand_dims(img_array, axis=0)
return img_array
# Prediction function
def predict_disease(model, image):
# Prepare the image
processed_image = prepare_image(image)
# Make prediction
predictions = model.predict(processed_image)
score = tf.nn.softmax(predictions[0])
# Get the predicted class and confidence
predicted_class_index = np.argmax(score)
predicted_class = CLASS_NAMES[predicted_class_index]
confidence = 100 * np.max(score)
return predicted_class, confidence
# Detailed disease information
DISEASE_INFO = {
"Alphida": {
"description": "Aphids are small insects that can damage cotton plants by sucking sap and spreading viruses.",
"impact": "Low to moderate crop damage",
"treatment": "Use insecticidal soaps, neem oil, or introduce natural predators like ladybugs"
},
"Army worm": {
"description": "Army worms can cause significant damage by consuming leaf tissue, potentially reducing crop yield.",
"impact": "High crop damage potential",
"treatment": "Apply appropriate insecticides, practice crop rotation, maintain field hygiene"
},
"Bacterial blight": {
"description": "A bacterial disease that causes lesions and wilting in cotton plants.",
"impact": "Moderate to severe crop damage",
"treatment": "Use copper-based bactericides, remove infected plants, practice crop rotation"
},
"Leaf spot": {
"description": "A fungal disease that creates spots on leaves, potentially affecting plant health and productivity.",
"impact": "Moderate crop damage",
"treatment": "Apply fungicides, ensure proper plant spacing, avoid overhead irrigation"
},
"Powdery Mildew": {
"description": "A fungal disease that appears as a white powdery substance on leaf surfaces.",
"impact": "Moderate crop damage",
"treatment": "Use sulfur-based fungicides, improve air circulation, avoid overhead watering"
},
"Healthy leaf": {
"description": "The cotton plant leaf is in good health with no visible diseases or pest damage.",
"impact": "No negative impact",
"treatment": "Continue regular plant care and monitoring"
}
}
# Main prediction interface
def cotton_disease_prediction(input_image):
# Load the model (you might want to load this once globally)
model = load_model()
if model is None:
return "Error: Model could not be loaded", None, None
if input_image is None:
return "Please upload an image", None, None
try:
# Convert to PIL Image if it's not already
if not isinstance(input_image, PIL.Image.Image):
input_image = PIL.Image.fromarray(input_image)
# Predict disease
predicted_class, confidence = predict_disease(model, input_image)
# Get detailed information
disease_details = DISEASE_INFO.get(predicted_class, {})
# Format result
result_text = f"Predicted Disease: {predicted_class}\n"
result_text += f"Confidence: {confidence:.2f}%\n\n"
result_text += f"Description: {disease_details.get('description', 'No additional information')}\n"
result_text += f"Impact: {disease_details.get('impact', 'Not specified')}\n"
result_text += f"Treatment: {disease_details.get('treatment', 'Consult an agricultural expert')}"
return result_text, predicted_class, confidence
except Exception as e:
return f"Error in prediction: {str(e)}", None, None
# Create Gradio Interface
def create_gradio_interface():
# Define input and output components
image_input = gr.Image(type="pil", label="Upload Cotton Leaf Image")
text_output = gr.Textbox(label="Prediction Results")
disease_label = gr.Label(label="Detected Disease")
confidence_number = gr.Number(label="Confidence Score")
# Create the Gradio interface
demo = gr.Interface(
fn=cotton_disease_prediction,
inputs=image_input,
outputs=[text_output, disease_label, confidence_number],
title="Cotton Plant Disease Detector",
description="Upload a cotton plant leaf image to detect potential diseases or assess health status.",
theme="huggingface",
examples=[
["example_healthy_leaf.jpg"],
["example_diseased_leaf.jpg"]
]
)
return demo
# Launch the app
if __name__ == "__main__":
demo = create_gradio_interface()
demo.launch() |