Spaces:
Build error
Build error
Download sam.py from Noursine2025/Sam_obstacles: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/spaces/Noursine2025/Sam_obstacles/resolve/main/sam.py
- Command line
-
hf download hf://spaces/Noursine2025/Sam_obstacles/sam.py
-
curl -L -o sam.py https://huggingface.co/spaces/Noursine2025/Sam_obstacles/resolve/main/sam.py
5.86 kB
| # =============================== | |
| # rooftop_obstacle_detection_obstacles_only.py | |
| # =============================== | |
| import io | |
| import os | |
| import base64 | |
| import random | |
| import cv2 | |
| import numpy as np | |
| from fastapi import FastAPI, UploadFile, File | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse | |
| from inference_sdk import InferenceHTTPClient | |
| from PIL import Image, ImageDraw | |
| # ------------------------------- | |
| # Model setup (Roboflow) | |
| # ------------------------------- | |
| MODEL_API_KEY = os.environ.get("API_KEY") | |
| MODEL_API_URL = "https://serverless.roboflow.com" | |
| MODEL_ID = "gable_rectangular_rooftop-p9ose/2" | |
| if not MODEL_API_KEY: | |
| raise ValueError("MODEL_API_KEY not set") | |
| CLIENT = InferenceHTTPClient(api_key=MODEL_API_KEY, api_url=MODEL_API_URL) | |
| # ------------------------------- | |
| # SAM2 imports | |
| # ------------------------------- | |
| from sam2.build_sam import build_sam2 | |
| from sam2.automatic_mask_generator import SAM2AutomaticMaskGenerator | |
| from hydra import initialize | |
| from hydra.core.global_hydra import GlobalHydra | |
| # ------------------------------- | |
| # Load SAM2 model (CPU) | |
| # ------------------------------- | |
| if GlobalHydra.instance().is_initialized(): | |
| GlobalHydra.instance().clear() | |
| with initialize(version_base=None, config_path="segment-anything-2/sam2/configs"): | |
| sam2_model = build_sam2( | |
| "sam2.1/sam2.1_hiera_l", | |
| "sam2.1_hiera_large.pt", | |
| device="cpu" | |
| ) | |
| mask_generator = SAM2AutomaticMaskGenerator( | |
| sam2_model, | |
| points_per_side=16, | |
| pred_iou_thresh=0.5, # lower to detect tiny obstacles | |
| stability_score_thresh=0.5 | |
| ) | |
| # ------------------------------- | |
| # FastAPI app | |
| # ------------------------------- | |
| app = FastAPI( | |
| title="Rooftop Obstacle Detection", | |
| description="Detect rooftop obstacles using Roboflow + SAM2", | |
| version="1.0" | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"] | |
| ) | |
| def root(): | |
| return { | |
| "status": "running", | |
| "message": "Rooftop Obstacle Detection API", | |
| "note": "POST an image to /process/" | |
| } | |
| # ------------------------------- | |
| # Helper functions | |
| # ------------------------------- | |
| def resize_image(image: Image.Image, max_size=1024) -> Image.Image: | |
| w, h = image.size | |
| if max(w, h) <= max_size: | |
| return image | |
| if w > h: | |
| h = int(h * max_size / w) | |
| w = max_size | |
| else: | |
| w = int(w * max_size / h) | |
| h = max_size | |
| return image.resize((w, h), Image.ANTIALIAS) | |
| def generate_rooftop_mask(image: Image.Image) -> np.ndarray: | |
| img_np = np.array(image) | |
| result = CLIENT.infer(img_np, model_id=MODEL_ID) | |
| mask = Image.new("L", image.size, 0) | |
| draw = ImageDraw.Draw(mask) | |
| for pred in result.get("predictions", []): | |
| points = [(p["x"], p["y"]) for p in pred["points"]] | |
| draw.polygon(points, fill=255) | |
| return np.array(mask) | |
| def get_rooftop_boundary(rooftop_mask: np.ndarray): | |
| contours, _ = cv2.findContours( | |
| rooftop_mask.astype(np.uint8), | |
| cv2.RETR_EXTERNAL, | |
| cv2.CHAIN_APPROX_SIMPLE | |
| ) | |
| return max(contours, key=cv2.contourArea) | |
| def generate_obstacle_overlay(image: Image.Image, rooftop_mask: np.ndarray): | |
| img_np = np.array(image) | |
| overlay = img_np.copy() | |
| sam_masks = mask_generator.generate(img_np) | |
| obstacle_polygons = [] | |
| rooftop_boundary = get_rooftop_boundary(rooftop_mask) | |
| for m in sam_masks: | |
| seg = np.logical_and(m["segmentation"], rooftop_mask > 0) | |
| if seg.sum() == 0: | |
| continue | |
| seg_uint8 = (seg * 255).astype(np.uint8) | |
| contours, _ = cv2.findContours(seg_uint8, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| for cnt in contours: | |
| area = cv2.contourArea(cnt) | |
| if area < 10: # remove noise | |
| continue | |
| # Reject any segment touching rooftop boundary | |
| touches_boundary = False | |
| for point in cnt.reshape(-1, 2): | |
| dist = cv2.pointPolygonTest( | |
| rooftop_boundary, | |
| (int(point[0]), int(point[1])), | |
| measureDist=True | |
| ) | |
| if dist <= 2: # near boundary | |
| touches_boundary = True | |
| break | |
| if touches_boundary: | |
| continue | |
| # ✅ True obstacle detected | |
| epsilon = 0.01 * cv2.arcLength(cnt, True) | |
| poly = cv2.approxPolyDP(cnt, epsilon, True) | |
| # Generate random color for this obstacle (cute touch!) | |
| color = tuple([random.randint(50, 255) for _ in range(3)]) | |
| mask_layer = overlay.copy() | |
| cv2.fillPoly(mask_layer, [poly], color) | |
| overlay = cv2.addWeighted(mask_layer, 0.4, overlay, 0.6, 0) | |
| cv2.polylines(overlay, [poly], True, color, 1) | |
| obstacle_polygons.append(poly.reshape(-1, 2).tolist()) | |
| return overlay, obstacle_polygons | |
| def encode_overlay_image(overlay: np.ndarray) -> str: | |
| buf = io.BytesIO() | |
| Image.fromarray(overlay).save(buf, format="JPEG", quality=85) | |
| return base64.b64encode(buf.getvalue()).decode() | |
| # ------------------------------- | |
| # API endpoint | |
| # ------------------------------- | |
| async def process_image_endpoint(file: UploadFile = File(...)): | |
| image_bytes = await file.read() | |
| image = Image.open(io.BytesIO(image_bytes)).convert("RGB") | |
| image = resize_image(image, max_size=1024) | |
| rooftop_mask = generate_rooftop_mask(image) | |
| overlay, polygons = generate_obstacle_overlay(image, rooftop_mask) | |
| overlay_b64 = encode_overlay_image(overlay) | |
| return JSONResponse({ | |
| "num_obstacles": len(polygons), | |
| "overlay_base64": overlay_b64, | |
| "obstacle_polygons": polygons | |
| }) | |