Download services/wall/components.py from modventures/room-visualizer-v2: direct link, hf CLI and curl.
- Browser
- Download file 8.82 kB
-
https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/wall/components.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer-v2/services/wall/components.py
-
curl -L -o components.py https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/wall/components.py
8.82 kB
| """Wall surface connected-component extraction. | |
| Functions | |
| --------- | |
| wall_surface_components - segment wall mask into independently renderable regions | |
| """ | |
| import cv2 | |
| import numpy as np | |
| from config.surface import SURFACE_MIN_PLANE_PIXELS | |
| from services.geometry.multi_plane import ( | |
| assign_points_to_surface_planes, | |
| fit_multi_surface_planes, | |
| geometry_point_maps, | |
| merge_coplanar_planes, | |
| merge_planes_by_point_consistency, | |
| ) | |
| from services.geometry.normals import normalize_vectors | |
| from services.geometry.plane_fitting import surface_distance_threshold | |
| from services.wall.mask import refine_wall_component_mask, wall_region_masks | |
| from state import OCCLUDER_CLASSES, class_ids | |
| from utils import seg_class_mask | |
| def split_region_if_not_planar(region: np.ndarray, geometry: dict | None, min_area: int): | |
| """Return [region] when it is one flat wall, else split it by fitted planes. | |
| Connectivity alone is not quite enough: where two walls meet at a corner | |
| with nothing between them, segmentation bridges the corner and hands us one | |
| region covering both. Those need separating, or one warped transform gets | |
| stretched across an angle. | |
| So geometry gets a narrow, well-posed job: decide whether this region is | |
| flat. A single least-squares plane is fitted and the 90th-percentile | |
| residual measured. A real wall sits within a couple of centimetres of its | |
| own plane; a region spanning a corner does not come close. Only when the | |
| region fails that test do we fall back to multi-plane splitting. | |
| """ | |
| if geometry is None: | |
| return [region] | |
| maps = geometry_point_maps(region, geometry) | |
| if maps is None: | |
| return [region] | |
| valid = maps["validMask"] & (region > 0) | |
| ys, xs = np.where(valid) | |
| if len(xs) < SURFACE_MIN_PLANE_PIXELS: | |
| return [region] | |
| points = maps["points"][ys, xs].astype(np.float32) | |
| normals = maps["normals"][ys, xs].astype(np.float32) | |
| finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1) | |
| points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite] | |
| if len(points) < SURFACE_MIN_PLANE_PIXELS: | |
| return [region] | |
| threshold = surface_distance_threshold(points) | |
| centered = points - points.mean(axis=0) | |
| # Smallest-eigenvalue eigenvector of the covariance is the plane normal. | |
| _eigenvalues, eigenvectors = np.linalg.eigh(centered.T @ centered) | |
| residual = np.abs(centered @ eigenvectors[:, 0].astype(np.float32)) | |
| flatness = float(np.percentile(residual, 90)) | |
| print( | |
| f"[WALL_REGION] {int(region.sum())} px p90Flatness={flatness:.3f}m " | |
| f"threshold={threshold:.3f}m {'FLAT (keep whole)' if flatness <= threshold else 'not flat -> split by plane'}", | |
| flush=True, | |
| ) | |
| if flatness <= threshold: | |
| return [region] | |
| lengths = np.linalg.norm(normals, axis=1) | |
| usable = lengths > 1e-4 | |
| if int(usable.sum()) < SURFACE_MIN_PLANE_PIXELS: | |
| return [region] | |
| points, ys, xs = points[usable], ys[usable], xs[usable] | |
| normals = normalize_vectors(normals[usable]) | |
| planes = fit_multi_surface_planes(points, normals, True, mark_floor=False) | |
| planes = merge_coplanar_planes(planes, threshold) | |
| wall_planes = [plane for plane in planes if abs(float(plane["normal"][1])) <= 0.45] | |
| if len(wall_planes) <= 1: | |
| return [region] | |
| assignment = assign_points_to_surface_planes(points, normals, wall_planes, True) | |
| assignment, wall_planes = merge_planes_by_point_consistency( | |
| points, assignment, wall_planes, threshold | |
| ) | |
| if len(wall_planes) <= 1: | |
| return [region] | |
| pieces = [] | |
| for plane_index in range(len(wall_planes)): | |
| selected = assignment == plane_index | |
| if int(selected.sum()) < min_area: | |
| continue | |
| piece = np.zeros_like(region) | |
| piece[ys[selected], xs[selected]] = 1 | |
| pieces.append(piece) | |
| return pieces or [region] | |
| def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None, | |
| image_rgb: np.ndarray | None = None): | |
| """Create clean, independently renderable wall regions. | |
| Semantic wall predictions often bridge across corners and openings. Removing | |
| protected classes before connected-component analysis prevents one warped | |
| transform from being applied to several physically different walls. | |
| """ | |
| # Components may occupy the wall itself plus anything mounted on it; those | |
| # objects are re-drawn over the tile via the segment occlusion mask instead | |
| # of being cut out of the surface. See services/wall/mask.py. | |
| wall_raw, barrier_mask, reclaimable_mask = wall_region_masks(seg_map) | |
| wall = wall_raw.copy() | |
| protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | { | |
| "door", "window", "column", "base", "railing", "ceiling", | |
| "building", "painting", "mirror", "curtain", | |
| })) | |
| # Wide enough to close the gap a wall-mounted TV or mirror leaves behind, | |
| # narrow enough that a doorway or a room corner still separates two walls. | |
| bridge_kernel_size = max(3, int(round(min(seg_map.shape[:2]) * 0.05))) | 1 | |
| radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006))) | |
| kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1)) | |
| protected = cv2.dilate(protected, kernel, iterations=1) | |
| wall[protected > 0] = 0 | |
| wall = cv2.morphologyEx(wall, cv2.MORPH_CLOSE, kernel) | |
| wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel) | |
| wall[protected > 0] = 0 | |
| # --- Stage 1: connectivity decides what counts as one wall ---------------- | |
| # Geometry used to decide this, by fitting planes over every wall pixel and | |
| # assigning each pixel to its nearest plane. Per-pixel normals from depth are | |
| # noisy, so that assignment banded single walls into vertical depth slabs: a | |
| # living room with three walls produced three planes but five segments, each | |
| # with its own UV frame, so the tile grid restarted and rotated at every | |
| # seam. Spatial connectivity is far more reliable for "is this one wall", | |
| # because walls are separated by corners, which are visible discontinuities. | |
| bridge = cv2.morphologyEx( | |
| wall, | |
| cv2.MORPH_CLOSE, | |
| cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (bridge_kernel_size, bridge_kernel_size)), | |
| ) | |
| region_count, region_labels, _region_stats, _ = cv2.connectedComponentsWithStats( | |
| bridge, connectivity=8 | |
| ) | |
| regions = [] | |
| for region_id in range(1, region_count): | |
| region = ((region_labels == region_id) & (wall > 0)).astype(np.uint8) | |
| if int(region.sum()) >= min_area: | |
| regions.append(region) | |
| print(f"[WALL_COMPONENTS] {len(regions)} connected wall region(s)", flush=True) | |
| # --- Stage 2: geometry only splits a region that is not actually flat ----- | |
| # components is a list of (area, mask) pairs; the repair pass below sorts on | |
| # the area, so pieces must be paired up rather than appended bare. | |
| components = [] | |
| for region in regions: | |
| for piece in split_region_if_not_planar(region, geometry, min_area): | |
| area = int(piece.sum()) | |
| if area >= min_area: | |
| components.append((area, piece.astype(np.uint8))) | |
| # --- Repair pass ------------------------------------------------------- | |
| # Splitting above deliberately runs on the protected-subtracted mask, so one | |
| # warped transform is never stretched across a corner or an opening. Now | |
| # that the split is settled, each component reclaims the holes that plane | |
| # assignment and protection punched through it. | |
| # | |
| # Largest first, subtracting whatever earlier components already claimed, so | |
| # the refined masks stay disjoint — otherwise the edge-repair dilation would | |
| # let two walls overlap at a corner and that seam would be tiled twice. | |
| components.sort(key=lambda item: item[0], reverse=True) | |
| claimed = np.zeros(wall_raw.shape[:2], dtype=bool) | |
| refined_components = [] | |
| for _, component_mask in components: | |
| refined, _metadata = refine_wall_component_mask( | |
| component_mask, wall_raw, reclaimable_mask, barrier_mask, image_rgb | |
| ) | |
| refined[claimed] = 0 | |
| area = int(refined.sum()) | |
| if area < min_area: | |
| continue | |
| claimed |= refined.astype(bool) | |
| refined_components.append((area, refined)) | |
| if refined_components: | |
| refined_components.sort(key=lambda item: item[0], reverse=True) | |
| print( | |
| f"[WALL_COMPONENTS] emitting {len(refined_components)} wall segment(s): " | |
| f"{[area for area, _ in refined_components]} px", | |
| flush=True, | |
| ) | |
| return refined_components, protected | |
| return components, protected | |