File size: 1,877 Bytes
e286d96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()