Spaces:
Paused
Paused
Download apps/renderer/test_wall_segments.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/test_wall_segments.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/test_wall_segments.py
-
curl -L -o test_wall_segments.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/test_wall_segments.py
11.5 kB
| """Wall segmentation: one segment per physical wall, floor plane budget untouched, fast. | |
| Run from apps/renderer: python -m unittest test_wall_segments | |
| Uses the GPU profile so the floor's max_planes (1) is the production value. | |
| """ | |
| import base64 | |
| import os | |
| import time | |
| import unittest | |
| os.environ.setdefault("VISUALIZER_CONFIG", "visualizer.gpu.toml") | |
| import cv2 # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| from config.surface import SURFACE_MAX_PLANES, WALL_MAX_PLANES # noqa: E402 | |
| from services.geometry.multi_plane import fit_multi_surface_planes # noqa: E402 | |
| from services.geometry.plane_uv import plane_to_image_transform, ray_plane_uv, upright_plane_basis # noqa: E402 | |
| from services.wall.components import discover_wall_components # noqa: E402 | |
| from services.wall.pipeline import build_wall_segments # noqa: E402 | |
| from state import class_ids # noqa: E402 | |
| WIDTH, HEIGHT = 1920, 1440 | |
| FOCAL = 1400.0 | |
| INTRINSICS = np.array([[FOCAL, 0, (WIDTH - 1) / 2], [0, FOCAL, (HEIGHT - 1) / 2], [0, 0, 1]], np.float32) | |
| FLOOR_ID = class_ids({"floor"})[0] | |
| WALL_ID = class_ids({"wall"})[0] | |
| CEILING_ID = class_ids({"ceiling"})[0] | |
| DOOR_ID = class_ids({"door"})[0] | |
| # Wall budget for the whole test run: generous for a CI CPU, well under the | |
| # ~3s of floor CPU stages the wall thread overlaps with in production. | |
| WALL_TIME_BUDGET_SECONDS = 1.5 | |
| def synthetic_room(walls=("left", "back", "right")): | |
| """Camera inside a box room, OpenCV axes (x right, y down, z forward). | |
| Returns (seg_map, geometry, labels) with MoGe-style full-res points/normals. | |
| labels: 0 floor, 1 ceiling, 2+ walls in the order given. | |
| """ | |
| planes = [ # (normal pointing into the room, offset d) for n.p + d = 0 | |
| (np.array([0, -1, 0], np.float32), 1.5, FLOOR_ID), # floor y = 1.5 | |
| (np.array([0, 1, 0], np.float32), 1.2, CEILING_ID), # ceiling y = -1.2 | |
| ] | |
| wall_planes = { | |
| "left": (np.array([1, 0, 0], np.float32), 2.2), # x = -2.2 | |
| "back": (np.array([0, 0, -1], np.float32), 5.0), # z = 5 | |
| "right": (np.array([-1, 0, 0], np.float32), 2.2), # x = 2.2 | |
| } | |
| planes += [(wall_planes[name][0], wall_planes[name][1], WALL_ID) for name in walls] | |
| yy, xx = np.mgrid[0:HEIGHT, 0:WIDTH].astype(np.float32) | |
| rays = np.dstack(((xx - INTRINSICS[0, 2]) / FOCAL, (yy - INTRINSICS[1, 2]) / FOCAL, np.ones_like(xx))) | |
| best_t = np.full((HEIGHT, WIDTH), np.inf, np.float32) | |
| labels = np.full((HEIGHT, WIDTH), -1, np.int32) | |
| for index, (normal, offset, _) in enumerate(planes): | |
| with np.errstate(divide="ignore", invalid="ignore"): | |
| t = -offset / (rays @ normal) | |
| closer = (t > 0) & (t < best_t) | |
| best_t[closer] = t[closer] | |
| labels[closer] = index | |
| valid = np.isfinite(best_t) | |
| points = rays * np.where(valid, best_t, 0)[..., None] | |
| seg_map = np.zeros((HEIGHT, WIDTH), np.uint8) | |
| normals = np.zeros((HEIGHT, WIDTH, 3), np.float32) | |
| for index, (normal, _, class_id) in enumerate(planes): | |
| seg_map[labels == index] = class_id | |
| normals[labels == index] = normal # into the room == facing the camera (MoGe-style) | |
| geometry = { | |
| "provider": "moge-2", | |
| "points": points.astype(np.float32), | |
| "normals": normals, | |
| "validMask": valid, | |
| "depth": points[..., 2].astype(np.float32), | |
| "intrinsics": INTRINSICS, | |
| } | |
| return seg_map, geometry, labels | |
| class WallSegmentTests(unittest.TestCase): | |
| def setUpClass(cls): | |
| cls.seg_map, cls.geometry, cls.labels = synthetic_room() | |
| cls.min_area = max(1200, int(WIDTH * HEIGHT * 0.015)) | |
| def test_three_walls_become_three_ordered_segments(self): | |
| discovery = discover_wall_components(self.seg_map, self.geometry, self.min_area) | |
| self.assertEqual(len(discovery.components), 3) | |
| expected_normals = ([1, 0, 0], [0, 0, 1], [1, 0, 0]) # left, back, right (up to sign) | |
| for component, expected, true_label in zip(discovery.components, expected_normals, (2, 3, 4)): | |
| purity = float((self.labels[component.mask > 0] == true_label).mean()) | |
| self.assertGreater(purity, 0.97, "a wall segment leaked into another wall") | |
| plane = component.plane | |
| assert plane is not None | |
| self.assertGreater(abs(float(plane.normal @ np.array(expected, np.float32))), 0.98) | |
| def test_wall_outline_reaches_the_door_frame(self): | |
| """Walls must follow the semantic boundary like the floor: no gap band, no bleed.""" | |
| seg_map = self.seg_map.copy() | |
| door = np.array([[1150, 520], [1330, 505], [1340, 1000], [1160, 1010]], np.int32) # slanted frame | |
| cv2.fillPoly(seg_map, [door], int(DOOR_ID)) | |
| discovery = discover_wall_components(seg_map, self.geometry, self.min_area) | |
| walls = np.zeros(seg_map.shape, bool) | |
| for component in discovery.components: | |
| walls |= component.mask > 0 | |
| door_mask = seg_map == DOOR_ID | |
| depth_into_door = cv2.distanceTransform(door_mask.astype(np.uint8), cv2.DIST_L2, 3) | |
| bleed = walls & door_mask | |
| # Rasterising a straight slanted edge may touch the door's first pixel row only. | |
| self.assertLessEqual(float(depth_into_door[bleed].max()) if bleed.any() else 0.0, 1.5, | |
| "wall texture bled onto the door") | |
| near_door = cv2.dilate(door_mask.astype(np.uint8), np.ones((7, 7), np.uint8)) > 0 | |
| wall_near_door = near_door & ~door_mask & (seg_map == WALL_ID) | |
| covered = float(walls[wall_near_door].mean()) | |
| self.assertGreater(covered, 0.97, f"only {covered:.0%} of wall pixels next to the door are textured") | |
| def test_zigzag_door_edge_becomes_one_straight_line(self): | |
| """A wobbly semantic boundary (as OneFormer produces) is redrawn as a straight edge.""" | |
| seg_map = self.seg_map.copy() | |
| rng = np.random.default_rng(3) | |
| top, bottom, edge_x = 520, 1000, 1150 | |
| for y in range(top, bottom): | |
| wobble = int(rng.integers(-4, 5)) # +-4px zig-zag per row | |
| seg_map[y, edge_x + wobble:1330] = DOOR_ID | |
| discovery = discover_wall_components(seg_map, self.geometry, self.min_area) | |
| walls = np.zeros(seg_map.shape, bool) | |
| for component in discovery.components: | |
| walls |= component.mask > 0 | |
| rows = np.arange(top + 40, bottom - 40) # away from the corners | |
| window = walls[rows, edge_x - 40:edge_x + 40] | |
| edge = edge_x - 40 + window.shape[1] - np.argmax(window[:, ::-1], axis=1) # last wall px + 1 | |
| fitted = np.polyval(np.polyfit(rows, edge, 1), rows) | |
| self.assertLess(float(np.abs(edge - fitted).max()), 1.01, "wall edge along the door is not straight") | |
| self.assertLess(float(np.abs(fitted - edge_x).max()), 2.5, "straight edge drifted off the true boundary") | |
| def test_single_flat_wall_is_not_split(self): | |
| seg_map, geometry, _ = synthetic_room(walls=("back",)) | |
| discovery = discover_wall_components(seg_map, geometry, self.min_area) | |
| self.assertEqual(len(discovery.components), 1) | |
| def test_floor_keeps_its_own_plane_budget(self): | |
| self.assertEqual(SURFACE_MAX_PLANES, 1, "GPU profile floor max_planes must stay 1") | |
| self.assertGreater(WALL_MAX_PLANES, 1) | |
| mask = self.labels >= 2 | |
| points = self.geometry["points"][mask][::20] | |
| normals = self.geometry["normals"][mask][::20] | |
| self.assertLessEqual(len(fit_multi_surface_planes(points, normals, True)), 1) | |
| self.assertGreaterEqual(len(fit_multi_surface_planes(points, normals, True, max_planes=WALL_MAX_PLANES)), 3) | |
| def test_ray_plane_uv_matches_true_points(self): | |
| normal = np.array([0, 0, -1], np.float32) | |
| origin = np.array([0, 0, 5], np.float32) | |
| u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32)) | |
| flat = np.flatnonzero((self.labels == 3).ravel())[::50] | |
| uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis) | |
| self.assertTrue(hit.all()) | |
| true_points = self.geometry["points"].reshape(-1, 3)[flat] | |
| true_uv = np.column_stack(((true_points - origin) @ u_axis, (true_points - origin) @ v_axis)) | |
| self.assertLess(float(np.abs(uv - true_uv).max()), 1e-3) | |
| def test_plane_transform_equals_ray_plane_uv(self): | |
| normal = np.array([0.6, 0.0, -0.8], np.float32) | |
| origin = np.array([0.5, 0.2, 4.0], np.float32) | |
| u_axis, v_axis = upright_plane_basis(normal, np.array([0, 1, 0], np.float32)) | |
| flat = np.arange(0, WIDTH * HEIGHT, 997) | |
| uv, hit = ray_plane_uv(flat, WIDTH, INTRINSICS, origin, normal, u_axis, v_axis) | |
| transform = plane_to_image_transform(INTRINSICS, origin, normal, u_axis, v_axis) | |
| pixels = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat)))) | |
| mapped = pixels @ transform.T | |
| mapped_uv = mapped[:, :2] / mapped[:, 2:3] | |
| self.assertLess(float(np.abs(mapped_uv[hit] - uv[hit]).max()), 1e-3) | |
| def test_wall_texture_axis_is_upright(self): | |
| u_axis, v_axis = upright_plane_basis(np.array([1, 0, 0], np.float32), np.array([0, 1, 0], np.float32)) | |
| self.assertGreater(abs(float(v_axis[1])), 0.99) | |
| self.assertLess(abs(float(u_axis[1])), 1e-3) | |
| def test_segments_have_exact_plane_mapping_small_payload_and_fit_budget(self): | |
| started = time.perf_counter() | |
| result = build_wall_segments( | |
| np.full((HEIGHT, WIDTH, 3), 180, np.uint8), self.seg_map, self.geometry, | |
| self.min_area, "test-model", | |
| ) | |
| elapsed = time.perf_counter() - started | |
| print(f"\n[wall benchmark] {WIDTH}x{HEIGHT}: {elapsed * 1000:.0f}ms {result.detail}") | |
| self.assertEqual([s["id"] for s in result.segments], [1, 2, 3]) | |
| points = self.geometry["points"].reshape(-1, 3) | |
| true_labels = self.labels.ravel() | |
| for segment, wall_label in zip(result.segments, (2, 3, 4)): # left, back, right | |
| plane = segment["plane"] | |
| self.assertIsNone(segment["surfaceUv"], "walls ship a 3x3 transform, not per-pixel UV") | |
| self.assertEqual(segment["metadata"]["textureMappingMode"], "wall-plane") | |
| self.assertGreaterEqual(plane["geometryConfidence"], 0.99) | |
| self.assertEqual(segment["metadata"]["wallComponentCount"], 3) | |
| # The transform reproduces the true metric position of the wall's own pixels | |
| # (edge pixels shared with a neighbouring surface lie on that surface's plane). | |
| flat = np.frombuffer(base64.b64decode(segment["mask"]), np.uint32)[::101] | |
| flat = flat[true_labels[flat] == wall_label] | |
| transform = np.asarray(segment["surfaceTransform"], np.float64).reshape(3, 3) | |
| mapped = np.column_stack((flat % WIDTH, flat // WIDTH, np.ones(len(flat)))) @ transform.T | |
| origin = np.asarray(plane["planeOrigin"]) | |
| true_uv = np.column_stack(( | |
| (points[flat] - origin) @ np.asarray(plane["surfaceUAxis"]), | |
| (points[flat] - origin) @ np.asarray(plane["surfaceVAxis"]), | |
| )) | |
| self.assertLess(float(np.abs(mapped[:, :2] / mapped[:, 2:3] - true_uv).max()), 0.005) | |
| shade = segment["shadeMap"] | |
| if shade is not None: | |
| self.assertLessEqual(max(shade.shape), 768) | |
| self.assertLess(elapsed, WALL_TIME_BUDGET_SECONDS) | |
| if __name__ == "__main__": | |
| unittest.main() | |