Spaces:
Runtime error
Runtime error
Menezes commited on
Upload 2 files
Browse filesFiles changed (2)
- app.pyAdded+145
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import os
import zipfile
import tempfile
import uuid
import rasterio
import numpy as np
import matplotlib.pyplot as plt
import gradio as gr
from rasterio.enums import Resampling
def gerar_caminho_temporario(suffix=".tif"):
return os.path.join(tempfile.gettempdir(), f"{uuid.uuid4().hex}{suffix}")
def ler_banda(caminho):
with rasterio.open(caminho) as src:
return src.read(1).astype(np.float32), src.profile
def reamostrar_para_10m(banda_path, ref_shape, ref_transform):
with rasterio.open(banda_path) as src:
data = src.read(
out_shape=(1, ref_shape[0], ref_shape[1]),
resampling=Resampling.bilinear
)
return data[0].astype(np.float32)
def normalizar(arr):
arr /= 10000.0
return np.clip(arr, 0, 1)
def imagem_para_fig(img, title, cmap=None):
fig = plt.figure(figsize=(6, 6))
if cmap:
plt.imshow(img, cmap=cmap)
plt.colorbar()
else:
plt.imshow(img)
plt.title(title)
plt.axis('off')
return fig
def salvar_tif(path, array, profile, count=3):
profile = profile.copy()
profile.update({
'driver': 'GTiff',
'count': count,
'dtype': rasterio.float32,
'compress': 'deflate',
'predictor': 2,
'tiled': True,
'blockxsize': 512,
'blockysize': 512
})
with rasterio.open(path, 'w', **profile) as dst:
if count == 1:
dst.write(array, 1)
else:
for i in range(count):
dst.write(array[:, :, i], i + 1)
def processar_visualizacao(zip_file_path, tipo_vis):
with tempfile.TemporaryDirectory() as temp_dir:
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
dirs = [d for d in os.listdir(temp_dir) if d.endswith(".SAFE")]
if not dirs:
raise Exception("Pasta .SAFE não encontrada dentro do zip.")
extract_dir = os.path.join(temp_dir, dirs[0])
granule = os.path.join(extract_dir, "GRANULE")
granule_path = [os.path.join(granule, d) for d in os.listdir(granule) if d.startswith("L2A_")][0]
img_data_path = os.path.join(granule_path, "IMG_DATA")
res_paths = {
"R10m": os.path.join(img_data_path, "R10m"),
"R20m": os.path.join(img_data_path, "R20m")
}
# Referência para geometria
b4, prof = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B04" in f][0]))
if tipo_vis == "RGB Natural (B4, B3, B2)":
b2, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B02" in f][0]))
b3, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B03" in f][0]))
rgb = np.stack([b4, b3, b2], axis=-1)
rgb_fig = imagem_para_fig(normalizar(rgb), tipo_vis)
tif_path = gerar_caminho_temporario(".tif")
salvar_tif(tif_path, rgb, prof, count=3)
return rgb_fig, tif_path
elif tipo_vis == "Falsa Cor Vegetação (B8, B4, B3)":
b3, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B03" in f][0]))
b8, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B08" in f][0]))
fcv = np.stack([b8, b4, b3], axis=-1)
fcv_fig = imagem_para_fig(normalizar(fcv), tipo_vis)
tif_path = gerar_caminho_temporario(".tif")
salvar_tif(tif_path, fcv, prof, count=3)
return fcv_fig, tif_path
elif tipo_vis == "Falso Colorido SWIR (B12, B8, B4)":
b8, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B08" in f][0]))
b12_path = os.path.join(res_paths["R20m"], [f for f in os.listdir(res_paths["R20m"]) if "_B12" in f][0])
b12 = reamostrar_para_10m(b12_path, b4.shape, prof["transform"])
fcswir = np.stack([b12, b8, b4], axis=-1)
fcswir_fig = imagem_para_fig(normalizar(fcswir), tipo_vis)
tif_path = gerar_caminho_temporario(".tif")
salvar_tif(tif_path, fcswir, prof, count=3)
return fcswir_fig, tif_path
elif tipo_vis == "NDVI":
b8, _ = ler_banda(os.path.join(res_paths["R10m"], [f for f in os.listdir(res_paths["R10m"]) if "_B08" in f][0]))
ndvi = (b8 - b4) / (b8 + b4 + 1e-6)
ndvi_fig = imagem_para_fig(ndvi, "NDVI", cmap='RdYlGn')
tif_path = gerar_caminho_temporario(".tif")
salvar_tif(tif_path, ndvi, prof, count=1)
return ndvi_fig, tif_path
else:
raise ValueError("Tipo de visualização inválido.")
# === Interface Gradio ===
demo = gr.Interface(
fn=processar_visualizacao,
inputs=[
gr.File(label="Arquivo Sentinel-2 (.zip)", type="filepath"),
gr.Dropdown(
choices=[
"RGB Natural (B4, B3, B2)",
"Falsa Cor Vegetação (B8, B4, B3)",
"Falso Colorido SWIR (B12, B8, B4)",
"NDVI"
],
label="Tipo de visualização"
)
],
outputs=[
gr.Plot(label="Visualização"),
gr.File(label="Download do GeoTIFF")
],
title="Sentinel-2: Visualizar + Exportar GeoTIFF",
description="Escolha uma visualização, envie um arquivo .SAFE.zip e baixe o GeoTIFF correspondente."
)
if __name__ == "__main__":
demo.launch()1234gradio>=4.0
rasterio>=1.3
numpy>=1.21
matplotlib>=3.5app.pyAdded+145
requirements.txtAdded+4