Eleawa's picture
Create app.py
e286d96 verified
import gradio as gr
import numpy as np
from PIL import Image
import tensorflow as tf
# Load the trained model
model = tf.keras.models.load_model("preprocessed_model.keras")
input_size = (224, 224)
# EuroSAT class names
class_names = [
'AnnualCrop', 'Forest', 'HerbaceousVegetation',
'Highway', 'Industrial', 'Pasture',
'PermanentCrop', 'Residential', 'River',
'SeaLake'
]
# Prediction function
def classify_image(img: Image.Image):
try:
# Resize and preprocess the image
img_resized = img.resize(input_size)
img_array = np.array(img_resized) / 255.0 # Normalize
img_array = np.expand_dims(img_array, axis=0)
# Predict
predictions = model.predict(img_array)[0]
predicted_index = np.argmax(predictions)
predicted_class = class_names[predicted_index]
confidence = predictions[predicted_index]
# Create dictionary of class probabilities
result = {
class_names[i]: float(predictions[i])
for i in range(len(class_names))
}
return predicted_class, confidence, result
except Exception as e:
return f"Error: {str(e)}", 0.0, {}
# Gradio Interface
image_input = gr.Image(type="pil", label="Upload EuroSAT Image")
label_output = gr.Label(num_top_classes=3, label="Top Predictions")
text_output = gr.Textbox(label="Predicted Class with Confidence")
interface = gr.Interface(
fn=lambda img: (
classify_image(img)[0] + f" ({classify_image(img)[1]*100:.2f}%)",
classify_image(img)[2]
),
inputs=image_input,
outputs=[text_output, label_output],
title="EuroSAT Land Cover Classifier",
description="Upload a satellite image (EuroSAT-like) to classify its land cover type using a deep learning model."
)
# Launch locally or on HF Spaces
if __name__ == "__main__":
interface.launch()