File size: 16,006 Bytes
d7b5c2a 6d2f042 d7b5c2a 6d2f042 d7b5c2a 6d2f042 d7b5c2a 6d2f042 d7b5c2a | 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | """Synthetic checks for wall mask refinement.
No model downloads, no server β pure numpy, runs in under a second.
python scripts/test_wall_mask.py
Builds a toy room (ceiling band on top, wall band in the middle, floor below,
a mirror hanging on the wall), punches the kind of holes that 3D plane
assignment leaves behind, and asserts the refinement puts them back without
leaking into the ceiling.
The three "regression" sections each pin a bug found while developing this.
All of them produced plausible-looking output that was wrong, which is exactly
why they are worth keeping.
"""
from __future__ import annotations
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
import numpy as np
from services.geometry.multi_plane import merge_planes_by_point_consistency
from services.image.edge_snap import snap_mask_to_image_edges
from services.wall.components import wall_surface_components
from services.wall.mask import contour_fill, refine_wall_component_mask, wall_region_masks
from state import ADE20K_CLASSES
H, W = 400, 600
CEILING_ROWS = slice(0, 80)
WALL_ROWS = slice(80, 300)
FLOOR_ROWS = slice(300, 400)
MIRROR = (slice(120, 200), slice(100, 220))
HOLE_A = (slice(150, 210), slice(300, 380)) # interior hole, like a marble patch
HOLE_B = (slice(230, 260), slice(420, 470)) # second interior hole
failures: list[str] = []
def check(label: str, condition: bool, detail: str = "") -> None:
if condition:
print(f" PASS {label}")
else:
failures.append(label)
print(f" FAIL {label}" + (f" ({detail})" if detail else ""))
def class_index(name: str) -> int:
return ADE20K_CLASSES.index(name)
def build_seg_map() -> np.ndarray:
seg = np.zeros((H, W), dtype=np.int32)
seg[CEILING_ROWS, :] = class_index("ceiling")
seg[WALL_ROWS, :] = class_index("wall")
seg[FLOOR_ROWS, :] = class_index("floor")
seg[MIRROR] = class_index("mirror")
return seg
def main() -> int:
seg_map = build_seg_map()
wall_raw, barrier, reclaimable = wall_region_masks(seg_map)
print("\nwall_region_masks:")
check("wall class found", wall_raw.sum() > 0)
check("mirror is NOT part of the raw wall class", wall_raw[MIRROR].sum() == 0)
check("ceiling is a barrier", barrier[CEILING_ROWS, :].all())
check("floor is a barrier", barrier[FLOOR_ROWS, :].all())
check("mirror is reclaimable", reclaimable[MIRROR].all())
check("ceiling is not reclaimable", reclaimable[CEILING_ROWS, :].sum() == 0)
print("\ncontour_fill:")
holed = np.zeros((H, W), dtype=np.uint8)
holed[WALL_ROWS, :] = 1
holed[HOLE_A] = 0
filled = contour_fill(holed)
check("interior hole is filled", filled[HOLE_A].all())
check("does not grow past the original outline",
filled[CEILING_ROWS, :].sum() == 0)
check("empty mask stays empty", contour_fill(np.zeros((H, W), np.uint8)).sum() == 0)
print("\nrefine_wall_component_mask:")
# What plane assignment realistically hands over: the wall, minus the mirror
# (stripped as protected), minus a couple of patches dropped for noisy normals.
component = np.zeros((H, W), dtype=np.uint8)
component[WALL_ROWS, :] = 1
component[MIRROR] = 0
component[HOLE_A] = 0
component[HOLE_B] = 0
refined, metadata = refine_wall_component_mask(component, wall_raw, reclaimable, barrier)
check("dropped patch A recovered", refined[HOLE_A].all())
check("dropped patch B recovered", refined[HOLE_B].all())
check("mirror reclaimed (tile drawn behind it)", refined[MIRROR].all())
check("no bleed into ceiling", refined[CEILING_ROWS, :].sum() == 0,
f"{int(refined[CEILING_ROWS, :].sum())} px leaked")
check("no bleed into floor", refined[FLOOR_ROWS, :].sum() == 0,
f"{int(refined[FLOOR_ROWS, :].sum())} px leaked")
check("recovered more than it started with",
metadata["wallMaskPixelsAfter"] > metadata["wallMaskPixelsBefore"])
check("whole wall band is covered",
refined[WALL_ROWS, :].all(),
f"{int((refined[WALL_ROWS, :] == 0).sum())} px still missing")
print("\neroded outer boundary (the ragged ceiling join):")
# Plane assignment does not only punch interior holes; it chews a wavy edge
# into the top of the wall where it meets the ceiling. That gap is open, so
# contour fill alone cannot reach it.
eroded = np.zeros((H, W), dtype=np.uint8)
eroded[WALL_ROWS, :] = 1
rng = np.random.default_rng(0)
for x in range(0, W, 10):
bite = int(rng.integers(6, 34))
eroded[80:80 + bite, x:x + 10] = 0 # wavy bite out of the top
bite = int(rng.integers(6, 26))
eroded[300 - bite:300, x:x + 10] = 0 # and the bottom
eroded_refined, _ = refine_wall_component_mask(eroded, wall_raw, reclaimable, barrier)
before_cover = eroded[WALL_ROWS, :].mean()
after_cover = eroded_refined[WALL_ROWS, :].mean()
check("wall band coverage substantially restored",
after_cover > 0.97,
f"{before_cover:.1%} -> {after_cover:.1%}")
check("coverage strictly improved", after_cover > before_cover,
f"{before_cover:.1%} -> {after_cover:.1%}")
check("deep bites filled (row 100)", eroded_refined[100, :].mean() > 0.98,
f"{eroded_refined[100, :].mean():.0%}")
check("still no ceiling bleed after hull expansion",
eroded_refined[CEILING_ROWS, :].sum() == 0,
f"{int(eroded_refined[CEILING_ROWS, :].sum())} px leaked")
print("\nregression β a doorway must keep two walls apart:")
# Growing vertically through `allowed` (wall + furniture) with a generous
# reach let one wall travel down through a TV cabinet and absorb the wall
# beyond a doorway β two segments collapsed into one and geometry confidence
# fell from 0.91 to 0.70. Growth now travels through wall pixels only.
seg_two = np.zeros((H, W), dtype=np.int32)
seg_two[CEILING_ROWS, :] = class_index("ceiling")
seg_two[WALL_ROWS, :] = class_index("wall")
seg_two[FLOOR_ROWS, :] = class_index("floor")
seg_two[WALL_ROWS, 250:350] = class_index("door")
seg_two[250:300, 0:120] = class_index("cabinet") # furniture against the wall
wall_two, barrier_two, reclaim_two = wall_region_masks(seg_two)
near_wall = np.zeros((H, W), dtype=np.uint8)
near_wall[WALL_ROWS, 0:250] = 1
near_wall[seg_two == class_index("door")] = 0
near_wall[seg_two == class_index("cabinet")] = 0
near_wall[120:180, 60:200] = 0 # hole needing repair
near_refined, _ = refine_wall_component_mask(near_wall, wall_two, reclaim_two, barrier_two)
check("hole in the near wall still repaired", near_refined[120:180, 60:200].all())
check("does not cross the doorway to the far wall",
near_refined[WALL_ROWS, 350:].sum() == 0,
f"{int(near_refined[WALL_ROWS, 350:].sum())} px crossed")
check("does not tile the doorway opening itself",
near_refined[WALL_ROWS, 250:350].sum() == 0,
f"{int(near_refined[WALL_ROWS, 250:350].sum())} px in the doorway")
# Reclaimable is now "everything that is not wall or barrier", so bounding
# against it is vacuous. Bound against the near wall's own extent instead.
check("does not run away past its own wall",
int(near_refined[:, 300:].sum()) == 0,
f"{int(near_refined[:, 300:].sum())} px past the doorway")
print("\nregression β hull must not jump an opening to a disconnected wall:")
# In the living-room photo the wall wraps above a doorway, so its convex hull
# reached across the opening and swallowed the hallway wall beyond it. Two
# segments became one and Wall 2 disappeared.
seg_gap = np.zeros((H, W), dtype=np.int32)
seg_gap[CEILING_ROWS, :] = class_index("ceiling")
seg_gap[WALL_ROWS, :] = class_index("wall")
seg_gap[FLOOR_ROWS, :] = class_index("floor")
seg_gap[130:300, 300:600] = class_index("door") # the opening
ISLAND = (slice(190, 250), slice(400, 500))
seg_gap[ISLAND] = class_index("wall") # far wall through it
wall_gap, barrier_gap, reclaim_gap = wall_region_masks(seg_gap)
near = np.zeros((H, W), dtype=np.uint8)
near[80:130, :] = 1
near[WALL_ROWS, 0:300] = 1
near[seg_gap == class_index("door")] = 0
near[ISLAND] = 0
near_refined2, _ = refine_wall_component_mask(near, wall_gap, reclaim_gap, barrier_gap)
check("disconnected far wall NOT absorbed", near_refined2[ISLAND].sum() == 0,
f"{int(near_refined2[ISLAND].sum())} px absorbed")
check("opening itself not tiled", near_refined2[150:290, 320:590].sum() == 0,
f"{int(near_refined2[150:290, 320:590].sum())} px in the opening")
check("near wall itself still intact", near_refined2[WALL_ROWS, 0:290].mean() > 0.95,
f"{near_refined2[WALL_ROWS, 0:290].mean():.0%}")
print("\nregression β a genuinely absent region must stay absent:")
# A wall that really does stop halfway across must not be stretched to fill
# the frame; contour fill only closes enclosed holes, never open edges.
partial = np.zeros((H, W), dtype=np.uint8)
partial[WALL_ROWS, 0:200] = 1
partial_refined, _ = refine_wall_component_mask(partial, wall_raw, reclaimable, barrier)
right_edge = partial_refined[WALL_ROWS, 400:]
check("does not invent wall on the far side", right_edge.sum() == 0,
f"{int(right_edge.sum())} px invented")
print("\nedge snapping (guided filter):")
# A photo with a dead-straight horizontal edge at row 200, and a mask whose
# boundary wobbles around it by +/-6 px, as ellipse morphology leaves it.
photo = np.zeros((H, W, 3), dtype=np.uint8)
photo[:200, :] = 210 # bright above the edge
photo[200:, :] = 90 # dark below
wobbly = np.zeros((H, W), dtype=np.uint8)
rng3 = np.random.default_rng(3)
for x in range(0, W, 12):
offset = int(rng3.integers(-6, 7))
wobbly[200 + offset:, x:x + 12] = 1
def boundary_spread(mask):
"""Std-dev of the first set row per column: 0 means dead straight."""
rows = [int(np.argmax(col)) for col in mask.T if col.any()]
return float(np.std(rows))
before_spread = boundary_spread(wobbly)
snapped = snap_mask_to_image_edges(wobbly, photo)
after_spread = boundary_spread(snapped)
check("wobble reduced", after_spread < before_spread * 0.5,
f"stddev {before_spread:.2f} -> {after_spread:.2f} px")
check("boundary landed on the real edge",
abs(np.mean([int(np.argmax(c)) for c in snapped.T if c.any()]) - 200) < 3,
f"mean row {np.mean([int(np.argmax(c)) for c in snapped.T if c.any()]):.1f}, expected ~200")
check("interior is untouched", snapped[300:, :].all())
check("no image means no change",
np.array_equal(snap_mask_to_image_edges(wobbly, None), wobbly))
print("\nregression β an unlisted object class must still be reclaimed:")
# A wall-mounted TV is often labelled `screen`, which was absent from
# OCCLUDER_CLASSES. It therefore landed in neither the barrier set nor the
# reclaimable set and got clamped away, punching a TV-shaped hole through
# the middle of the wall. Reclaimable is now defined by exclusion, so no
# object class can fall through the gap.
seg_tv = np.zeros((H, W), dtype=np.int32)
seg_tv[CEILING_ROWS, :] = class_index("ceiling")
seg_tv[WALL_ROWS, :] = class_index("wall")
seg_tv[FLOOR_ROWS, :] = class_index("floor")
TV = (slice(130, 230), slice(200, 420))
seg_tv[TV] = class_index("screen") # deliberately not in OCCLUDER_CLASSES
wall_tv, barrier_tv, reclaim_tv = wall_region_masks(seg_tv)
check("'screen' counts as reclaimable", reclaim_tv[TV].all())
check("'screen' is not a barrier", barrier_tv[TV].sum() == 0)
tv_component = np.zeros((H, W), dtype=np.uint8)
tv_component[WALL_ROWS, :] = 1
tv_component[TV] = 0 # segmentation cut the TV out
tv_refined, _ = refine_wall_component_mask(tv_component, wall_tv, reclaim_tv, barrier_tv)
check("tile is laid behind the TV", tv_refined[TV].all(),
f"{int((tv_refined[TV] == 0).sum())} px still missing")
check("still no ceiling bleed", tv_refined[CEILING_ROWS, :].sum() == 0)
print("\nwall_surface_components return contract:")
# Caught a real crash: the connectivity-first restructure appended bare masks
# where the repair pass expects (area, mask) pairs, so sorting compared numpy
# rows and every conversion died with "truth value of an array ... ambiguous".
# geometry=None short-circuits the planarity split, so the whole function is
# exercisable without a GPU.
parts, protected_out = wall_surface_components(seg_map, min_area=2000, geometry=None)
check("returns a list of 3-tuples (area, mask, planes)",
all(isinstance(item, tuple) and len(item) == 3 for item in parts),
f"got {[type(i).__name__ for i in parts[:3]]}")
check("first element is an int area",
all(isinstance(area, int) for area, _, _ in parts))
check("second element is a 2D uint8 mask",
all(mask.ndim == 2 and mask.dtype == np.uint8 for _, mask, _ in parts))
check("areas are sorted largest first",
[a for a, _, _ in parts] == sorted([a for a, _, _ in parts], reverse=True))
check("found the wall", len(parts) >= 1, f"{len(parts)} components")
check("protected mask returned", protected_out.shape == seg_map.shape)
print("\nplane merging by point consistency:")
# Numbers taken from a real living room measured on the GPU backend: the two
# halves of each flat wall sat 0.018 m and 0.035 m apart, while the
# protruding chimney breast was 0.155 m from its neighbours. RANSAC had
# banded each wall into vertical depth slabs.
rng2 = np.random.default_rng(7)
def wall_points(offset_m, count=4000, jitter=0.01):
"""A patch of a flat wall at x = offset_m, facing +x."""
pts = np.zeros((count, 3), dtype=np.float32)
pts[:, 0] = offset_m + rng2.normal(0, jitter, count)
pts[:, 1] = rng2.uniform(0, 2.5, count)
pts[:, 2] = rng2.uniform(0, 3.0, count)
return pts
def plane_at(offset_m, count):
return {"id": 0, "normal": np.array([1.0, 0.0, 0.0], np.float32),
"origin": np.array([offset_m, 0.0, 0.0], np.float32),
"offset": -offset_m, "inlierCount": count, "fitMode": "normal-aware"}
# Two slabs of ONE wall (0.035 m apart) plus a chimney breast (0.155 m out).
near, far, chimney = wall_points(0.0), wall_points(0.035), wall_points(0.155)
pts = np.vstack([near, far, chimney])
assign = np.concatenate([np.zeros(len(near), np.int32),
np.ones(len(far), np.int32),
np.full(len(chimney), 2, np.int32)])
planes = [plane_at(0.0, len(near)), plane_at(0.035, len(far)), plane_at(0.155, len(chimney))]
new_assign, new_planes = merge_planes_by_point_consistency(pts, assign, planes, 0.04)
check("two slabs of one wall merged", len(new_planes) == 2,
f"got {len(new_planes)} planes, expected 2")
check("chimney breast kept separate",
len(set(new_assign[:len(near)])) == 1
and new_assign[0] == new_assign[len(near)]
and new_assign[0] != new_assign[-1])
check("no point left unassigned", (new_assign >= 0).all())
far_apart = merge_planes_by_point_consistency(
pts, assign.copy(), [plane_at(0.0, 4000), plane_at(0.6, 4000), plane_at(1.2, 4000)], 0.04)[1]
check("clearly separate walls are never merged", len(far_apart) == 3,
f"got {len(far_apart)}")
print()
if failures:
print(f"{len(failures)} FAILED: {', '.join(failures)}")
return 1
print("All checks passed.")
return 0
if __name__ == "__main__":
sys.exit(main())
|