"""Floor mask creation and morphological cleanup. Functions --------- clean_floor_mask - morphological close/open + connected-component filtering smooth_mask_edge - remove pixel speckle along the mask edge wall_subtract - remove wall/reject pixels from a floor mask build_floor_surface_mask - composite floor surface from segmentation, depth, and geometry """ import time import cv2 import numpy as np from config.runtime import ENABLE_FLOOR_MASK_CLEANUP from state import ( OCCLUDER_CLASSES, REJECT_SURFACE_CLASSES, SOFT_FLOOR_COVERING_CLASSES, class_ids, ) from utils import seg_class_mask from services.floor.edge_coverage import ( improve_surface_edge_coverage, expand_surface_over_soft_floor_coverings, ) from services.floor.geometry_filter import filter_surface_by_floor_geometry def clean_floor_mask(mask: np.ndarray) -> np.ndarray: if not ENABLE_FLOOR_MASK_CLEANUP: return mask.astype(np.uint8, copy=False) if mask.dtype != np.uint8: mask = mask.astype(np.uint8) h, w = mask.shape[:2] min_side = max(3, min(h, w)) close_size = max(5, int(round(min_side * 0.018))) | 1 open_size = max(3, int(round(min_side * 0.006))) | 1 closed = cv2.morphologyEx( mask, cv2.MORPH_CLOSE, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size)), ) cleaned = cv2.morphologyEx( closed, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (open_size, open_size)), ) count, labels, stats, _ = cv2.connectedComponentsWithStats(cleaned, connectivity=8) if count <= 1: return cleaned gravity_threshold = int(h * 0.60) min_area = max(1000, int(h * w * 0.01)) result = np.zeros_like(cleaned) for component_id in range(1, count): area = stats[component_id, cv2.CC_STAT_AREA] if area < min_area: continue comp_bottom = stats[component_id, cv2.CC_STAT_TOP] + stats[component_id, cv2.CC_STAT_HEIGHT] if comp_bottom <= gravity_threshold: continue result[labels == component_id] = 1 if result.any(): return result largest = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) return (labels == largest).astype(np.uint8) def smooth_mask_edge(mask: np.ndarray, sigma: float = 1.5) -> np.ndarray: """Remove the single-pixel speckle and spikes the per-pixel depth and plane filters leave.""" if not mask.any(): return mask.astype(np.uint8, copy=False) blurred = cv2.GaussianBlur(mask.astype(np.float32), (0, 0), sigmaX=sigma, sigmaY=sigma) return (blurred >= 0.5).astype(np.uint8) def wall_subtract(mask: np.ndarray, seg_map: np.ndarray, dilation: int = 1) -> np.ndarray: reject_raw = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES)) if dilation > 0: kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) reject_raw = cv2.dilate(reject_raw, kern, iterations=dilation) result = mask.copy() result[reject_raw > 0] = 0 return result def build_floor_surface_mask( floor_mask: np.ndarray, seg_map: np.ndarray, quad: np.ndarray | None, depth: np.ndarray | None, geometry: dict | None, plane: dict | None, *, geometry_maps: dict | None = None, ): total_started = time.perf_counter() phase_started = total_started h, w = floor_mask.shape[:2] kern_size = max(5, min(h, w) // 160) | 1 kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size)) occluder_mask = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES)) soft_covering_mask = seg_class_mask(seg_map, class_ids(SOFT_FLOOR_COVERING_CLASSES)) reject_mask = seg_class_mask(seg_map, class_ids(REJECT_SURFACE_CLASSES)) hard_protected_mask = (occluder_mask > 0) | (reject_mask > 0) normal_edge_protected_mask = hard_protected_mask | (soft_covering_mask > 0) surface = floor_mask.copy() surface[reject_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 if not surface.any(): surface = floor_mask.copy() surface[soft_covering_mask > 0] = 0 contours, _ = cv2.findContours(surface, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if contours: filled = np.zeros((h, w), dtype=np.uint8) cv2.drawContours(filled, contours, -1, 1, cv2.FILLED) filled[reject_mask > 0] = 0 filled[soft_covering_mask > 0] = 0 surface = filled if quad is not None and surface.any(): plane_mask = np.zeros((h, w), dtype=np.uint8) cv2.fillConvexPoly(plane_mask, np.round(quad).astype(np.int32), 1) plane_mask[reject_mask > 0] = 0 plane_mask[soft_covering_mask > 0] = 0 near_floor = cv2.dilate(surface, kern, iterations=6) surface = cv2.bitwise_or(surface, cv2.bitwise_and(plane_mask, near_floor)) surface[soft_covering_mask > 0] = 0 surface[occluder_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 if depth is not None and floor_mask.any(): floor_depth = depth[(floor_mask > 0) & np.isfinite(depth)] if floor_depth.size == 0: floor_depth = None else: floor_depth = None if floor_depth is not None: lo, hi = float(np.percentile(floor_depth, 2)), float(np.percentile(floor_depth, 98)) margin = max(0.08, (hi - lo) * 0.35) depth_keep = (depth >= lo - margin) & (depth <= hi + margin) surface = (surface & depth_keep.astype(np.uint8)).astype(np.uint8) surface[floor_mask > 0] = np.maximum(surface[floor_mask > 0], 1) surface[occluder_mask > 0] = 0 surface[reject_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 preparation_ms = (time.perf_counter() - phase_started) * 1000 phase_started = time.perf_counter() surface, geometry_filter_metadata = filter_surface_by_floor_geometry( surface, geometry, plane, geometry_maps=geometry_maps, ) initial_filter_ms = (time.perf_counter() - phase_started) * 1000 surface[occluder_mask > 0] = 0 surface[reject_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 phase_started = time.perf_counter() surface = clean_floor_mask(surface) surface[occluder_mask > 0] = 0 surface[reject_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask) cleanup_and_edge_ms = (time.perf_counter() - phase_started) * 1000 phase_started = time.perf_counter() surface, post_edge_filter_metadata = filter_surface_by_floor_geometry( surface, geometry, plane, geometry_maps=geometry_maps, ) post_edge_filter_ms = (time.perf_counter() - phase_started) * 1000 surface[occluder_mask > 0] = 0 surface[reject_mask > 0] = 0 surface[soft_covering_mask > 0] = 0 post_edge_filter_metadata = { f"postEdge{k[0].upper()}{k[1:]}": value for k, value in post_edge_filter_metadata.items() } phase_started = time.perf_counter() surface_before_soft_covering = surface surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings( surface, soft_covering_mask, hard_protected_mask, ) soft_covering_ms = (time.perf_counter() - phase_started) * 1000 phase_started = time.perf_counter() if surface is surface_before_soft_covering or not soft_covering_metadata["softFloorCoveringExpansionApplied"]: post_soft_covering_filter_metadata = { "geometrySurfaceFilterApplied": False, "geometrySurfaceFilterReason": "soft-floor-surface-unchanged", "geometrySurfacePixelsBefore": int(surface.sum()), "geometrySurfacePixelsAfter": int(surface.sum()), } else: surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry( surface, geometry, plane, geometry_maps=geometry_maps, ) post_soft_filter_ms = (time.perf_counter() - phase_started) * 1000 surface = smooth_mask_edge(surface) surface[occluder_mask > 0] = 0 surface[reject_mask > 0] = 0 post_soft_covering_filter_metadata = { f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value for k, value in post_soft_covering_filter_metadata.items() } timing_ms = { "preparation": round(preparation_ms, 2), "initialGeometryFilter": round(initial_filter_ms, 2), "cleanupAndEdgeRepair": round(cleanup_and_edge_ms, 2), "postEdgeGeometryFilter": round(post_edge_filter_ms, 2), "softFloorExpansion": round(soft_covering_ms, 2), "postSoftFloorGeometryFilter": round(post_soft_filter_ms, 2), "total": round((time.perf_counter() - total_started) * 1000, 2), } print( "[SURFACE_MASKING_TIMING] " + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()), flush=True, ) return surface, { **geometry_filter_metadata, **edge_metadata, **post_edge_filter_metadata, **soft_covering_metadata, **post_soft_covering_filter_metadata, "surfaceMaskingTimingMs": timing_ms, }