""" Room segmentation backend using SAM AutomaticMaskGenerator + SegFormer. This "Paint-by-Numbers" pipeline ensures perfectly straight geometric edges from SAM, while retaining the accurate semantic understanding from SegFormer. """ import base64 import json import os import sys import cv2 import numpy as np import torch from PIL import Image try: from dotenv import load_dotenv load_dotenv(os.path.join(os.path.dirname(__file__), '..', '.env.local')) except ImportError: pass try: from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor from segment_anything import sam_model_registry, SamAutomaticMaskGenerator except ImportError: print(json.dumps({"error": "transformers or segment_anything not installed"})) sys.exit(1) # ADE20K target labels mapped to surface types. # Note: 'door' and 'window' are removed as per user requirements. ADE_SURFACE_MAP = { 0: ("wall", True), 3: ("floor", False), 5: ("ceiling", False), 10: ("cabinet", True), 14: ("door", True), # Re-enable door per user request 22: ("painting", True), # Exclude from wall, treat as separate object 24: ("shelf", True), 27: ("mirror", True), 28: ("rug", True), 35: ("wardrobe", True), 36: ("poster", True), # Exclude from wall, treat as separate object 45: ("vanity", True), 70: ("countertop", True), 73: ("island", True), 82: ("light", True), } MIN_AREA_FRACTION = { "wall": 0.001, "floor": 0.005, "ceiling": 0.002, "cabinet": 0.002, "door": 0.001, "painting": 0.001, "shelf": 0.001, "mirror": 0.001, "rug": 0.002, "wardrobe": 0.001, # Decreased to detect much smaller wardrobes "poster": 0.001, "vanity": 0.002, "countertop": 0.002, "island": 0.002, "light": 0.001, } def load_image(path, max_dim=768): img = cv2.imread(path) if img is None: return None, None, None img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) orig_h, orig_w = img.shape[:2] if max(orig_h, orig_w) > max_dim: scale = max_dim / max(orig_h, orig_w) new_w = int(orig_w * scale) new_h = int(orig_h * scale) img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA) return img, orig_w, orig_h def get_device(): if torch.cuda.is_available(): return "cuda" if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): return "mps" return "cpu" def get_semantic_map(image_np, device): # Use half-precision (fp16) for massive speedups and memory reduction on GPU/MPS dtype = torch.float16 if device in ["cuda", "mps"] else torch.float32 model_name = "nvidia/segformer-b5-finetuned-ade-640-640" processor = SegformerImageProcessor.from_pretrained(model_name) model = SegformerForSemanticSegmentation.from_pretrained(model_name, torch_dtype=dtype).to(device) # Scale down for SegFormer since it operates semantically at lower res # This massively speeds up the SegFormer pass without affecting final edge quality h, w = image_np.shape[:2] scale_seg = 640 / max(h, w) if max(h, w) > 640 else 1.0 seg_w, seg_h = int(w * scale_seg), int(h * scale_seg) img_seg = cv2.resize(image_np, (seg_w, seg_h), interpolation=cv2.INTER_AREA) inputs = processor(images=Image.fromarray(img_seg), return_tensors="pt").to(device) if dtype == torch.float16: inputs["pixel_values"] = inputs["pixel_values"].to(dtype) with torch.inference_mode(): outputs = model(**inputs) logits = outputs.logits # Upsample to the exact resolution of the SAM input image upsampled_logits = torch.nn.functional.interpolate( logits, size=(h, w), mode="bilinear", align_corners=False ) pred_labels = upsampled_logits.argmax(dim=1)[0] return pred_labels.cpu().numpy() def initialize_sam(device, points_per_side=32): checkpoint = os.getenv("SAM_CHECKPOINT", "/app/models/sam_vit_b_01ec64.pth") model_type = os.getenv("SAM_MODEL_TYPE", "vit_b") if not checkpoint or not os.path.exists(checkpoint): raise FileNotFoundError(f"SAM checkpoint not found at {checkpoint}. Please check .env.local") sam = sam_model_registry[model_type](checkpoint=checkpoint) # SAM AutomaticMaskGenerator has float64 operations which crash on MPS. # We must force it to CPU on Apple Silicon. sam_device = "cpu" if device == "mps" else device sam.to(device=sam_device) # Use AutomaticMaskGenerator for full-image crisp geometric segmentation return SamAutomaticMaskGenerator( model=sam, points_per_side=points_per_side, pred_iou_thresh=0.86, # Stricter threshold ensures crisper edge quality stability_score_thresh=0.90, # Higher stability reduces hallucinated masks crop_n_layers=0, min_mask_region_area=50, # Drop to 50 pixels to capture very tiny wall slivers ) def mask_to_base64(mask_np): rgba = np.zeros((mask_np.shape[0], mask_np.shape[1], 4), dtype=np.uint8) rgba[:, :, 0] = 255 rgba[:, :, 1] = 255 rgba[:, :, 2] = 255 rgba[:, :, 3] = mask_np _, buffer = cv2.imencode(".png", rgba) encoded = base64.b64encode(buffer).decode("utf-8") return f"data:image/png;base64,{encoded}" def compute_centroid(mask_bool, img_h, img_w): ys, xs = np.where(mask_bool) if len(xs) == 0: return None return [float(np.mean(xs)) / img_w, float(np.mean(ys)) / img_h] def process_image(input_path): device = get_device() diagnostics = [f"Device: {device}"] # Dynamic scaling: Free CPU containers are incredibly slow. # Drop resolution and grid density to avoid 300s timeouts on CPUs. is_fast_device = device in ["cuda", "mps"] max_dim = 896 if is_fast_device else 512 sam_points = 48 if is_fast_device else 24 img, orig_w, orig_h = load_image(input_path, max_dim) if img is None: return {"error": "Failed to load image"} img_h, img_w = img.shape[:2] total_pixels = img_h * img_w try: # 1. Get exact geometric boundaries from SAM diagnostics.append(f"Running SAM AutomaticMaskGenerator (points={sam_points})...") mask_generator = initialize_sam(device, sam_points) sam_masks = mask_generator.generate(img) diagnostics.append(f"SAM generated {len(sam_masks)} crisp geometric fragments.") # 2. Get rough semantic map from SegFormer diagnostics.append("Running SegFormer for semantic context...") semantic_map = get_semantic_map(img, device) # 3. Paint-by-Numbers: Assign each SAM fragment to the majority SegFormer class # using Smallest-First Assignment to preserve crisp foreground details diagnostics.append("Merging geometric fragments with semantic context...") accumulated_class_masks = {ade_id: np.zeros((img_h, img_w), dtype=bool) for ade_id in ADE_SURFACE_MAP.keys()} # Track pixels that have already been definitively assigned to a mask assigned_pixels = np.zeros((img_h, img_w), dtype=bool) # Sort SAM masks from smallest to largest sam_masks_sorted = sorted(sam_masks, key=lambda x: x['area']) for sam_mask_data in sam_masks_sorted: m_bool = sam_mask_data['segmentation'] # Extract only the pixels that haven't been claimed by a smaller, more specific mask valid_pixels = m_bool & ~assigned_pixels if not np.any(valid_pixels): continue # Find the semantic majority using the WHOLE mask (for context confidence), # but we only ASSIGN the valid_pixels. semantic_pixels = semantic_map[m_bool] if len(semantic_pixels) == 0: continue counts = np.bincount(semantic_pixels) majority_class = int(np.argmax(counts)) # We assign to any majority class (even if not in our target map) to reserve the pixels! assigned_pixels |= valid_pixels if majority_class in accumulated_class_masks: accumulated_class_masks[majority_class] |= valid_pixels # Semantic fallback layer: Assign any unassigned pixels directly using the blurry SegFormer map # This acts as a safety net for regions SAM missed entirely unassigned_pixels = ~assigned_pixels if np.any(unassigned_pixels): for ade_id in accumulated_class_masks.keys(): fallback_mask = unassigned_pixels & (semantic_map == ade_id) accumulated_class_masks[ade_id] |= fallback_mask masks = {} result_centroids = {} surface_types = {} for ade_id, (surface_type, multi_instance) in ADE_SURFACE_MAP.items(): surface_bool = accumulated_class_masks[ade_id] min_area = MIN_AREA_FRACTION.get(surface_type, 0.005) * total_pixels if np.sum(surface_bool) < min_area: continue def process_segment(seg_mask_bool, key_name): # The mask is already perfectly crisp from SAM, just resize it to the original image dimensions # with INTER_NEAREST to avoid blurring the razor-sharp edges. mask_np = seg_mask_bool.astype(np.uint8) * 255 if orig_w != img_w or orig_h != img_h: mask_np = cv2.resize(mask_np, (orig_w, orig_h), interpolation=cv2.INTER_NEAREST) # Apply a micro-feather so it blends perfectly in the HTML canvas mask_np = cv2.GaussianBlur(mask_np, (3, 3), 0) masks[key_name] = mask_to_base64(mask_np) centroid = compute_centroid(mask_np > 127, orig_h, orig_w) if centroid: result_centroids[key_name] = centroid surface_types[key_name] = surface_type if multi_instance: # Use connected components to separate disconnected instances of the same class (e.g. two separate walls) surface_np = surface_bool.astype(np.uint8) * 255 # Use a gentle MORPH_CLOSE to merge micro-fractures without shrinking the mask surface_np = cv2.morphologyEx(surface_np, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)) num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(surface_np, connectivity=8) areas = [(i, stats[i, cv2.CC_STAT_AREA]) for i in range(1, num_labels)] areas.sort(key=lambda x: x[1], reverse=True) count = 0 for comp_idx, area in areas: if area < min_area: continue count += 1 mask_key = surface_type if count == 1 and len([a for _, a in areas if a >= min_area]) == 1 else f"{surface_type}_{count}" comp_bool = labels == comp_idx process_segment(comp_bool, mask_key) else: process_segment(surface_bool, surface_type) diagnostics.append(f"Total: {len(masks)} high-precision architectural mask(s) finalized.") return { "source": "sam+segformer_generator", "width": orig_w, "height": orig_h, "diagnostics": diagnostics, "masks": masks, "centroids": result_centroids, "surface_types": surface_types, } except Exception as e: import traceback with open("/tmp/sam_error.txt", "w") as f: f.write(traceback.format_exc()) return {"error": str(e), "diagnostics": diagnostics} if __name__ == "__main__": if len(sys.argv) < 2: print(json.dumps({"error": "Missing input image path"})) sys.exit(1) print(json.dumps(process_image(sys.argv[1])))