Spaces:
Sleeping
Sleeping
Update inference.py
Browse files- inference.py +370 -338
inference.py
CHANGED
|
@@ -1,6 +1,22 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
Performs building, road, and water body segmentation on orthophoto tiles using UNet++.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os
|
|
@@ -8,10 +24,9 @@ import sys
|
|
| 8 |
import cv2
|
| 9 |
import numpy as np
|
| 10 |
import torch
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
from pathlib import Path
|
| 13 |
import segmentation_models_pytorch as smp
|
| 14 |
-
from typing import Tuple, Dict, Optional
|
| 15 |
|
| 16 |
# Ensure UTF-8 output encoding for Windows consoles
|
| 17 |
if hasattr(sys.stdout, "reconfigure"):
|
|
@@ -20,232 +35,318 @@ if hasattr(sys.stdout, "reconfigure"):
|
|
| 20 |
except Exception:
|
| 21 |
pass
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
from PIL import Image
|
| 26 |
Image.MAX_IMAGE_PIXELS = None
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
_IMAGE_CACHE = {}
|
|
|
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
|
|
|
| 32 |
"""
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
and caches in RAM to eliminate latency when switching features or thresholds.
|
| 36 |
"""
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
try:
|
| 43 |
-
# Open with PIL first to inspect dimensions and downsample before uncompressed memory allocation
|
| 44 |
with Image.open(image_path) as pil_img:
|
| 45 |
w, h = pil_img.size
|
| 46 |
if max(w, h) > max_dim:
|
| 47 |
scale = max_dim / float(max(w, h))
|
| 48 |
new_w, new_h = max(1, int(w * scale)), max(1, int(h * scale))
|
| 49 |
-
#
|
|
|
|
|
|
|
| 50 |
pil_img = pil_img.resize((new_w, new_h), Image.Resampling.BILINEAR)
|
| 51 |
-
|
| 52 |
if pil_img.mode != "RGB":
|
| 53 |
pil_img = pil_img.convert("RGB")
|
| 54 |
-
|
| 55 |
except Exception:
|
| 56 |
-
# Fallback to OpenCV if PIL fails
|
| 57 |
image = cv2.imread(image_path)
|
| 58 |
-
if image is
|
| 59 |
-
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 60 |
-
h, w = image.shape[:2]
|
| 61 |
-
if max(h, w) > max_dim:
|
| 62 |
-
scale = max_dim / float(max(h, w))
|
| 63 |
-
new_w, new_h = max(1, int(w * scale)), max(1, int(h * scale))
|
| 64 |
-
image = cv2.resize(image, (new_w, new_h))
|
| 65 |
-
result = image
|
| 66 |
-
else:
|
| 67 |
raise ValueError(f"Cannot load image {image_path}. Ensure it is a valid PNG, JPG, or TIFF format.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
_IMAGE_CACHE.clear()
|
| 71 |
_IMAGE_CACHE[cache_key] = result
|
| 72 |
return result.copy()
|
| 73 |
|
| 74 |
|
| 75 |
-
class
|
| 76 |
"""
|
| 77 |
Unified interface for SVAMITVA feature extraction using UNet++.
|
| 78 |
Supports buildings, roads, and water bodies segmentation.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
"""
|
| 80 |
-
|
| 81 |
def __init__(self, models_dir: str = "models", device: str = None):
|
| 82 |
-
"""
|
| 83 |
-
Initialize the segmentation models.
|
| 84 |
-
|
| 85 |
-
Args:
|
| 86 |
-
models_dir: Directory containing trained model weights
|
| 87 |
-
device: 'cuda', 'cpu', or None for auto-detection
|
| 88 |
-
"""
|
| 89 |
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 90 |
self.models_dir = Path(models_dir)
|
| 91 |
self.models = {}
|
| 92 |
self.feature_names = ["buildings", "roads", "water_bodies"]
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
classes=1,
|
| 113 |
-
activation="sigmoid"
|
| 114 |
-
)
|
| 115 |
-
|
| 116 |
-
# Load weights
|
| 117 |
-
state_dict = torch.load(model_path, map_location=self.device, weights_only=True)
|
| 118 |
-
model.load_state_dict(state_dict)
|
| 119 |
-
model.to(self.device)
|
| 120 |
-
model.eval()
|
| 121 |
-
|
| 122 |
-
self.models[feature_name] = model
|
| 123 |
-
print(f"✓ Loaded {feature_name} model")
|
| 124 |
-
except Exception as e:
|
| 125 |
-
print(f"✗ Failed to load {feature_name}: {e}")
|
| 126 |
-
|
| 127 |
-
def _preprocess_image(self, image_path: str, target_size: Tuple[int, int] = (512, 512)) -> np.ndarray:
|
| 128 |
-
"""
|
| 129 |
-
Preprocess image for inference.
|
| 130 |
-
"""
|
| 131 |
-
# Read image robustly
|
| 132 |
-
image = load_robust_image(image_path)
|
| 133 |
-
|
| 134 |
-
# Resize to target input size
|
| 135 |
-
image_resized = cv2.resize(image, (target_size[1], target_size[0]))
|
| 136 |
-
|
| 137 |
-
# Normalize to [0, 1]
|
| 138 |
-
image_norm = image_resized.astype(np.float32) / 255.0
|
| 139 |
-
|
| 140 |
-
# Convert to tensor and add batch dimension
|
| 141 |
-
image_tensor = torch.from_numpy(image_norm).permute(2, 0, 1).unsqueeze(0)
|
| 142 |
-
|
| 143 |
-
return image_tensor.to(self.device)
|
| 144 |
-
|
| 145 |
-
def _postprocess_mask(self, mask: torch.Tensor, threshold: float = 0.5) -> np.ndarray:
|
| 146 |
-
"""
|
| 147 |
-
Convert model output to binary mask.
|
| 148 |
-
"""
|
| 149 |
-
# Remove batch and channel dimensions
|
| 150 |
-
mask = mask.squeeze().cpu().detach().numpy()
|
| 151 |
-
|
| 152 |
-
# Apply threshold
|
| 153 |
-
binary_mask = (mask > threshold).astype(np.uint8) * 255
|
| 154 |
-
|
| 155 |
-
return binary_mask
|
| 156 |
-
|
| 157 |
-
def predict(self, image_path: str, feature: str = "buildings", threshold: float = 0.5) -> Dict:
|
| 158 |
-
"""
|
| 159 |
-
Run segmentation inference on an image.
|
| 160 |
-
"""
|
| 161 |
-
if feature not in self.models:
|
| 162 |
-
raise ValueError(f"Feature '{feature}' not available. Available: {list(self.models.keys())}")
|
| 163 |
-
|
| 164 |
try:
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
# Resize mask back to match display image shape
|
| 181 |
-
if original_image.shape[:2] != mask.shape:
|
| 182 |
-
mask = cv2.resize(mask, (original_image.shape[1], original_image.shape[0]))
|
| 183 |
-
|
| 184 |
-
# Create overlay
|
| 185 |
-
overlay = self._create_overlay(original_image, mask)
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
# Calculate metrics
|
| 189 |
-
detected_pixels = np.sum(mask > 0)
|
| 190 |
-
total_pixels = mask.size
|
| 191 |
-
detection_ratio = detected_pixels / total_pixels if total_pixels > 0 else 0
|
| 192 |
-
|
| 193 |
-
# Additional downstream analysis for buildings (rooftop classification & solar/tax calculations)
|
| 194 |
-
rooftop_analysis = None
|
| 195 |
-
if feature == "buildings" and detected_pixels > 0:
|
| 196 |
-
rooftop_analysis = self.classify_rooftops(original_image, mask)
|
| 197 |
-
|
| 198 |
-
return {
|
| 199 |
-
"original_image": original_image,
|
| 200 |
-
"mask": mask,
|
| 201 |
-
"overlay": overlay,
|
| 202 |
-
"feature": feature,
|
| 203 |
-
"detected_ratio": detection_ratio,
|
| 204 |
-
"detected_pixels": detected_pixels,
|
| 205 |
-
"total_pixels": total_pixels,
|
| 206 |
-
"rooftop_analysis": rooftop_analysis
|
| 207 |
-
}
|
| 208 |
-
|
| 209 |
except Exception as e:
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
@staticmethod
|
| 213 |
def classify_rooftops(image: np.ndarray, mask: np.ndarray) -> Dict:
|
| 214 |
"""
|
| 215 |
-
|
| 216 |
-
|
| 217 |
"""
|
| 218 |
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
| 219 |
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats((mask > 0).astype(np.uint8))
|
| 220 |
-
|
| 221 |
rooftop_counts = {
|
| 222 |
"RCC / Concrete": 0,
|
| 223 |
"Tiled / Terracotta": 0,
|
| 224 |
"Tin / Metal Sheet": 0,
|
| 225 |
-
"Others": 0
|
| 226 |
}
|
| 227 |
-
|
| 228 |
building_details = []
|
| 229 |
total_area_m2 = 0.0
|
| 230 |
rcc_area_m2 = 0.0
|
| 231 |
-
|
| 232 |
-
# Pixel scale: SVAMITVA 50cm resolution -> 1 pixel = 0.5m x 0.5m = 0.25 m²
|
| 233 |
-
pixel_area_m2 = 0.25
|
| 234 |
colored_classification_map = image.copy()
|
| 235 |
-
|
| 236 |
for i in range(1, num_labels):
|
| 237 |
area_px = stats[i, cv2.CC_STAT_AREA]
|
| 238 |
-
if area_px < 15:
|
| 239 |
continue
|
| 240 |
-
|
| 241 |
area_m2 = area_px * pixel_area_m2
|
| 242 |
total_area_m2 += area_m2
|
| 243 |
-
|
| 244 |
component_mask = (labels == i)
|
| 245 |
mean_hsv = cv2.mean(hsv, mask=component_mask.astype(np.uint8))
|
| 246 |
h, s, v = mean_hsv[0], mean_hsv[1], mean_hsv[2]
|
| 247 |
-
|
| 248 |
-
# Rooftop classification rules based on spectral characteristics
|
| 249 |
if (h <= 25 or h >= 160) and s > 35:
|
| 250 |
roof_type = "Tiled / Terracotta"
|
| 251 |
color = [220, 80, 50]
|
|
@@ -259,22 +360,19 @@ class VaayuSegmentationModel:
|
|
| 259 |
else:
|
| 260 |
roof_type = "Others"
|
| 261 |
color = [180, 140, 70]
|
| 262 |
-
|
| 263 |
rooftop_counts[roof_type] += 1
|
| 264 |
colored_classification_map[component_mask] = color
|
| 265 |
-
|
| 266 |
building_details.append({
|
| 267 |
"id": i,
|
| 268 |
"area_m2": round(area_m2, 2),
|
| 269 |
"roof_type": roof_type,
|
| 270 |
-
"centroid": (int(centroids[i][0]), int(centroids[i][1]))
|
| 271 |
})
|
| 272 |
|
| 273 |
-
# Solar Energy Calculation (150 kWh/m²/year for 75% usable RCC flat roof area)
|
| 274 |
usable_solar_m2 = rcc_area_m2 * 0.75
|
| 275 |
annual_solar_kwh = usable_solar_m2 * 150.0
|
| 276 |
-
|
| 277 |
-
# Property Tax Calculation (Panchayat rate: RCC=₹25/m², Tiled=₹15/m², Others=₹10/m²)
|
| 278 |
tax_inr = (rcc_area_m2 * 25.0) + ((total_area_m2 - rcc_area_m2) * 15.0)
|
| 279 |
|
| 280 |
return {
|
|
@@ -285,178 +383,128 @@ class VaayuSegmentationModel:
|
|
| 285 |
"annual_solar_kwh": round(annual_solar_kwh, 1),
|
| 286 |
"annual_property_tax_inr": round(tax_inr, 2),
|
| 287 |
"classification_map": colored_classification_map,
|
| 288 |
-
"building_details": building_details
|
| 289 |
}
|
| 290 |
-
|
| 291 |
def _create_overlay(self, image: np.ndarray, mask: np.ndarray, alpha: float = 0.55) -> np.ndarray:
|
| 292 |
-
"""
|
| 293 |
-
Create a crisp cartographic GIS blended overlay of mask and vector polygon outlines on original image.
|
| 294 |
-
"""
|
| 295 |
-
# Create base overlay
|
| 296 |
overlay = image.copy()
|
| 297 |
-
|
| 298 |
-
# Binary mask thresholding
|
| 299 |
binary = (mask > 127).astype(np.uint8)
|
| 300 |
-
|
| 301 |
if np.sum(binary) > 0:
|
| 302 |
-
# Color fill layer (muted olive-green for buildings)
|
| 303 |
color_fill = np.zeros_like(image)
|
| 304 |
-
color_fill[binary > 0] = [70, 180, 70]
|
| 305 |
-
|
| 306 |
-
# Semi-transparent blend
|
| 307 |
overlay = cv2.addWeighted(image, 1.0 - alpha, color_fill, alpha, 0)
|
| 308 |
-
|
| 309 |
-
# Find vector contours and draw crisp 1.5px boundary lines
|
| 310 |
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 311 |
cv2.drawContours(overlay, contours, -1, (240, 255, 240), 1, cv2.LINE_AA)
|
| 312 |
cv2.drawContours(overlay, contours, -1, (40, 200, 40), 1, cv2.LINE_AA)
|
| 313 |
-
|
| 314 |
return overlay
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
Splits the image into overlapping tiles, runs UNet++ on each,
|
| 323 |
-
and stitches probability maps with cosine distance weighting
|
| 324 |
-
to eliminate boundary seams.
|
| 325 |
-
|
| 326 |
-
Args:
|
| 327 |
-
image: RGB numpy array of any size
|
| 328 |
-
feature: Feature class to segment
|
| 329 |
-
tile_size: Size of each inference chip (default 512)
|
| 330 |
-
overlap: Overlap pixels between adjacent tiles (default 64)
|
| 331 |
-
threshold: Binarization threshold
|
| 332 |
-
|
| 333 |
-
Returns:
|
| 334 |
-
Stitched binary mask (uint8, 0 or 255) at original image resolution
|
| 335 |
-
"""
|
| 336 |
-
if feature not in self.models:
|
| 337 |
-
raise ValueError(f"Feature '{feature}' not available.")
|
| 338 |
-
|
| 339 |
-
model = self.models[feature]
|
| 340 |
h, w = image.shape[:2]
|
| 341 |
stride = tile_size - overlap
|
| 342 |
-
|
| 343 |
-
# If image fits in a single tile, run direct inference
|
| 344 |
-
if h <= tile_size and w <= tile_size:
|
| 345 |
-
resized = cv2.resize(image, (tile_size, tile_size))
|
| 346 |
-
tensor = torch.from_numpy(resized.astype(np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
| 347 |
-
with torch.no_grad():
|
| 348 |
-
pred = model(tensor).squeeze().cpu().numpy()
|
| 349 |
-
pred_full = cv2.resize(pred, (w, h))
|
| 350 |
-
return (pred_full > threshold).astype(np.uint8) * 255
|
| 351 |
-
|
| 352 |
-
# Build cosine blending weight map for each tile
|
| 353 |
ramp = np.ones(tile_size, dtype=np.float32)
|
| 354 |
if overlap > 0:
|
| 355 |
fade = np.linspace(0, 1, overlap, dtype=np.float32)
|
| 356 |
ramp[:overlap] = fade
|
| 357 |
ramp[-overlap:] = fade[::-1]
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
weight_map = np.outer(weight_1d_y, weight_1d_x) # (tile_size, tile_size)
|
| 361 |
-
|
| 362 |
-
# Accumulator arrays at original resolution
|
| 363 |
-
prob_accum = np.zeros((h, w), dtype=np.float64)
|
| 364 |
-
weight_accum = np.zeros((h, w), dtype=np.float64)
|
| 365 |
-
|
| 366 |
-
# Generate tile grid positions
|
| 367 |
y_positions = list(range(0, max(1, h - tile_size + 1), stride))
|
| 368 |
if y_positions[-1] + tile_size < h:
|
| 369 |
y_positions.append(h - tile_size)
|
| 370 |
-
|
| 371 |
x_positions = list(range(0, max(1, w - tile_size + 1), stride))
|
| 372 |
if x_positions[-1] + tile_size < w:
|
| 373 |
x_positions.append(w - tile_size)
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
f"({tile_size}px, {overlap}px overlap)")
|
| 378 |
-
|
| 379 |
-
# Collect all chips and their coordinates
|
| 380 |
-
chips_list = []
|
| 381 |
-
coords_list = []
|
| 382 |
for y0 in y_positions:
|
| 383 |
for x0 in x_positions:
|
| 384 |
-
chip = image[y0:y0+tile_size, x0:x0+tile_size]
|
| 385 |
ch, cw = chip.shape[:2]
|
| 386 |
if ch < tile_size or cw < tile_size:
|
| 387 |
padded = np.zeros((tile_size, tile_size, 3), dtype=np.uint8)
|
| 388 |
padded[:ch, :cw] = chip
|
| 389 |
chip = padded
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
with torch.no_grad():
|
| 398 |
-
for i in range(0, len(
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
if
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
weight_accum[weight_accum == 0] = 1.0
|
| 412 |
prob_map = prob_accum / weight_accum
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
binary_mask = (prob_map > threshold).astype(np.uint8) * 255
|
| 416 |
-
|
| 417 |
-
print(f" Batched sliding window ({batch_size}x parallel): {w}×{h}px stitched successfully")
|
| 418 |
-
return binary_mask
|
| 419 |
-
|
| 420 |
def predict_large(self, image_path: str, feature: str = "buildings",
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
Full
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
Args:
|
| 427 |
-
image_path: Path to input image (any size, including multi-hundred MB GeoTIFF)
|
| 428 |
-
feature: Feature class to segment
|
| 429 |
-
threshold: Binarization threshold
|
| 430 |
-
max_display: Maximum display dimension (for browser rendering)
|
| 431 |
-
|
| 432 |
-
Returns:
|
| 433 |
-
Same dict format as predict() for API compatibility
|
| 434 |
-
"""
|
| 435 |
-
if feature not in self.models:
|
| 436 |
-
raise ValueError(f"Feature '{feature}' not available. Available: {list(self.models.keys())}")
|
| 437 |
-
|
| 438 |
-
print(f" Loading image: {image_path}")
|
| 439 |
original_image = load_robust_image(image_path, max_dim=max_display)
|
| 440 |
h, w = original_image.shape[:2]
|
| 441 |
print(f" Image loaded: {w}×{h}px")
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
overlay = self._create_overlay(original_image, mask)
|
| 449 |
-
|
| 450 |
-
# Metrics
|
| 451 |
detected_pixels = int(np.sum(mask > 0))
|
| 452 |
total_pixels = int(mask.size)
|
| 453 |
detection_ratio = detected_pixels / total_pixels if total_pixels > 0 else 0
|
| 454 |
-
|
| 455 |
-
# Rooftop analysis for buildings
|
| 456 |
rooftop_analysis = None
|
| 457 |
if feature == "buildings" and detected_pixels > 0:
|
| 458 |
rooftop_analysis = self.classify_rooftops(original_image, mask)
|
| 459 |
-
|
| 460 |
return {
|
| 461 |
"original_image": original_image,
|
| 462 |
"mask": mask,
|
|
@@ -465,64 +513,48 @@ class VaayuSegmentationModel:
|
|
| 465 |
"detected_ratio": detection_ratio,
|
| 466 |
"detected_pixels": detected_pixels,
|
| 467 |
"total_pixels": total_pixels,
|
| 468 |
-
"rooftop_analysis": rooftop_analysis
|
| 469 |
}
|
| 470 |
-
|
| 471 |
def batch_predict(self, image_paths: list, feature: str = "buildings") -> list:
|
| 472 |
-
"""
|
| 473 |
-
Run inference on multiple images using sliding-window pipeline.
|
| 474 |
-
|
| 475 |
-
Args:
|
| 476 |
-
image_paths: List of image paths
|
| 477 |
-
feature: Feature to segment
|
| 478 |
-
|
| 479 |
-
Returns:
|
| 480 |
-
List of prediction results
|
| 481 |
-
"""
|
| 482 |
results = []
|
| 483 |
for image_path in image_paths:
|
| 484 |
try:
|
| 485 |
-
|
| 486 |
-
results.append(result)
|
| 487 |
except Exception as e:
|
| 488 |
print(f"Failed to process {image_path}: {e}")
|
| 489 |
results.append(None)
|
| 490 |
-
|
| 491 |
return results
|
| 492 |
|
| 493 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
def main():
|
| 495 |
-
"""Simple CLI test of the inference module."""
|
| 496 |
import argparse
|
| 497 |
-
|
| 498 |
-
parser = argparse.ArgumentParser(description="
|
| 499 |
parser.add_argument("image_path", help="Path to input image")
|
| 500 |
-
parser.add_argument("--feature", choices=["buildings", "roads", "water_bodies"],
|
| 501 |
-
|
| 502 |
-
parser.add_argument("--
|
| 503 |
-
parser.add_argument("--output_dir", default="inference_outputs", help="Output directory for results")
|
| 504 |
-
|
| 505 |
args = parser.parse_args()
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
# Run inference
|
| 511 |
-
result = model.predict(args.image_path, args.feature, args.threshold)
|
| 512 |
-
|
| 513 |
-
# Save outputs
|
| 514 |
output_dir = Path(args.output_dir)
|
| 515 |
output_dir.mkdir(exist_ok=True)
|
| 516 |
-
|
| 517 |
-
# Save mask
|
| 518 |
mask_path = output_dir / f"{Path(args.image_path).stem}_mask.png"
|
| 519 |
cv2.imwrite(str(mask_path), result["mask"])
|
| 520 |
-
|
| 521 |
-
# Save overlay
|
| 522 |
overlay_path = output_dir / f"{Path(args.image_path).stem}_overlay.png"
|
| 523 |
overlay_bgr = cv2.cvtColor(result["overlay"], cv2.COLOR_RGB2BGR)
|
| 524 |
cv2.imwrite(str(overlay_path), overlay_bgr)
|
| 525 |
-
|
| 526 |
print(f"\n✓ Inference complete for {args.feature}")
|
| 527 |
print(f" Detection ratio: {result['detected_ratio']:.2%}")
|
| 528 |
print(f" Detected pixels: {result['detected_pixels']}/{result['total_pixels']}")
|
|
@@ -531,4 +563,4 @@ def main():
|
|
| 531 |
|
| 532 |
|
| 533 |
if __name__ == "__main__":
|
| 534 |
-
main()
|
|
|
|
| 1 |
"""
|
| 2 |
+
Aerix Inference Module - SVAMITVA Feature Extraction
|
| 3 |
Performs building, road, and water body segmentation on orthophoto tiles using UNet++.
|
| 4 |
+
|
| 5 |
+
Fixed for ZeroGPU + large-TIFF stability:
|
| 6 |
+
1. Image loading uses rasterio windowed/decimated reads for GeoTIFFs, so a
|
| 7 |
+
multi-hundred-MB raster is never fully decoded into RAM just to be
|
| 8 |
+
downsampled. Falls back to PIL/OpenCV for ordinary PNG/JPG.
|
| 9 |
+
2. The pipeline is split into three explicit stages so app.py can keep the
|
| 10 |
+
CPU-only parts (file I/O, resizing, tiling, postprocessing) OUTSIDE the
|
| 11 |
+
@spaces.GPU-decorated function, and only the actual tensor->model->tensor
|
| 12 |
+
step inside it:
|
| 13 |
+
prepare_input() -> CPU
|
| 14 |
+
run_model() -> must run inside @spaces.GPU
|
| 15 |
+
postprocess() -> CPU
|
| 16 |
+
predict() / predict_large() still exist and just chain the three stages,
|
| 17 |
+
for local/non-ZeroGPU use (e.g. the CLI at the bottom of this file).
|
| 18 |
+
3. A cheap header-only size/dimension check (get_image_info) lets the caller
|
| 19 |
+
reject or route oversized uploads BEFORE attempting to open pixel data.
|
| 20 |
"""
|
| 21 |
|
| 22 |
import os
|
|
|
|
| 24 |
import cv2
|
| 25 |
import numpy as np
|
| 26 |
import torch
|
|
|
|
| 27 |
from pathlib import Path
|
| 28 |
import segmentation_models_pytorch as smp
|
| 29 |
+
from typing import Tuple, Dict, Optional, List
|
| 30 |
|
| 31 |
# Ensure UTF-8 output encoding for Windows consoles
|
| 32 |
if hasattr(sys.stdout, "reconfigure"):
|
|
|
|
| 35 |
except Exception:
|
| 36 |
pass
|
| 37 |
|
|
|
|
|
|
|
| 38 |
from PIL import Image
|
| 39 |
Image.MAX_IMAGE_PIXELS = None
|
| 40 |
|
| 41 |
+
try:
|
| 42 |
+
import rasterio
|
| 43 |
+
from rasterio.enums import Resampling as RioResampling
|
| 44 |
+
HAS_RASTERIO = True
|
| 45 |
+
except ImportError:
|
| 46 |
+
HAS_RASTERIO = False
|
| 47 |
+
|
| 48 |
_IMAGE_CACHE = {}
|
| 49 |
+
_CACHE_LIMIT = 8 # decimated images can still be several MB each; keep this small
|
| 50 |
|
| 51 |
+
# Hard ceiling on raw upload size. Tune to whatever your Space's hardware can
|
| 52 |
+
# actually hold in RAM alongside the model. Rejecting fast beats hanging.
|
| 53 |
+
MAX_UPLOAD_BYTES = 300 * 1024 * 1024 # 300 MB
|
| 54 |
|
| 55 |
+
|
| 56 |
+
def get_image_info(image_path: str) -> Dict:
|
| 57 |
"""
|
| 58 |
+
Header-only inspection — does NOT decode pixel data. Safe to call on a
|
| 59 |
+
multi-GB file. Used to size-gate uploads before touching pixels.
|
|
|
|
| 60 |
"""
|
| 61 |
+
size_bytes = os.path.getsize(image_path) if os.path.exists(image_path) else 0
|
| 62 |
+
width = height = None
|
| 63 |
+
|
| 64 |
+
if HAS_RASTERIO:
|
| 65 |
+
try:
|
| 66 |
+
with rasterio.open(image_path) as ds:
|
| 67 |
+
width, height = ds.width, ds.height
|
| 68 |
+
except Exception:
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
if width is None:
|
| 72 |
+
try:
|
| 73 |
+
with Image.open(image_path) as pil_img:
|
| 74 |
+
width, height = pil_img.size
|
| 75 |
+
except Exception:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
return {"size_bytes": size_bytes, "width": width, "height": height}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def validate_upload(image_path: str, max_bytes: int = MAX_UPLOAD_BYTES) -> None:
|
| 82 |
+
"""Raise a clean, fast error instead of letting a huge file hang the pipeline."""
|
| 83 |
+
info = get_image_info(image_path)
|
| 84 |
+
if info["size_bytes"] > max_bytes:
|
| 85 |
+
raise ValueError(
|
| 86 |
+
f"File is {info['size_bytes'] / 1e6:.0f} MB, which exceeds the "
|
| 87 |
+
f"{max_bytes / 1e6:.0f} MB limit for this Space. Please downsample "
|
| 88 |
+
f"or crop the orthophoto before uploading."
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
|
| 92 |
+
def _load_via_rasterio(image_path: str, max_dim: int) -> np.ndarray:
|
| 93 |
+
"""
|
| 94 |
+
Decimated read: asks GDAL to decode directly at (approximately) the target
|
| 95 |
+
resolution using its own overviews/decimation, so the full-resolution
|
| 96 |
+
raster is never materialized in RAM. This is the key fix for large
|
| 97 |
+
GeoTIFFs — PIL/OpenCV have no equivalent of this.
|
| 98 |
+
"""
|
| 99 |
+
with rasterio.open(image_path) as ds:
|
| 100 |
+
w, h = ds.width, ds.height
|
| 101 |
+
scale = min(1.0, max_dim / float(max(w, h))) if max(w, h) > max_dim else 1.0
|
| 102 |
+
out_w, out_h = max(1, int(w * scale)), max(1, int(h * scale))
|
| 103 |
+
|
| 104 |
+
band_count = min(ds.count, 3)
|
| 105 |
+
data = ds.read(
|
| 106 |
+
indexes=list(range(1, band_count + 1)),
|
| 107 |
+
out_shape=(band_count, out_h, out_w),
|
| 108 |
+
resampling=RioResampling.bilinear,
|
| 109 |
+
) # (bands, H, W)
|
| 110 |
+
|
| 111 |
+
data = np.transpose(data, (1, 2, 0)) # HWC
|
| 112 |
+
|
| 113 |
+
if data.dtype != np.uint8:
|
| 114 |
+
# Common with GeoTIFFs (uint16 / float reflectance). Normalize per-band
|
| 115 |
+
# to 8-bit for the RGB model input.
|
| 116 |
+
data = data.astype(np.float32)
|
| 117 |
+
for b in range(data.shape[-1]):
|
| 118 |
+
band = data[..., b]
|
| 119 |
+
lo, hi = np.percentile(band, (1, 99))
|
| 120 |
+
if hi > lo:
|
| 121 |
+
band = np.clip((band - lo) / (hi - lo), 0, 1) * 255.0
|
| 122 |
+
else:
|
| 123 |
+
band = np.zeros_like(band)
|
| 124 |
+
data[..., b] = band
|
| 125 |
+
data = data.astype(np.uint8)
|
| 126 |
+
|
| 127 |
+
if data.shape[-1] == 1:
|
| 128 |
+
data = np.repeat(data, 3, axis=-1)
|
| 129 |
+
elif data.shape[-1] > 3:
|
| 130 |
+
data = data[..., :3]
|
| 131 |
+
|
| 132 |
+
return np.ascontiguousarray(data)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _load_via_pil_or_cv2(image_path: str, max_dim: int) -> np.ndarray:
|
| 136 |
try:
|
|
|
|
| 137 |
with Image.open(image_path) as pil_img:
|
| 138 |
w, h = pil_img.size
|
| 139 |
if max(w, h) > max_dim:
|
| 140 |
scale = max_dim / float(max(w, h))
|
| 141 |
new_w, new_h = max(1, int(w * scale)), max(1, int(h * scale))
|
| 142 |
+
# draft() lets Pillow decode a smaller JPEG DCT block directly
|
| 143 |
+
# where supported; a no-op for formats that don't support it.
|
| 144 |
+
pil_img.draft("RGB", (new_w, new_h))
|
| 145 |
pil_img = pil_img.resize((new_w, new_h), Image.Resampling.BILINEAR)
|
|
|
|
| 146 |
if pil_img.mode != "RGB":
|
| 147 |
pil_img = pil_img.convert("RGB")
|
| 148 |
+
return np.array(pil_img)
|
| 149 |
except Exception:
|
|
|
|
| 150 |
image = cv2.imread(image_path)
|
| 151 |
+
if image is None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
raise ValueError(f"Cannot load image {image_path}. Ensure it is a valid PNG, JPG, or TIFF format.")
|
| 153 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 154 |
+
h, w = image.shape[:2]
|
| 155 |
+
if max(h, w) > max_dim:
|
| 156 |
+
scale = max_dim / float(max(h, w))
|
| 157 |
+
new_w, new_h = max(1, int(w * scale)), max(1, int(h * scale))
|
| 158 |
+
image = cv2.resize(image, (new_w, new_h))
|
| 159 |
+
return image
|
| 160 |
|
| 161 |
+
|
| 162 |
+
def load_robust_image(image_path: str, max_dim: int = 2048) -> np.ndarray:
|
| 163 |
+
"""
|
| 164 |
+
Robustly load any image format (PNG, JPG, TIFF, large GeoTIFF) as an RGB
|
| 165 |
+
numpy array, downsampled to max_dim on the longest side. For GeoTIFFs this
|
| 166 |
+
uses rasterio's decimated read (no full-res decode); everything else uses
|
| 167 |
+
PIL with draft-mode decoding, falling back to OpenCV.
|
| 168 |
+
"""
|
| 169 |
+
mtime = os.path.getmtime(image_path) if os.path.exists(image_path) else 0
|
| 170 |
+
cache_key = (str(image_path), max_dim, mtime)
|
| 171 |
+
if cache_key in _IMAGE_CACHE:
|
| 172 |
+
return _IMAGE_CACHE[cache_key].copy()
|
| 173 |
+
|
| 174 |
+
suffix = Path(image_path).suffix.lower()
|
| 175 |
+
result = None
|
| 176 |
+
|
| 177 |
+
if HAS_RASTERIO and suffix in (".tif", ".tiff"):
|
| 178 |
+
try:
|
| 179 |
+
result = _load_via_rasterio(image_path, max_dim)
|
| 180 |
+
except Exception as e:
|
| 181 |
+
print(f"rasterio read failed ({e}), falling back to PIL/OpenCV")
|
| 182 |
+
|
| 183 |
+
if result is None:
|
| 184 |
+
result = _load_via_pil_or_cv2(image_path, max_dim)
|
| 185 |
+
|
| 186 |
+
if len(_IMAGE_CACHE) >= _CACHE_LIMIT:
|
| 187 |
_IMAGE_CACHE.clear()
|
| 188 |
_IMAGE_CACHE[cache_key] = result
|
| 189 |
return result.copy()
|
| 190 |
|
| 191 |
|
| 192 |
+
class AerixSegmentationModel:
|
| 193 |
"""
|
| 194 |
Unified interface for SVAMITVA feature extraction using UNet++.
|
| 195 |
Supports buildings, roads, and water bodies segmentation.
|
| 196 |
+
|
| 197 |
+
Pipeline is split into three stages so the caller controls exactly what
|
| 198 |
+
runs under a ZeroGPU @spaces.GPU context:
|
| 199 |
+
prepare_input() — CPU only, safe to run with no GPU attached
|
| 200 |
+
run_model() — the only stage that needs CUDA
|
| 201 |
+
postprocess() — CPU only
|
| 202 |
"""
|
| 203 |
+
|
| 204 |
def __init__(self, models_dir: str = "models", device: str = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 206 |
self.models_dir = Path(models_dir)
|
| 207 |
self.models = {}
|
| 208 |
self.feature_names = ["buildings", "roads", "water_bodies"]
|
| 209 |
+
|
| 210 |
+
def _load_single_model(self, feature_name: str):
|
| 211 |
+
"""Load a single model on demand. Call this INSIDE the GPU context —
|
| 212 |
+
it's what does model.to('cuda') under ZeroGPU."""
|
| 213 |
+
if feature_name in self.models:
|
| 214 |
+
return self.models[feature_name]
|
| 215 |
+
|
| 216 |
+
model_path = self.models_dir / f"{feature_name}_unetpp_model.pth"
|
| 217 |
+
if not model_path.exists():
|
| 218 |
+
raise FileNotFoundError(f"Model weight file not found: {model_path}")
|
| 219 |
+
|
| 220 |
+
if len(self.models) > 0:
|
| 221 |
+
self.models.clear()
|
| 222 |
+
import gc
|
| 223 |
+
gc.collect()
|
| 224 |
+
if torch.cuda.is_available():
|
| 225 |
+
torch.cuda.empty_cache()
|
| 226 |
+
|
| 227 |
+
print(f"Loading {feature_name} model into RAM...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
try:
|
| 229 |
+
model = smp.UnetPlusPlus(
|
| 230 |
+
encoder_name="resnet34",
|
| 231 |
+
encoder_weights=None,
|
| 232 |
+
in_channels=3,
|
| 233 |
+
classes=1,
|
| 234 |
+
activation="sigmoid",
|
| 235 |
+
)
|
| 236 |
+
state_dict = torch.load(model_path, map_location=self.device, weights_only=True)
|
| 237 |
+
model.load_state_dict(state_dict)
|
| 238 |
+
model.to(self.device)
|
| 239 |
+
model.eval()
|
| 240 |
+
|
| 241 |
+
self.models[feature_name] = model
|
| 242 |
+
print(f"✓ Successfully loaded {feature_name} model")
|
| 243 |
+
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
except Exception as e:
|
| 245 |
+
print(f"✗ Failed to load {feature_name}: {e}")
|
| 246 |
+
raise e
|
| 247 |
+
|
| 248 |
+
# ------------------------------------------------------------------ #
|
| 249 |
+
# STAGE 1 — CPU only. Safe to call before a GPU is attached.
|
| 250 |
+
# ------------------------------------------------------------------ #
|
| 251 |
+
def prepare_input(self, image_path: str, target_size: Tuple[int, int] = (512, 512),
|
| 252 |
+
max_dim: int = 2048) -> Dict:
|
| 253 |
+
"""Load + downsample the image and build the normalized model input array."""
|
| 254 |
+
validate_upload(image_path)
|
| 255 |
+
original_image = load_robust_image(image_path, max_dim=max_dim)
|
| 256 |
+
|
| 257 |
+
resized = cv2.resize(original_image, (target_size[1], target_size[0]))
|
| 258 |
+
input_array = resized.astype(np.float32) / 255.0 # HWC, CPU numpy — no torch/cuda touched
|
| 259 |
+
|
| 260 |
+
return {"original_image": original_image, "input_array": input_array}
|
| 261 |
+
|
| 262 |
+
# ------------------------------------------------------------------ #
|
| 263 |
+
# STAGE 2 — the ONLY stage that needs CUDA. Wrap the caller of this
|
| 264 |
+
# (or this itself) in @spaces.GPU on ZeroGPU Spaces.
|
| 265 |
+
# ------------------------------------------------------------------ #
|
| 266 |
+
def run_model(self, feature: str, input_array: np.ndarray) -> np.ndarray:
|
| 267 |
+
"""input_array: HWC float32 [0,1]. Returns raw sigmoid output, HxW numpy."""
|
| 268 |
+
model = self._load_single_model(feature)
|
| 269 |
+
tensor = torch.from_numpy(input_array).permute(2, 0, 1).unsqueeze(0).to(self.device)
|
| 270 |
+
with torch.no_grad():
|
| 271 |
+
output = model(tensor)
|
| 272 |
+
raw = output.squeeze().detach().cpu().numpy()
|
| 273 |
+
del tensor, output
|
| 274 |
+
return raw
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------------ #
|
| 277 |
+
# STAGE 3 — CPU only.
|
| 278 |
+
# ------------------------------------------------------------------ #
|
| 279 |
+
def postprocess(self, original_image: np.ndarray, raw_output: np.ndarray,
|
| 280 |
+
feature: str, threshold: float = 0.5) -> Dict:
|
| 281 |
+
binary_mask = (raw_output > threshold).astype(np.uint8) * 255
|
| 282 |
+
if original_image.shape[:2] != binary_mask.shape:
|
| 283 |
+
binary_mask = cv2.resize(binary_mask, (original_image.shape[1], original_image.shape[0]))
|
| 284 |
+
|
| 285 |
+
overlay = self._create_overlay(original_image, binary_mask)
|
| 286 |
+
|
| 287 |
+
detected_pixels = int(np.sum(binary_mask > 0))
|
| 288 |
+
total_pixels = int(binary_mask.size)
|
| 289 |
+
detection_ratio = detected_pixels / total_pixels if total_pixels > 0 else 0
|
| 290 |
+
|
| 291 |
+
rooftop_analysis = None
|
| 292 |
+
if feature == "buildings" and detected_pixels > 0:
|
| 293 |
+
rooftop_analysis = self.classify_rooftops(original_image, binary_mask)
|
| 294 |
+
|
| 295 |
+
return {
|
| 296 |
+
"original_image": original_image,
|
| 297 |
+
"mask": binary_mask,
|
| 298 |
+
"overlay": overlay,
|
| 299 |
+
"feature": feature,
|
| 300 |
+
"detected_ratio": detection_ratio,
|
| 301 |
+
"detected_pixels": detected_pixels,
|
| 302 |
+
"total_pixels": total_pixels,
|
| 303 |
+
"rooftop_analysis": rooftop_analysis,
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
# ------------------------------------------------------------------ #
|
| 307 |
+
# Convenience wrapper for local / non-ZeroGPU use (CLI, tests). On a
|
| 308 |
+
# ZeroGPU Space, DO NOT call this from inside app.py — call the three
|
| 309 |
+
# stages separately so only run_model() sits inside @spaces.GPU.
|
| 310 |
+
# ------------------------------------------------------------------ #
|
| 311 |
+
def predict(self, image_path: str, feature: str = "buildings", threshold: float = 0.5) -> Dict:
|
| 312 |
+
prepped = self.prepare_input(image_path)
|
| 313 |
+
raw = self.run_model(feature, prepped["input_array"])
|
| 314 |
+
return self.postprocess(prepped["original_image"], raw, feature, threshold)
|
| 315 |
+
|
| 316 |
@staticmethod
|
| 317 |
def classify_rooftops(image: np.ndarray, mask: np.ndarray) -> Dict:
|
| 318 |
"""
|
| 319 |
+
Rooftop classification (RCC, Tiled, Tin, Others) on detected building
|
| 320 |
+
footprints, plus solar/tax estimates. Pure CPU/OpenCV — no GPU needed.
|
| 321 |
"""
|
| 322 |
hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
|
| 323 |
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats((mask > 0).astype(np.uint8))
|
| 324 |
+
|
| 325 |
rooftop_counts = {
|
| 326 |
"RCC / Concrete": 0,
|
| 327 |
"Tiled / Terracotta": 0,
|
| 328 |
"Tin / Metal Sheet": 0,
|
| 329 |
+
"Others": 0,
|
| 330 |
}
|
| 331 |
+
|
| 332 |
building_details = []
|
| 333 |
total_area_m2 = 0.0
|
| 334 |
rcc_area_m2 = 0.0
|
| 335 |
+
pixel_area_m2 = 0.25 # 50cm GSD -> 1 px = 0.25 m²
|
|
|
|
|
|
|
| 336 |
colored_classification_map = image.copy()
|
| 337 |
+
|
| 338 |
for i in range(1, num_labels):
|
| 339 |
area_px = stats[i, cv2.CC_STAT_AREA]
|
| 340 |
+
if area_px < 15:
|
| 341 |
continue
|
| 342 |
+
|
| 343 |
area_m2 = area_px * pixel_area_m2
|
| 344 |
total_area_m2 += area_m2
|
| 345 |
+
|
| 346 |
component_mask = (labels == i)
|
| 347 |
mean_hsv = cv2.mean(hsv, mask=component_mask.astype(np.uint8))
|
| 348 |
h, s, v = mean_hsv[0], mean_hsv[1], mean_hsv[2]
|
| 349 |
+
|
|
|
|
| 350 |
if (h <= 25 or h >= 160) and s > 35:
|
| 351 |
roof_type = "Tiled / Terracotta"
|
| 352 |
color = [220, 80, 50]
|
|
|
|
| 360 |
else:
|
| 361 |
roof_type = "Others"
|
| 362 |
color = [180, 140, 70]
|
| 363 |
+
|
| 364 |
rooftop_counts[roof_type] += 1
|
| 365 |
colored_classification_map[component_mask] = color
|
| 366 |
+
|
| 367 |
building_details.append({
|
| 368 |
"id": i,
|
| 369 |
"area_m2": round(area_m2, 2),
|
| 370 |
"roof_type": roof_type,
|
| 371 |
+
"centroid": (int(centroids[i][0]), int(centroids[i][1])),
|
| 372 |
})
|
| 373 |
|
|
|
|
| 374 |
usable_solar_m2 = rcc_area_m2 * 0.75
|
| 375 |
annual_solar_kwh = usable_solar_m2 * 150.0
|
|
|
|
|
|
|
| 376 |
tax_inr = (rcc_area_m2 * 25.0) + ((total_area_m2 - rcc_area_m2) * 15.0)
|
| 377 |
|
| 378 |
return {
|
|
|
|
| 383 |
"annual_solar_kwh": round(annual_solar_kwh, 1),
|
| 384 |
"annual_property_tax_inr": round(tax_inr, 2),
|
| 385 |
"classification_map": colored_classification_map,
|
| 386 |
+
"building_details": building_details,
|
| 387 |
}
|
| 388 |
+
|
| 389 |
def _create_overlay(self, image: np.ndarray, mask: np.ndarray, alpha: float = 0.55) -> np.ndarray:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
overlay = image.copy()
|
|
|
|
|
|
|
| 391 |
binary = (mask > 127).astype(np.uint8)
|
| 392 |
+
|
| 393 |
if np.sum(binary) > 0:
|
|
|
|
| 394 |
color_fill = np.zeros_like(image)
|
| 395 |
+
color_fill[binary > 0] = [70, 180, 70]
|
|
|
|
|
|
|
| 396 |
overlay = cv2.addWeighted(image, 1.0 - alpha, color_fill, alpha, 0)
|
| 397 |
+
|
|
|
|
| 398 |
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 399 |
cv2.drawContours(overlay, contours, -1, (240, 255, 240), 1, cv2.LINE_AA)
|
| 400 |
cv2.drawContours(overlay, contours, -1, (40, 200, 40), 1, cv2.LINE_AA)
|
| 401 |
+
|
| 402 |
return overlay
|
| 403 |
+
|
| 404 |
+
# ------------------------------------------------------------------ #
|
| 405 |
+
# Large-orthomosaic path: sliding window, split the same way.
|
| 406 |
+
# ------------------------------------------------------------------ #
|
| 407 |
+
def prepare_tiles(self, image: np.ndarray, tile_size: int = 512,
|
| 408 |
+
overlap: int = 64) -> Dict:
|
| 409 |
+
"""CPU only: build the chip batch + blending weight map. No CUDA."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
h, w = image.shape[:2]
|
| 411 |
stride = tile_size - overlap
|
| 412 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
ramp = np.ones(tile_size, dtype=np.float32)
|
| 414 |
if overlap > 0:
|
| 415 |
fade = np.linspace(0, 1, overlap, dtype=np.float32)
|
| 416 |
ramp[:overlap] = fade
|
| 417 |
ramp[-overlap:] = fade[::-1]
|
| 418 |
+
weight_map = np.outer(ramp, ramp)
|
| 419 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
y_positions = list(range(0, max(1, h - tile_size + 1), stride))
|
| 421 |
if y_positions[-1] + tile_size < h:
|
| 422 |
y_positions.append(h - tile_size)
|
|
|
|
| 423 |
x_positions = list(range(0, max(1, w - tile_size + 1), stride))
|
| 424 |
if x_positions[-1] + tile_size < w:
|
| 425 |
x_positions.append(w - tile_size)
|
| 426 |
+
|
| 427 |
+
chips = []
|
| 428 |
+
coords = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
for y0 in y_positions:
|
| 430 |
for x0 in x_positions:
|
| 431 |
+
chip = image[y0:y0 + tile_size, x0:x0 + tile_size]
|
| 432 |
ch, cw = chip.shape[:2]
|
| 433 |
if ch < tile_size or cw < tile_size:
|
| 434 |
padded = np.zeros((tile_size, tile_size, 3), dtype=np.uint8)
|
| 435 |
padded[:ch, :cw] = chip
|
| 436 |
chip = padded
|
| 437 |
+
chips.append(chip.astype(np.float32) / 255.0)
|
| 438 |
+
coords.append((y0, x0, min(tile_size, h - y0), min(tile_size, w - x0)))
|
| 439 |
+
|
| 440 |
+
print(f" Sliding window: {len(y_positions)}×{len(x_positions)} = {len(chips)} tiles "
|
| 441 |
+
f"({tile_size}px, {overlap}px overlap)")
|
| 442 |
+
|
| 443 |
+
return {"chips": chips, "coords": coords, "weight_map": weight_map,
|
| 444 |
+
"image_shape": (h, w)}
|
| 445 |
+
|
| 446 |
+
def run_model_tiles(self, feature: str, chips: List[np.ndarray],
|
| 447 |
+
batch_size: Optional[int] = None) -> List[np.ndarray]:
|
| 448 |
+
"""The only CUDA-touching part of the large-image path."""
|
| 449 |
+
model = self._load_single_model(feature)
|
| 450 |
+
batch_size = batch_size or (4 if self.device == "cpu" else 16)
|
| 451 |
+
|
| 452 |
+
preds: List[np.ndarray] = []
|
| 453 |
with torch.no_grad():
|
| 454 |
+
for i in range(0, len(chips), batch_size):
|
| 455 |
+
batch = np.stack(chips[i:i + batch_size]) # (B, H, W, C)
|
| 456 |
+
tensor = torch.from_numpy(batch).permute(0, 3, 1, 2).to(self.device)
|
| 457 |
+
out = model(tensor).squeeze(1).detach().cpu().numpy()
|
| 458 |
+
if out.ndim == 2:
|
| 459 |
+
out = np.expand_dims(out, 0)
|
| 460 |
+
preds.extend(list(out))
|
| 461 |
+
del tensor, out
|
| 462 |
+
return preds
|
| 463 |
+
|
| 464 |
+
def stitch_tiles(self, preds: List[np.ndarray], coords, weight_map,
|
| 465 |
+
image_shape, threshold: float = 0.5) -> np.ndarray:
|
| 466 |
+
"""CPU only: blend overlapping tile predictions into one mask."""
|
| 467 |
+
h, w = image_shape
|
| 468 |
+
prob_accum = np.zeros((h, w), dtype=np.float64)
|
| 469 |
+
weight_accum = np.zeros((h, w), dtype=np.float64)
|
| 470 |
+
|
| 471 |
+
for pred, (y0, x0, ah, aw) in zip(preds, coords):
|
| 472 |
+
prob_accum[y0:y0 + ah, x0:x0 + aw] += pred[:ah, :aw] * weight_map[:ah, :aw]
|
| 473 |
+
weight_accum[y0:y0 + ah, x0:x0 + aw] += weight_map[:ah, :aw]
|
| 474 |
+
|
| 475 |
weight_accum[weight_accum == 0] = 1.0
|
| 476 |
prob_map = prob_accum / weight_accum
|
| 477 |
+
return (prob_map > threshold).astype(np.uint8) * 255
|
| 478 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
def predict_large(self, image_path: str, feature: str = "buildings",
|
| 480 |
+
threshold: float = 0.5, max_display: int = 2048,
|
| 481 |
+
tile_size: int = 512, overlap: int = 64) -> Dict:
|
| 482 |
+
"""Full large-orthomosaic pipeline, chaining the split stages (local/CLI use)."""
|
| 483 |
+
validate_upload(image_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 484 |
original_image = load_robust_image(image_path, max_dim=max_display)
|
| 485 |
h, w = original_image.shape[:2]
|
| 486 |
print(f" Image loaded: {w}×{h}px")
|
| 487 |
+
|
| 488 |
+
if h <= tile_size and w <= tile_size:
|
| 489 |
+
resized = cv2.resize(original_image, (tile_size, tile_size))
|
| 490 |
+
raw = self.run_model(feature, resized.astype(np.float32) / 255.0)
|
| 491 |
+
raw_full = cv2.resize(raw, (w, h))
|
| 492 |
+
return self.postprocess(original_image, raw_full, feature, threshold)
|
| 493 |
+
|
| 494 |
+
tiles = self.prepare_tiles(original_image, tile_size, overlap)
|
| 495 |
+
preds = self.run_model_tiles(feature, tiles["chips"])
|
| 496 |
+
mask = self.stitch_tiles(preds, tiles["coords"], tiles["weight_map"],
|
| 497 |
+
tiles["image_shape"], threshold)
|
| 498 |
+
|
| 499 |
overlay = self._create_overlay(original_image, mask)
|
|
|
|
|
|
|
| 500 |
detected_pixels = int(np.sum(mask > 0))
|
| 501 |
total_pixels = int(mask.size)
|
| 502 |
detection_ratio = detected_pixels / total_pixels if total_pixels > 0 else 0
|
| 503 |
+
|
|
|
|
| 504 |
rooftop_analysis = None
|
| 505 |
if feature == "buildings" and detected_pixels > 0:
|
| 506 |
rooftop_analysis = self.classify_rooftops(original_image, mask)
|
| 507 |
+
|
| 508 |
return {
|
| 509 |
"original_image": original_image,
|
| 510 |
"mask": mask,
|
|
|
|
| 513 |
"detected_ratio": detection_ratio,
|
| 514 |
"detected_pixels": detected_pixels,
|
| 515 |
"total_pixels": total_pixels,
|
| 516 |
+
"rooftop_analysis": rooftop_analysis,
|
| 517 |
}
|
| 518 |
+
|
| 519 |
def batch_predict(self, image_paths: list, feature: str = "buildings") -> list:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
results = []
|
| 521 |
for image_path in image_paths:
|
| 522 |
try:
|
| 523 |
+
results.append(self.predict_large(image_path, feature))
|
|
|
|
| 524 |
except Exception as e:
|
| 525 |
print(f"Failed to process {image_path}: {e}")
|
| 526 |
results.append(None)
|
|
|
|
| 527 |
return results
|
| 528 |
|
| 529 |
|
| 530 |
+
# Backward compatibility aliases
|
| 531 |
+
GramDrishtiSegmentationModel = AerixSegmentationModel
|
| 532 |
+
VaayuSegmentationModel = AerixSegmentationModel
|
| 533 |
+
|
| 534 |
+
|
| 535 |
def main():
|
|
|
|
| 536 |
import argparse
|
| 537 |
+
|
| 538 |
+
parser = argparse.ArgumentParser(description="Aerix Segmentation Inference")
|
| 539 |
parser.add_argument("image_path", help="Path to input image")
|
| 540 |
+
parser.add_argument("--feature", choices=["buildings", "roads", "water_bodies"], default="buildings")
|
| 541 |
+
parser.add_argument("--threshold", type=float, default=0.5)
|
| 542 |
+
parser.add_argument("--output_dir", default="inference_outputs")
|
|
|
|
|
|
|
| 543 |
args = parser.parse_args()
|
| 544 |
+
|
| 545 |
+
model = AerixSegmentationModel()
|
| 546 |
+
result = model.predict_large(args.image_path, args.feature, args.threshold)
|
| 547 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
output_dir = Path(args.output_dir)
|
| 549 |
output_dir.mkdir(exist_ok=True)
|
| 550 |
+
|
|
|
|
| 551 |
mask_path = output_dir / f"{Path(args.image_path).stem}_mask.png"
|
| 552 |
cv2.imwrite(str(mask_path), result["mask"])
|
| 553 |
+
|
|
|
|
| 554 |
overlay_path = output_dir / f"{Path(args.image_path).stem}_overlay.png"
|
| 555 |
overlay_bgr = cv2.cvtColor(result["overlay"], cv2.COLOR_RGB2BGR)
|
| 556 |
cv2.imwrite(str(overlay_path), overlay_bgr)
|
| 557 |
+
|
| 558 |
print(f"\n✓ Inference complete for {args.feature}")
|
| 559 |
print(f" Detection ratio: {result['detected_ratio']:.2%}")
|
| 560 |
print(f" Detected pixels: {result['detected_pixels']}/{result['total_pixels']}")
|
|
|
|
| 563 |
|
| 564 |
|
| 565 |
if __name__ == "__main__":
|
| 566 |
+
main()
|