Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
|
| 6 |
+
# Load the trained model
|
| 7 |
+
model = tf.keras.models.load_model("preprocessed_model.keras")
|
| 8 |
+
input_size = (224, 224)
|
| 9 |
+
|
| 10 |
+
# EuroSAT class names
|
| 11 |
+
class_names = [
|
| 12 |
+
'AnnualCrop', 'Forest', 'HerbaceousVegetation',
|
| 13 |
+
'Highway', 'Industrial', 'Pasture',
|
| 14 |
+
'PermanentCrop', 'Residential', 'River',
|
| 15 |
+
'SeaLake'
|
| 16 |
+
]
|
| 17 |
+
|
| 18 |
+
# Prediction function
|
| 19 |
+
def classify_image(img: Image.Image):
|
| 20 |
+
try:
|
| 21 |
+
# Resize and preprocess the image
|
| 22 |
+
img_resized = img.resize(input_size)
|
| 23 |
+
img_array = np.array(img_resized) / 255.0 # Normalize
|
| 24 |
+
img_array = np.expand_dims(img_array, axis=0)
|
| 25 |
+
|
| 26 |
+
# Predict
|
| 27 |
+
predictions = model.predict(img_array)[0]
|
| 28 |
+
predicted_index = np.argmax(predictions)
|
| 29 |
+
predicted_class = class_names[predicted_index]
|
| 30 |
+
confidence = predictions[predicted_index]
|
| 31 |
+
|
| 32 |
+
# Create dictionary of class probabilities
|
| 33 |
+
result = {
|
| 34 |
+
class_names[i]: float(predictions[i])
|
| 35 |
+
for i in range(len(class_names))
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
return predicted_class, confidence, result
|
| 39 |
+
except Exception as e:
|
| 40 |
+
return f"Error: {str(e)}", 0.0, {}
|
| 41 |
+
|
| 42 |
+
# Gradio Interface
|
| 43 |
+
image_input = gr.Image(type="pil", label="Upload EuroSAT Image")
|
| 44 |
+
label_output = gr.Label(num_top_classes=3, label="Top Predictions")
|
| 45 |
+
text_output = gr.Textbox(label="Predicted Class with Confidence")
|
| 46 |
+
|
| 47 |
+
interface = gr.Interface(
|
| 48 |
+
fn=lambda img: (
|
| 49 |
+
classify_image(img)[0] + f" ({classify_image(img)[1]*100:.2f}%)",
|
| 50 |
+
classify_image(img)[2]
|
| 51 |
+
),
|
| 52 |
+
inputs=image_input,
|
| 53 |
+
outputs=[text_output, label_output],
|
| 54 |
+
title="EuroSAT Land Cover Classifier",
|
| 55 |
+
description="Upload a satellite image (EuroSAT-like) to classify its land cover type using a deep learning model."
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
# Launch locally or on HF Spaces
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
interface.launch()
|