Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import geopandas as gpd
|
3 |
+
import leafmap.foliumap as leafmap
|
4 |
+
from PIL import Image
|
5 |
+
import rasterio
|
6 |
+
from rasterio.windows import Window
|
7 |
+
from tqdm import tqdm
|
8 |
+
import io
|
9 |
+
import zipfile
|
10 |
+
import os
|
11 |
+
import albumentations as albu
|
12 |
+
import segmentation_models_pytorch as smp
|
13 |
+
from albumentations.pytorch.transforms import ToTensorV2
|
14 |
+
from shapely.geometry import shape
|
15 |
+
from shapely.ops import unary_union
|
16 |
+
from rasterio.features import shapes
|
17 |
+
import torch
|
18 |
+
import numpy as np
|
19 |
+
|
20 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
21 |
+
ENCODER = 'se_resnext50_32x4d'
|
22 |
+
ENCODER_WEIGHTS = 'imagenet'
|
23 |
+
|
24 |
+
# Load and prepare the model
|
25 |
+
def load_model():
|
26 |
+
model = torch.load('deeplabv3+ v15.pth', map_location=DEVICE)
|
27 |
+
model.eval().float()
|
28 |
+
return model
|
29 |
+
|
30 |
+
best_model = load_model()
|
31 |
+
|
32 |
+
def to_tensor(x, **kwargs):
|
33 |
+
return x.astype('float32')
|
34 |
+
|
35 |
+
# Preprocessing
|
36 |
+
preprocessing_fn = smp.encoders.get_preprocessing_fn(ENCODER, ENCODER_WEIGHTS)
|
37 |
+
|
38 |
+
def get_preprocessing(tile_size):
|
39 |
+
_transform = [
|
40 |
+
albu.PadIfNeeded(min_height=tile_size, min_width=tile_size, always_apply=True),
|
41 |
+
albu.Lambda(image=preprocessing_fn),
|
42 |
+
albu.Lambda(image=to_tensor, mask=to_tensor),
|
43 |
+
ToTensorV2(),
|
44 |
+
]
|
45 |
+
return albu.Compose(_transform)
|
46 |
+
|
47 |
+
def extract_tiles(map_file, model, tile_size=512, overlap=0, batch_size=4, threshold=0.6):
|
48 |
+
preprocess = get_preprocessing(tile_size)
|
49 |
+
tiles = []
|
50 |
+
|
51 |
+
with rasterio.open(map_file) as src:
|
52 |
+
height = src.height
|
53 |
+
width = src.width
|
54 |
+
effective_tile_size = tile_size - overlap
|
55 |
+
|
56 |
+
for y in stqdm(range(0, height, effective_tile_size)):
|
57 |
+
for x in range(0, width, effective_tile_size):
|
58 |
+
batch_images = []
|
59 |
+
batch_metas = []
|
60 |
+
|
61 |
+
for i in range(batch_size):
|
62 |
+
curr_y = y + (i * effective_tile_size)
|
63 |
+
if curr_y >= height:
|
64 |
+
break
|
65 |
+
|
66 |
+
window = Window(x, curr_y, tile_size, tile_size)
|
67 |
+
out_image = src.read(window=window)
|
68 |
+
|
69 |
+
if out_image.shape[0] == 1:
|
70 |
+
out_image = np.repeat(out_image, 3, axis=0)
|
71 |
+
elif out_image.shape[0] != 3:
|
72 |
+
raise ValueError("The number of channels in the image is not supported")
|
73 |
+
|
74 |
+
out_image = np.transpose(out_image, (1, 2, 0))
|
75 |
+
tile_image = Image.fromarray(out_image.astype(np.uint8))
|
76 |
+
|
77 |
+
out_meta = src.meta.copy()
|
78 |
+
out_meta.update({
|
79 |
+
"driver": "GTiff",
|
80 |
+
"height": tile_size,
|
81 |
+
"width": tile_size,
|
82 |
+
"transform": rasterio.windows.transform(window, src.transform)
|
83 |
+
})
|
84 |
+
|
85 |
+
tile_image = np.array(tile_image)
|
86 |
+
preprocessed_tile = preprocess(image=tile_image)['image']
|
87 |
+
batch_images.append(preprocessed_tile)
|
88 |
+
batch_metas.append(out_meta)
|
89 |
+
|
90 |
+
if not batch_images:
|
91 |
+
break
|
92 |
+
|
93 |
+
batch_tensor = torch.cat([img.unsqueeze(0).to(DEVICE) for img in batch_images], dim=0)
|
94 |
+
with torch.no_grad():
|
95 |
+
batch_masks = model(batch_tensor)
|
96 |
+
|
97 |
+
batch_masks = torch.sigmoid(batch_masks)
|
98 |
+
batch_masks = (batch_masks > threshold).float()
|
99 |
+
|
100 |
+
for j, mask_tensor in enumerate(batch_masks):
|
101 |
+
mask_resized = torch.nn.functional.interpolate(mask_tensor.unsqueeze(0),
|
102 |
+
size=(tile_size, tile_size), mode='bilinear',
|
103 |
+
align_corners=False).squeeze(0)
|
104 |
+
|
105 |
+
mask_array = mask_resized.squeeze().cpu().numpy()
|
106 |
+
|
107 |
+
if mask_array.any() == 1:
|
108 |
+
tiles.append([mask_array, batch_metas[j]])
|
109 |
+
|
110 |
+
return tiles
|
111 |
+
|
112 |
+
def create_vector_mask(tiles, output_path):
|
113 |
+
all_polygons = []
|
114 |
+
for mask_array, meta in tiles:
|
115 |
+
# Ensure mask is binary
|
116 |
+
mask_array = (mask_array > 0).astype(np.uint8)
|
117 |
+
|
118 |
+
# Get shapes from the mask
|
119 |
+
mask_shapes = list(shapes(mask_array, mask=mask_array, transform=meta['transform']))
|
120 |
+
|
121 |
+
# Convert shapes to Shapely polygons
|
122 |
+
polygons = [shape(geom) for geom, value in mask_shapes if value == 1]
|
123 |
+
|
124 |
+
all_polygons.extend(polygons)
|
125 |
+
# Perform union of all polygons
|
126 |
+
union_polygon = unary_union(all_polygons)
|
127 |
+
# Create a GeoDataFrame
|
128 |
+
gdf = gpd.GeoDataFrame({'geometry': [union_polygon]}, crs=meta['crs'])
|
129 |
+
# Save to file
|
130 |
+
gdf.to_file(output_path)
|
131 |
+
|
132 |
+
# Calculate area in square meters
|
133 |
+
area_m2 = gdf.to_crs(epsg=3857).area.sum()
|
134 |
+
|
135 |
+
return gdf, area_m2
|
136 |
+
|
137 |
+
def display_map(shapefile_path, tif_path):
|
138 |
+
# Create a leafmap centered on the shapefile bounds
|
139 |
+
mask = gpd.read_file(shapefile_path)
|
140 |
+
if mask.crs is None or mask.crs.to_string() != 'EPSG:3857':
|
141 |
+
mask = mask.to_crs('EPSG:3857')
|
142 |
+
bounds = mask.total_bounds
|
143 |
+
center = [(bounds[1] + bounds[3]) / 2, (bounds[0] + bounds[2]) / 2]
|
144 |
+
m = leafmap.Map(center=[center[1], center[0]], zoom=10, crs='EPSG3857')
|
145 |
+
m.add_gdf(mask, layer_name="Shapefile Mask")
|
146 |
+
m.add_raster(tif_path, layer_name="Satellite Image", rgb=True, opacity=0.9)
|
147 |
+
return m
|
148 |
+
|
149 |
+
def process_file(tif_file, resolution, overlap, threshold):
|
150 |
+
with open("temp.tif", "wb") as f:
|
151 |
+
f.write(tif_file.read())
|
152 |
+
|
153 |
+
best_model.float()
|
154 |
+
tiles = extract_tiles("temp.tif", best_model, tile_size=resolution, overlap=overlap, batch_size=4, threshold=threshold)
|
155 |
+
|
156 |
+
output_path = "output_mask.shp"
|
157 |
+
result_gdf, area_m2 = create_vector_mask(tiles, output_path)
|
158 |
+
|
159 |
+
# Create zip file for shapefile
|
160 |
+
shp_files = [f for f in os.listdir() if f.startswith("output_mask") and f.endswith((".shp", ".shx", ".dbf", ".prj"))]
|
161 |
+
with io.BytesIO() as zip_buffer:
|
162 |
+
with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zip_file:
|
163 |
+
for file in shp_files:
|
164 |
+
zip_file.write(file)
|
165 |
+
zip_buffer.seek(0)
|
166 |
+
with open("output_mask.zip", "wb") as f:
|
167 |
+
f.write(zip_buffer.getvalue())
|
168 |
+
|
169 |
+
# Display map
|
170 |
+
map_html = display_map("output_mask.shp", "temp.tif").to_html()
|
171 |
+
|
172 |
+
# Clean up temporary files
|
173 |
+
os.remove("temp.tif")
|
174 |
+
for file in shp_files:
|
175 |
+
os.remove(file)
|
176 |
+
|
177 |
+
return f"Total area occupied by PV panels: {area_m2:.4f} m^2", "output_mask.zip", map_html
|
178 |
+
|
179 |
+
iface = gr.Interface(
|
180 |
+
fn=process_file,
|
181 |
+
inputs=[
|
182 |
+
gr.File(label="Upload TIF file"),
|
183 |
+
gr.Radio([512, 1024], label="Processing resolution", value=512),
|
184 |
+
gr.Slider(50, 150, value=100, step=25, label="Overlap"),
|
185 |
+
gr.Slider(0.1, 0.9, value=0.6, step=0.01, label="Threshold")
|
186 |
+
],
|
187 |
+
outputs=[
|
188 |
+
gr.Textbox(label="Result"),
|
189 |
+
gr.File(label="Download Shapefile"),
|
190 |
+
gr.HTML(label="Map")
|
191 |
+
],
|
192 |
+
title="PV Segmentor",
|
193 |
+
description="Upload a TIF file to process and segment PV panels."
|
194 |
+
)
|
195 |
+
|
196 |
+
if __name__ == "__main__":
|
197 |
+
iface.launch()
|