Download services/floor/sam_refinement.py from modventures/floor-visualizer-gpu: direct link, hf CLI and curl.
- Browser
- Download file 4.79 kB
-
https://huggingface.co/spaces/modventures/floor-visualizer-gpu/resolve/main/services/floor/sam_refinement.py
- Command line
-
hf download hf://spaces/modventures/floor-visualizer-gpu/services/floor/sam_refinement.py
-
curl -L -o sam_refinement.py https://huggingface.co/spaces/modventures/floor-visualizer-gpu/resolve/main/services/floor/sam_refinement.py
4.79 kB
| """SAM2-based floor mask refinement. | |
| Functions | |
| --------- | |
| sample_prompt_points - sample positive/negative prompt points from a mask | |
| refine_floor_mask_with_sam2 - refine a floor mask using SAM2 predictions | |
| """ | |
| import cv2 | |
| import numpy as np | |
| from config.runtime import ENABLE_SAM_REFINEMENT | |
| from config.surface import SURFACE_MIN_PLANE_PIXELS | |
| from models.loader import _load_sam2_predictor | |
| from services.floor.mask import clean_floor_mask | |
| from utils import seg_class_mask | |
| from state import ( | |
| OCCLUDER_CLASSES, | |
| REJECT_SURFACE_CLASSES, | |
| class_ids, | |
| ) | |
| def sample_prompt_points(mask: np.ndarray, count: int, positive: bool) -> list[list[float]]: | |
| ys, xs = np.where(mask > 0) | |
| if len(xs) == 0: | |
| return [] | |
| if positive: | |
| step = max(1, len(xs) // max(count, 1)) | |
| order = np.argsort(np.abs(ys - np.median(ys)) + np.abs(xs - np.median(xs))) | |
| chosen = order[::step][:count] | |
| else: | |
| step = max(1, len(xs) // max(count, 1)) | |
| chosen = np.arange(0, len(xs), step)[:count] | |
| return [[float(xs[i]), float(ys[i])] for i in chosen] | |
| def refine_floor_mask_with_sam2( | |
| img_np: np.ndarray, | |
| floor_mask: np.ndarray, | |
| seg_map: np.ndarray, | |
| ) -> tuple[np.ndarray, dict]: | |
| metadata = { | |
| "samRefinementEnabled": ENABLE_SAM_REFINEMENT, | |
| "samRefinementApplied": False, | |
| "samRefinementReason": "disabled" if not ENABLE_SAM_REFINEMENT else "unavailable", | |
| "samRefinementScore": None, | |
| } | |
| if not ENABLE_SAM_REFINEMENT or int(floor_mask.sum()) < SURFACE_MIN_PLANE_PIXELS: | |
| return floor_mask, metadata | |
| predictor = _load_sam2_predictor() | |
| if predictor is None: | |
| return floor_mask, metadata | |
| ys, xs = np.where(floor_mask > 0) | |
| if len(xs) == 0: | |
| metadata["samRefinementReason"] = "empty-floor-mask" | |
| return floor_mask, metadata | |
| h, w = floor_mask.shape[:2] | |
| pad = max(4, min(h, w) // 80) | |
| box = np.array([ | |
| max(0, int(xs.min()) - pad), | |
| max(0, int(ys.min()) - pad), | |
| min(w - 1, int(xs.max()) + pad), | |
| min(h - 1, int(ys.max()) + pad), | |
| ], dtype=np.float32) | |
| positive_mask = cv2.erode( | |
| floor_mask.astype(np.uint8), | |
| cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)), | |
| iterations=1, | |
| ) | |
| reject_mask = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES | OCCLUDER_CLASSES)) | |
| negative_mask = cv2.dilate( | |
| reject_mask, | |
| cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)), | |
| iterations=1, | |
| ) | |
| positive_points = sample_prompt_points(positive_mask, 4, positive=True) | |
| negative_points = sample_prompt_points(negative_mask, 6, positive=False) | |
| point_coords = np.asarray(positive_points + negative_points, dtype=np.float32) | |
| point_labels = np.asarray( | |
| [1] * len(positive_points) + [0] * len(negative_points), | |
| dtype=np.int32, | |
| ) | |
| try: | |
| predictor.set_image(img_np) | |
| masks, scores, _ = predictor.predict( | |
| point_coords=point_coords if len(point_coords) else None, | |
| point_labels=point_labels if len(point_labels) else None, | |
| box=box, | |
| multimask_output=True, | |
| ) | |
| except Exception as exc: | |
| metadata["samRefinementReason"] = f"predict-failed:{exc}" | |
| return floor_mask, metadata | |
| if masks is None or len(masks) == 0: | |
| metadata["samRefinementReason"] = "no-mask" | |
| return floor_mask, metadata | |
| best_idx = int(np.argmax(scores)) if scores is not None and len(scores) else 0 | |
| sam_mask = masks[best_idx].astype(np.uint8) | |
| if sam_mask.shape[:2] != floor_mask.shape: | |
| sam_mask = cv2.resize(sam_mask, (w, h), interpolation=cv2.INTER_NEAREST) | |
| reject_dilated = cv2.dilate( | |
| reject_mask, | |
| cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)), | |
| iterations=1, | |
| ) | |
| floor_dilated = cv2.dilate( | |
| floor_mask.astype(np.uint8), | |
| cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (max(5, min(h, w) // 80) | 1,) * 2), | |
| iterations=2, | |
| ) | |
| refined = (sam_mask & floor_dilated).astype(np.uint8) | |
| refined[reject_dilated > 0] = 0 | |
| refined = clean_floor_mask(refined) | |
| refined_area = int(refined.sum()) | |
| original_area = int(floor_mask.sum()) | |
| if refined_area < SURFACE_MIN_PLANE_PIXELS or refined_area < original_area * 0.35: | |
| metadata["samRefinementReason"] = "refined-mask-too-small" | |
| return floor_mask, metadata | |
| metadata.update({ | |
| "samRefinementApplied": True, | |
| "samRefinementReason": "sam2-mask-refined", | |
| "samRefinementScore": float(scores[best_idx]) if scores is not None and len(scores) else None, | |
| "samRefinementOriginalPixels": original_area, | |
| "samRefinementPixels": refined_area, | |
| }) | |
| return refined, metadata | |