Spaces:
Paused
Paused
File size: 4,794 Bytes
c97431f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | """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
|