File size: 11,522 Bytes
18196ae | 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | """Wall segmentation: one segment per physical wall, floor plane budget untouched, fast.
Run from backend/floor-visualizer: 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):
@classmethod
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()
|