ajoy0071998's picture
Update app.py
d957bac verified
import streamlit as st
import numpy as np
import tensorflow as tf
import rasterio
import json
import tempfile
import os
# Load the model
model = tf.keras.models.load_model("EuroSAT_model.h5", cstom_objects={"GetItem": GetItem})
# Load class labels
with open("label_map.json", "r") as f:
class_labels = json.load(f)
class_labels = {v: k for k, v in class_labels.items()}
# Function to preprocess a .tif image and compute indices
def preprocess_tif(file_path, target_size=(224, 224)):
with rasterio.open(file_path) as src:
B3 = src.read(3).astype(np.float32) # Green
B4 = src.read(4).astype(np.float32) # Red
B5 = src.read(5).astype(np.float32) # NIR
B6 = src.read(6).astype(np.float32) # SWIR1
NDVI = (B5 - B4) / (B5 + B4 + 1e-5)
NDBI = (B6 - B5) / (B6 + B5 + 1e-5)
NDWI = (B3 - B5) / (B3 + B5 + 1e-5)
index_img = np.stack([NDBI, NDVI, NDWI], axis=-1)
index_img = np.nan_to_num(index_img)
index_img = tf.image.resize(index_img, target_size).numpy()
index_img = np.clip(index_img, -1, 1)
index_img = np.expand_dims(index_img, axis=0) # Add batch dimension
return index_img
# Streamlit App
st.title("Satellite Image Classification with Spectral Indices")
st.write("Upload a .tif satellite image. The model computes NDVI, NDBI, and NDWI, then predicts the class.")
# File uploader
uploaded_file = st.file_uploader("Choose a .tif image...", type=["tif", "tiff"])
if uploaded_file is not None:
# Save uploaded file to a temporary location
with tempfile.NamedTemporaryFile(delete=False, suffix=".tif") as tmp:
tmp.write(uploaded_file.read())
tmp_path = tmp.name
# Preprocess image
processed_image = preprocess_tif(tmp_path)
# Predict
predictions = model.predict(processed_image)
class_idx = np.argmax(predictions, axis=1)[0]
predicted_class = class_labels[class_idx]
# Show results
st.write(f"Predicted Class: **{predicted_class}**")
# Cleanup temp file
os.remove(tmp_path)