github-actions[bot] commited on
Commit
3e1a674
·
1 Parent(s): 6d2f042

Automated Deploy: 71f21250a44df8ae27632dcdbb91eb8cd38ba180

Browse files
config/runtime.py CHANGED
@@ -6,11 +6,11 @@ ENABLE_FLOOR_MASK_CLEANUP = config_bool("ENABLE_FLOOR_MASK_CLEANUP", "runtime",
6
  ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
7
  ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
8
  ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
9
- ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "1")
10
  ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
11
- ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "0")
12
  ENABLE_FAST_SHADOW_TRANSFER = config_bool(
13
- "ENABLE_FAST_SHADOW_TRANSFER", "runtime", "enable_fast_shadow_transfer", "0", # all lighting disabled
14
  )
15
  WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1")
16
 
@@ -44,16 +44,6 @@ ROOM_UPLOAD_JPEG_QUALITY = min(95, max(50, int(config_value(
44
  "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
45
  ))))
46
 
47
- # Deflate level for the .vizbundle zip. Its payload is raw float/uint surface
48
- # arrays, which are highly compressible: on a 1200x1600 room, level 6 takes the
49
- # bundle from 12.7 MB to 1.0 MB for about 170 ms of CPU. That matters because a
50
- # 12.7 MB body is exactly what fails to reach a browser through a dev tunnel.
51
- # 0 stores uncompressed (the old behaviour); 1 is ~6x for 37 ms; 9 buys almost
52
- # nothing over 6 and costs 5x the time.
53
- BUNDLE_COMPRESSION_LEVEL = max(0, min(9, int(config_value(
54
- "BUNDLE_COMPRESSION_LEVEL", "runtime", "bundle_compression_level", "6",
55
- ))))
56
-
57
  DEBUG_ARTIFACTS_ENABLED = config_bool(
58
  "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1",
59
  )
 
6
  ENABLE_DEPTH_ESTIMATION = config_bool("ENABLE_DEPTH_ESTIMATION", "runtime", "enable_depth_estimation", "1")
7
  ENABLE_PLANE_FIT = config_bool("ENABLE_PLANE_FIT", "runtime", "enable_plane_fit", "1")
8
  ENABLE_MULTI_PLANE_SURFACES = config_bool("ENABLE_MULTI_PLANE_SURFACES", "runtime", "enable_multi_plane_surfaces", "1")
9
+ ENABLE_WALL_SEGMENTS = config_bool("ENABLE_WALL_SEGMENTS", "runtime", "enable_wall_segments", "0")
10
  ENABLE_INTRINSIC_SHADING = config_bool("ENABLE_INTRINSIC_SHADING", "runtime", "enable_intrinsic_shading", "0")
11
+ ENABLE_SHADING_TRANSFER = config_bool("ENABLE_SHADING_TRANSFER", "runtime", "enable_shading_transfer", "1")
12
  ENABLE_FAST_SHADOW_TRANSFER = config_bool(
13
+ "ENABLE_FAST_SHADOW_TRANSFER", "runtime", "enable_fast_shadow_transfer", "0",
14
  )
15
  WARM_START_MODELS = config_bool("WARM_START_MODELS", "runtime", "warm_start_models", "1")
16
 
 
44
  "ROOM_UPLOAD_JPEG_QUALITY", "runtime", "room_upload_jpeg_quality", "85",
45
  ))))
46
 
 
 
 
 
 
 
 
 
 
 
47
  DEBUG_ARTIFACTS_ENABLED = config_bool(
48
  "DEBUG_ARTIFACTS_ENABLED", "runtime", "debug_artifacts_enabled", "1",
49
  )
config/surface.py CHANGED
@@ -78,12 +78,3 @@ SURFACE_PLANE_NORMAL_MIN_COS = float(config_value(
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
81
-
82
- # Walls tile *behind* mounted objects, so a wall surface legitimately
83
- # contains pixels with no valid wall geometry (a TV, a mirror, a cabinet).
84
- # Holding walls to the floor's 0.995 makes every wall fail the gate as
85
- # 'incomplete-surface-uv'. The shortfall is exactly the occluded pixels,
86
- # which the occlusion mask repaints anyway, so it is not a defect.
87
- SURFACE_UV_WALL_MIN_COVERAGE = float(config_value(
88
- "SURFACE_UV_WALL_MIN_COVERAGE", "surface_mapping", "uv_wall_min_coverage", "0.90",
89
- ))
 
78
  SURFACE_PLANE_FILTER_MIN_KEEP_RATIO = float(config_value(
79
  "SURFACE_PLANE_FILTER_MIN_KEEP_RATIO", "surface_mapping", "plane_filter_min_keep_ratio", "0.45",
80
  ))
 
 
 
 
 
 
 
 
 
services/debug/overlays.py CHANGED
@@ -19,38 +19,6 @@ def debug_mask_overlay(
19
  return output
20
 
21
 
22
- WALL_COMPONENT_COLORS = (
23
- (255, 96, 96), (96, 200, 255), (140, 240, 140), (255, 200, 80),
24
- (210, 140, 255), (255, 140, 200), (120, 255, 230), (200, 200, 120),
25
- )
26
-
27
-
28
- def debug_wall_components_overlay(image_rgb: np.ndarray, components) -> np.ndarray:
29
- """Tint each wall component a distinct colour and label it.
30
-
31
- `components` is the list of (area, mask) pairs returned by
32
- wall_surface_components(). Distinct colours are what make it obvious when
33
- two physically separate walls have been merged into one component, or when
34
- a single wall has been split across a corner.
35
- """
36
- output = image_rgb.copy()
37
- for index, item in enumerate(components):
38
- mask = item[1] if isinstance(item, (tuple, list)) else item
39
- valid = mask.astype(bool)
40
- if not valid.any():
41
- continue
42
- color = WALL_COMPONENT_COLORS[index % len(WALL_COMPONENT_COLORS)]
43
- overlay = np.empty_like(output)
44
- overlay[:] = color
45
- output[valid] = cv2.addWeighted(output, 0.42, overlay, 0.58, 0)[valid]
46
- ys, xs = np.where(valid)
47
- center = (int(xs.mean()) - 42, int(ys.mean()))
48
- label = f"Wall {index + 1}"
49
- cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 0), 5, cv2.LINE_AA)
50
- cv2.putText(output, label, center, cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA)
51
- return output
52
-
53
-
54
  def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
55
  labels = seg_map.astype(np.int32)
56
  hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
@@ -63,18 +31,6 @@ def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np
63
 
64
  def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
65
  scalar = values.astype(np.float32)
66
- if mask is not None and mask.shape[:2] != scalar.shape[:2]:
67
- # The map and the mask it was measured against need not share a shape.
68
- # The fast-shadow path bounds its shade map to FAST_SHADOW_MAX_DIMENSION
69
- # and the renderer samples it linearly, so for anything larger than that
70
- # the map arrives smaller than the surface mask. Match the mask to the
71
- # map rather than the reverse: the map is what is being visualised, and
72
- # upscaling it here would invent detail the pipeline never produced.
73
- mask = cv2.resize(
74
- mask.astype(np.uint8),
75
- (scalar.shape[1], scalar.shape[0]),
76
- interpolation=cv2.INTER_NEAREST,
77
- )
78
  finite = np.isfinite(scalar)
79
  if mask is not None:
80
  finite &= mask.astype(bool)
 
19
  return output
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def debug_segmentation_overlay(image_rgb: np.ndarray, seg_map: np.ndarray) -> np.ndarray:
23
  labels = seg_map.astype(np.int32)
24
  hsv = np.zeros((*labels.shape, 3), dtype=np.uint8)
 
31
 
32
  def debug_scalar_map(values: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
33
  scalar = values.astype(np.float32)
 
 
 
 
 
 
 
 
 
 
 
 
34
  finite = np.isfinite(scalar)
35
  if mask is not None:
36
  finite &= mask.astype(bool)
services/geometry/multi_plane.py CHANGED
@@ -4,7 +4,7 @@ import numpy as np
4
 
5
  from enums import PlaneFitMode
6
  from config.models import DEPTH_MODEL_NAME
7
- from config.runtime import DEBUG_ARTIFACTS_ENABLED, ENABLE_MULTI_PLANE_SURFACES
8
  from config.surface import (
9
  SURFACE_MAX_PLANES,
10
  SURFACE_MIN_PLANE_PIXELS,
@@ -92,8 +92,7 @@ def geometry_point_maps(mask: np.ndarray, geometry: dict | None):
92
  }
93
 
94
 
95
- def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True,
96
- mark_floor: bool = True, vertical_ref: np.ndarray | None = None):
97
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
98
  return []
99
 
@@ -151,189 +150,18 @@ def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_re
151
 
152
  planes = _prune_weak_secondary_planes(planes)
153
 
154
- # On a wall-only surface every normal is near-horizontal, so this argmax
155
- # would still crown one of them "the floor" and hand it floor-style axes
156
- # (an arbitrary horizontal reference) instead of gravity-aligned ones —
157
- # tiles on that wall would come out rotated. Callers working a non-floor
158
- # surface pass mark_floor=False.
159
  floor_id = int(np.argmax([
160
  plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1])))
161
  for plane in planes
162
- ])) if mark_floor else -1
163
  for idx, plane in enumerate(planes):
164
- plane["isFloor"] = bool(mark_floor and idx == floor_id)
165
- u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"], vertical_ref)
166
  plane["uAxis"] = u_axis
167
  plane["vAxis"] = v_axis
168
  return planes
169
 
170
 
171
- def merge_planes_by_point_consistency(
172
- points: np.ndarray,
173
- assignment: np.ndarray,
174
- planes: list[dict],
175
- distance_threshold: float,
176
- angle_degrees: float = 20.0,
177
- tolerance_scale: float = 1.5,
178
- ) -> tuple[np.ndarray, list[dict]]:
179
- """Merge planes whose assigned points actually lie on one another's plane.
180
-
181
- Comparing two fitted planes to each other does not work reliably here.
182
- RANSAC peels a plane off, removes its inliers, then fits the *remainder* --
183
- so on a single flat wall the leftover tails produce a plane that is both
184
- tilted and offset relative to the first, even though every point involved
185
- belongs to the same physical surface. Threshold the plane parameters and you
186
- either fail to merge (wall sliced into vertical depth-slab strips) or merge
187
- surfaces that are genuinely apart.
188
-
189
- Measuring the points instead is unambiguous: if plane B's pixels sit within
190
- tolerance of plane A, they are the same wall. On a sample living room the
191
- two halves of each wall sat 0.018 m and 0.035 m apart, while the protruding
192
- chimney breast was 0.155 m from its neighbours -- a clean gap with nothing
193
- in between.
194
-
195
- Returns (remapped_assignment, merged_planes).
196
- """
197
- if len(planes) <= 1:
198
- return assignment, planes
199
-
200
- cos_limit = float(np.cos(np.deg2rad(angle_degrees)))
201
- limit = float(distance_threshold) * tolerance_scale
202
- parent = list(range(len(planes)))
203
-
204
- def find(index: int) -> int:
205
- while parent[index] != index:
206
- parent[index] = parent[parent[index]]
207
- index = parent[index]
208
- return index
209
-
210
- def offset_of(plane: dict) -> tuple[np.ndarray, float]:
211
- normal = np.asarray(plane["normal"], dtype=np.float32)
212
- origin = np.asarray(plane["origin"], dtype=np.float32)
213
- return normal, float(-origin @ normal)
214
-
215
- def spread(subject: int, reference: int) -> float:
216
- """How far the subject plane's points sit from the reference plane."""
217
- member = points[assignment == subject]
218
- if member.size == 0:
219
- return float("inf")
220
- normal, offset = offset_of(planes[reference])
221
- return float(np.percentile(np.abs(member @ normal + offset), 90))
222
-
223
- for a in range(len(planes)):
224
- for b in range(a + 1, len(planes)):
225
- normal_a = np.asarray(planes[a]["normal"], dtype=np.float32)
226
- normal_b = np.asarray(planes[b]["normal"], dtype=np.float32)
227
- if abs(float(normal_a @ normal_b)) < cos_limit:
228
- continue
229
- worst = max(spread(b, a), spread(a, b))
230
- # One line per plane pair, so up to ten per wall region per
231
- # conversion now that max_planes is 5. Useful when working out why
232
- # two walls merged; noise in a production log.
233
- if DEBUG_ARTIFACTS_ENABLED:
234
- print(
235
- f"[PLANE_MERGE] plane {a} vs {b}: "
236
- f"angle={np.degrees(np.arccos(min(1.0, abs(float(normal_a @ normal_b))))):.1f}deg "
237
- f"p90Distance={worst:.3f}m limit={limit:.3f}m "
238
- f"{'MERGE' if worst <= limit else 'keep separate'}",
239
- flush=True,
240
- )
241
- if worst <= limit:
242
- root_a, root_b = find(a), find(b)
243
- if root_a != root_b:
244
- parent[max(root_a, root_b)] = min(root_a, root_b)
245
-
246
- roots = sorted({find(index) for index in range(len(planes))})
247
- if len(roots) == len(planes):
248
- return assignment, planes
249
-
250
- remap = {root: new for new, root in enumerate(roots)}
251
- merged_assignment = np.full_like(assignment, -1)
252
- merged_planes = []
253
- for root in roots:
254
- members = [index for index in range(len(planes)) if find(index) == root]
255
- # Keep the largest contributor's orientation; it is the best-supported fit.
256
- dominant = max(members, key=lambda index: int(planes[index]["inlierCount"]))
257
- plane = dict(planes[dominant])
258
- plane["inlierCount"] = sum(int(planes[index]["inlierCount"]) for index in members)
259
- plane["id"] = remap[root]
260
- merged_planes.append(plane)
261
- for index in members:
262
- merged_assignment[assignment == index] = remap[root]
263
-
264
- return merged_assignment, merged_planes
265
-
266
-
267
- def merge_coplanar_planes(planes: list[dict], distance_threshold: float,
268
- angle_degrees: float = 15.0,
269
- vertical_ref: np.ndarray | None = None) -> list[dict]:
270
- """Fuse fitted planes that describe the same physical surface.
271
-
272
- fit_multi_surface_planes peels planes off one at a time with RANSAC. On a
273
- large flat wall with noisy normals — which is what back-projected depth
274
- gives you — the first pass often claims only part of the wall and a later
275
- pass fits a second, geometrically near-identical plane to the remainder.
276
-
277
- Left alone that splits one wall into several segments, each with its own
278
- transform, so the tile grid breaks visibly at the seam. Raising inference
279
- resolution makes it worse, because finer normals give RANSAC more excuses to
280
- subdivide: a 1600px run split one living-room wall into three.
281
-
282
- Two planes are the same surface when their normals are near-parallel and
283
- each origin lies within `distance_threshold` of the other's plane.
284
- """
285
- if len(planes) <= 1:
286
- return planes
287
-
288
- cos_limit = float(np.cos(np.deg2rad(angle_degrees)))
289
- merged: list[dict] = []
290
- for plane in sorted(planes, key=lambda item: -int(item["inlierCount"])):
291
- normal = np.asarray(plane["normal"], dtype=np.float64)
292
- origin = np.asarray(plane["origin"], dtype=np.float64)
293
- target = None
294
- for candidate in merged:
295
- candidate_normal = np.asarray(candidate["normal"], dtype=np.float64)
296
- candidate_origin = np.asarray(candidate["origin"], dtype=np.float64)
297
- if abs(float(normal @ candidate_normal)) < cos_limit:
298
- continue
299
- if abs(float((origin - candidate_origin) @ candidate_normal)) > distance_threshold:
300
- continue
301
- target = candidate
302
- break
303
-
304
- if target is None:
305
- merged.append(dict(plane))
306
- continue
307
-
308
- # Inlier-weighted average, so the dominant plane keeps its orientation.
309
- target_normal = np.asarray(target["normal"], dtype=np.float64)
310
- if float(normal @ target_normal) < 0:
311
- normal = -normal # opposite-facing fits of one surface
312
- weight_a = float(target["inlierCount"])
313
- weight_b = float(plane["inlierCount"])
314
- total = max(weight_a + weight_b, 1.0)
315
- fused_normal = (target_normal * weight_a + normal * weight_b) / total
316
- norm = float(np.linalg.norm(fused_normal))
317
- if norm > 1e-6:
318
- fused_normal /= norm
319
- else:
320
- fused_normal = target_normal
321
- fused_origin = (
322
- np.asarray(target["origin"], dtype=np.float64) * weight_a + origin * weight_b
323
- ) / total
324
- target["normal"] = fused_normal.astype(np.float32)
325
- target["origin"] = fused_origin.astype(np.float32)
326
- target["offset"] = float(-fused_origin @ fused_normal)
327
- target["inlierCount"] = int(weight_a + weight_b)
328
-
329
- for index, plane in enumerate(merged):
330
- plane["id"] = index
331
- u_axis, v_axis = plane_basis(plane["normal"], bool(plane.get("isFloor")), vertical_ref)
332
- plane["uAxis"] = u_axis
333
- plane["vAxis"] = v_axis
334
- return merged
335
-
336
-
337
  def assign_points_to_surface_planes(
338
  points: np.ndarray,
339
  normals: np.ndarray,
 
4
 
5
  from enums import PlaneFitMode
6
  from config.models import DEPTH_MODEL_NAME
7
+ from config.runtime import ENABLE_MULTI_PLANE_SURFACES
8
  from config.surface import (
9
  SURFACE_MAX_PLANES,
10
  SURFACE_MIN_PLANE_PIXELS,
 
92
  }
93
 
94
 
95
+ def fit_multi_surface_planes(points: np.ndarray, normals: np.ndarray, normals_reliable: bool = True):
 
96
  if len(points) < SURFACE_MIN_PLANE_PIXELS:
97
  return []
98
 
 
150
 
151
  planes = _prune_weak_secondary_planes(planes)
152
 
 
 
 
 
 
153
  floor_id = int(np.argmax([
154
  plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1])))
155
  for plane in planes
156
+ ]))
157
  for idx, plane in enumerate(planes):
158
+ plane["isFloor"] = idx == floor_id
159
+ u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"])
160
  plane["uAxis"] = u_axis
161
  plane["vAxis"] = v_axis
162
  return planes
163
 
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  def assign_points_to_surface_planes(
166
  points: np.ndarray,
167
  normals: np.ndarray,
services/geometry/plane_fitting.py CHANGED
@@ -34,18 +34,7 @@ def refine_plane(points: np.ndarray, normals: np.ndarray | None = None):
34
  return centroid, normal
35
 
36
 
37
- def plane_basis(normal: np.ndarray, is_floor: bool, vertical_ref: np.ndarray | None = None):
38
- """Build (u, v) axes for a plane.
39
-
40
- For a non-floor surface v is world-up projected onto the plane, so tiles run
41
- up the wall. `vertical_ref` is which direction "up" actually is.
42
-
43
- It defaults to +Y, but geometry providers return points in *camera*
44
- coordinates, so +Y is camera-up rather than gravity-up. Any camera tilt then
45
- rotates every wall's tile grid by that same angle. Callers that know the
46
- floor plane should pass its normal: a floor is horizontal by definition, so
47
- its normal is true vertical in whatever frame the points are expressed in.
48
- """
49
  normal = normal.astype(np.float32)
50
  normal /= max(float(np.linalg.norm(normal)), 1e-6)
51
  if is_floor:
@@ -57,21 +46,11 @@ def plane_basis(normal: np.ndarray, is_floor: bool, vertical_ref: np.ndarray | N
57
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
58
  v_axis = np.cross(normal, u_axis)
59
  else:
60
- camera_up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
61
- if vertical_ref is None:
62
- up = camera_up
63
- else:
64
- up = np.asarray(vertical_ref, dtype=np.float32).copy()
65
- length = float(np.linalg.norm(up))
66
- up = camera_up if length < 1e-6 else up / length
67
- # A plane normal has arbitrary sign; keep the axis pointing the same
68
- # way as before so tile orientation does not flip.
69
- if float(up @ camera_up) < 0:
70
- up = -up
71
- v_axis = up - normal * float(up @ normal)
72
  if float(np.linalg.norm(v_axis)) < 1e-5:
73
- up = np.array([0.0, 0.0, 1.0], dtype=np.float32)
74
- v_axis = up - normal * float(up @ normal)
75
  v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6)
76
  u_axis = np.cross(v_axis, normal)
77
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
@@ -93,7 +72,6 @@ def fit_metric_floor_transform(
93
  intrinsics: np.ndarray | None = None,
94
  provider: str = GeometryProvider.METRIC_DEPTH,
95
  surface_kind: str = "floor",
96
- vertical_ref: np.ndarray | None = None,
97
  ):
98
  # Import here to avoid circular dependency with ransac module
99
  from services.geometry.ransac import ransac_plane_fit
@@ -155,7 +133,7 @@ def fit_metric_floor_transform(
155
 
156
  # Use local horizontal/vertical axes for walls and horizontal/depth axes
157
  # for floors. This keeps physical tile dimensions stable across surfaces.
158
- u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall", vertical_ref=vertical_ref)
159
 
160
  projected_points, _ = project_points_to_plane(points[keep], centroid, normal)
161
  floor_points = projected_points - centroid
@@ -224,7 +202,6 @@ def estimate_metric_floor_transform(
224
  provider: str = GeometryProvider.DEPTH_ANYTHING,
225
  intrinsics: np.ndarray | None = None,
226
  surface_kind: str = "floor",
227
- vertical_ref: np.ndarray | None = None,
228
  ):
229
  from config.models import DEPTH_MODEL_NAME
230
  from config.runtime import ENABLE_PLANE_FIT
@@ -242,7 +219,6 @@ def estimate_metric_floor_transform(
242
  intrinsics=pixel_intrinsics,
243
  provider=provider,
244
  surface_kind=surface_kind,
245
- vertical_ref=vertical_ref,
246
  )
247
  if result is not None:
248
  result["depthScale"] = depth_scale
 
34
  return centroid, normal
35
 
36
 
37
+ def plane_basis(normal: np.ndarray, is_floor: bool):
 
 
 
 
 
 
 
 
 
 
 
38
  normal = normal.astype(np.float32)
39
  normal /= max(float(np.linalg.norm(normal)), 1e-6)
40
  if is_floor:
 
46
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
47
  v_axis = np.cross(normal, u_axis)
48
  else:
49
+ vertical_ref = np.array([0.0, 1.0, 0.0], dtype=np.float32)
50
+ v_axis = vertical_ref - normal * float(vertical_ref @ normal)
 
 
 
 
 
 
 
 
 
 
51
  if float(np.linalg.norm(v_axis)) < 1e-5:
52
+ vertical_ref = np.array([0.0, 0.0, 1.0], dtype=np.float32)
53
+ v_axis = vertical_ref - normal * float(vertical_ref @ normal)
54
  v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6)
55
  u_axis = np.cross(v_axis, normal)
56
  u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6)
 
72
  intrinsics: np.ndarray | None = None,
73
  provider: str = GeometryProvider.METRIC_DEPTH,
74
  surface_kind: str = "floor",
 
75
  ):
76
  # Import here to avoid circular dependency with ransac module
77
  from services.geometry.ransac import ransac_plane_fit
 
133
 
134
  # Use local horizontal/vertical axes for walls and horizontal/depth axes
135
  # for floors. This keeps physical tile dimensions stable across surfaces.
136
+ u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall")
137
 
138
  projected_points, _ = project_points_to_plane(points[keep], centroid, normal)
139
  floor_points = projected_points - centroid
 
202
  provider: str = GeometryProvider.DEPTH_ANYTHING,
203
  intrinsics: np.ndarray | None = None,
204
  surface_kind: str = "floor",
 
205
  ):
206
  from config.models import DEPTH_MODEL_NAME
207
  from config.runtime import ENABLE_PLANE_FIT
 
219
  intrinsics=pixel_intrinsics,
220
  provider=provider,
221
  surface_kind=surface_kind,
 
222
  )
223
  if result is not None:
224
  result["depthScale"] = depth_scale
services/geometry/uv_mapping.py CHANGED
@@ -19,7 +19,6 @@ from services.geometry.multi_plane import (
19
  assign_points_to_surface_planes,
20
  fit_multi_surface_planes,
21
  geometry_point_maps,
22
- merge_coplanar_planes,
23
  )
24
  from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold
25
 
@@ -29,7 +28,6 @@ def analyze_surface_uv_quality(
29
  surface_indices: np.ndarray,
30
  uv_by_mask: np.ndarray,
31
  plane_ids: np.ndarray,
32
- min_coverage: float = SURFACE_UV_MIN_COVERAGE,
33
  ) -> dict:
34
  total_pixels = int(len(surface_indices))
35
  finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool)
@@ -61,7 +59,7 @@ def analyze_surface_uv_quality(
61
  if total_pixels == 0:
62
  quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE
63
  return quality
64
- if coverage < min_coverage:
65
  quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV
66
  return quality
67
  h, w = surface_mask.shape[:2]
@@ -130,23 +128,6 @@ def build_surface_uv_mapping(
130
  geometry: dict | None,
131
  *,
132
  geometry_maps: dict | None = None,
133
- mark_floor: bool = True,
134
- min_coverage: float | None = None,
135
- # Depth is noisy exactly where a surface is hardest to see -- at grazing
136
- # angles, in corners, behind furniture -- so a minority of pixels always
137
- # sits too far off the fitted plane to be assigned a UV from their own 3D
138
- # points. Left unfilled they keep NaN, coverage drops below the gate, and
139
- # the whole per-pixel mapping is discarded for a single homography. For a
140
- # floor that means the regularized-plane quad, a straight-edged trapezoid
141
- # that under-covers the mask at the corners.
142
- #
143
- # The plane and the camera are both known, so a UV exists regardless of
144
- # depth: intersect the pixel's ray with the plane. Defaulted on because
145
- # that is the right answer for any surface -- it was off only because the
146
- # fill was written for walls and floors were left on the old path.
147
- fill_missing_from_plane: bool = True,
148
- vertical_ref: np.ndarray | None = None,
149
- precomputed_planes: list[dict] | None = None,
150
  ):
151
  total_started = time.perf_counter()
152
  phase_started = total_started
@@ -204,20 +185,7 @@ def build_surface_uv_mapping(
204
  )
205
 
206
  phase_started = time.perf_counter()
207
- if precomputed_planes is not None:
208
- # Reuse planes already fitted during wall discovery — avoids a
209
- # duplicate RANSAC × max_planes pass.
210
- planes = list(precomputed_planes)
211
- else:
212
- planes = fit_multi_surface_planes(points, normals, normals_reliable, mark_floor=mark_floor,
213
- vertical_ref=vertical_ref)
214
- if not mark_floor:
215
- # One flat wall attracts several near-identical RANSAC planes when
216
- # normals are noisy. Distinct plane ids mean distinct UV origins, so
217
- # the tile grid would restart mid-wall. Floors keep the original
218
- # behaviour untouched.
219
- planes = merge_coplanar_planes(planes, surface_distance_threshold(points),
220
- vertical_ref=vertical_ref)
221
  plane_fit_ms = (time.perf_counter() - phase_started) * 1000
222
  if not planes:
223
  print(
@@ -268,59 +236,6 @@ def build_surface_uv_mapping(
268
  plane_ids[assigned_positions] = plane_idx
269
  plane["assignedCount"] = int(assigned_keep.sum())
270
 
271
- if fill_missing_from_plane and planes:
272
- # Pixels with no usable depth still belong to the surface: on a wall they
273
- # are the TV, the mirror, the cabinet standing in front of it. Their 3D
274
- # points describe the *object*, not the wall, so plane assignment leaves
275
- # them without UV and coverage collapses (0.78 on one living-room wall).
276
- #
277
- # We know the plane and the camera, so a UV exists regardless of depth:
278
- # intersect each pixel's camera ray with the plane. That both restores
279
- # coverage and makes the tile grid continue correctly behind the object,
280
- # which is what tiling *behind* an occluder is supposed to look like.
281
- missing = ~np.isfinite(uv_by_mask).all(axis=1)
282
- if missing.any():
283
- dominant_idx = int(np.argmax([
284
- int(plane.get("assignedCount", 0)) or int(plane["inlierCount"])
285
- for plane in planes
286
- ]))
287
- dominant = planes[dominant_idx]
288
- width = surface_mask.shape[1]
289
- flat = surface_indices[missing].astype(np.int64)
290
- pixel_y = (flat // width).astype(np.float32)
291
- pixel_x = (flat % width).astype(np.float32)
292
- intrinsics = np.asarray(maps["intrinsics"], dtype=np.float32)
293
- fx = float(intrinsics[0, 0]) or 1.0
294
- fy = float(intrinsics[1, 1]) or 1.0
295
- cx, cy = float(intrinsics[0, 2]), float(intrinsics[1, 2])
296
- rays = np.column_stack((
297
- (pixel_x - cx) / fx,
298
- (pixel_y - cy) / fy,
299
- np.ones(len(pixel_x), dtype=np.float32),
300
- )).astype(np.float32)
301
- normal = np.asarray(dominant["normal"], dtype=np.float32)
302
- origin = np.asarray(dominant["origin"], dtype=np.float32)
303
- denominator = rays @ normal
304
- usable = np.abs(denominator) > 1e-6
305
- distances = np.zeros(len(rays), dtype=np.float32)
306
- distances[usable] = float(origin @ normal) / denominator[usable]
307
- usable &= distances > 0 # plane behind the camera is not a hit
308
- if usable.any():
309
- hit = rays[usable] * distances[usable, None]
310
- delta = hit - origin
311
- filled_uv = np.column_stack((
312
- delta @ np.asarray(dominant["uAxis"], dtype=np.float32),
313
- delta @ np.asarray(dominant["vAxis"], dtype=np.float32),
314
- )).astype(np.float32)
315
- target = np.where(missing)[0][usable]
316
- uv_by_mask[target] = filled_uv
317
- plane_ids[target] = dominant_idx
318
- print(
319
- f"[SURFACE_MAPPING] ray-plane filled {int(usable.sum())} "
320
- f"occluded pixels from plane {dominant_idx}",
321
- flush=True,
322
- )
323
-
324
  serializable_planes = []
325
  for plane in planes:
326
  assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
@@ -351,10 +266,7 @@ def build_surface_uv_mapping(
351
 
352
  phase_started = time.perf_counter()
353
  finite_uv = np.isfinite(uv_by_mask).all(axis=1)
354
- uv_quality = analyze_surface_uv_quality(
355
- surface_mask, surface_indices, uv_by_mask, plane_ids,
356
- min_coverage=SURFACE_UV_MIN_COVERAGE if min_coverage is None else min_coverage,
357
- )
358
  quality_ms = (time.perf_counter() - phase_started) * 1000
359
  uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
360
  uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
 
19
  assign_points_to_surface_planes,
20
  fit_multi_surface_planes,
21
  geometry_point_maps,
 
22
  )
23
  from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold
24
 
 
28
  surface_indices: np.ndarray,
29
  uv_by_mask: np.ndarray,
30
  plane_ids: np.ndarray,
 
31
  ) -> dict:
32
  total_pixels = int(len(surface_indices))
33
  finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool)
 
59
  if total_pixels == 0:
60
  quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE
61
  return quality
62
+ if coverage < SURFACE_UV_MIN_COVERAGE:
63
  quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV
64
  return quality
65
  h, w = surface_mask.shape[:2]
 
128
  geometry: dict | None,
129
  *,
130
  geometry_maps: dict | None = None,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  ):
132
  total_started = time.perf_counter()
133
  phase_started = total_started
 
185
  )
186
 
187
  phase_started = time.perf_counter()
188
+ planes = fit_multi_surface_planes(points, normals, normals_reliable)
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  plane_fit_ms = (time.perf_counter() - phase_started) * 1000
190
  if not planes:
191
  print(
 
236
  plane_ids[assigned_positions] = plane_idx
237
  plane["assignedCount"] = int(assigned_keep.sum())
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  serializable_planes = []
240
  for plane in planes:
241
  assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])]
 
266
 
267
  phase_started = time.perf_counter()
268
  finite_uv = np.isfinite(uv_by_mask).all(axis=1)
269
+ uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
 
 
 
270
  quality_ms = (time.perf_counter() - phase_started) * 1000
271
  uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
272
  uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
services/pipeline/builder.py CHANGED
@@ -251,34 +251,27 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
251
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
252
  wall_components = []
253
  wall_protected_mask = None
254
- # Raw point maps (MoGe) are independent of the surface mask. Reuse the
255
- # floor's prepared normals instead of smoothing the entire image again for
256
- # every wall region and every wall UV map.
257
- wall_geometry_maps = (
258
- prepared_geometry_maps
259
- if geometry is not None and geometry.get("points") is not None
260
- else None
261
- )
262
-
263
- # --- Wall discovery: overlap with floor processing ---
264
- # Wall discovery only needs seg_map + geometry, both available now. Running
265
- # it concurrently with surface masking / UV mapping / lighting hides its
266
- # cost behind work that has to happen anyway.
267
- from concurrent.futures import ThreadPoolExecutor, Future
268
- _wall_discovery_future: Future | None = None
269
- _wall_discovery_started: float = 0.0
270
  if ENABLE_WALL_SEGMENTS:
271
- _wall_discovery_started = time.perf_counter()
272
- _wall_pool = ThreadPoolExecutor(max_workers=1)
273
- _wall_discovery_future = _wall_pool.submit(
274
- wall_surface_components,
275
  seg_map, min_floor_area, geometry,
276
- image_rgb=img_np, geometry_maps=wall_geometry_maps,
277
  )
 
278
 
279
- wall_lighting_enabled = (
280
- ENABLE_INTRINSIC_SHADING or ENABLE_FAST_SHADOW_TRANSFER or ENABLE_SHADING_TRANSFER
281
- )
 
 
 
 
 
 
 
 
 
 
 
282
 
283
  if progress_callback:
284
  progress_callback(PipelinePhase.LIGHTING, 100)
@@ -316,11 +309,16 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
316
  if progress_callback:
317
  progress_callback(PipelinePhase.DIRECTION, 100)
318
 
319
- # --- Collect wall discovery (was running in parallel) ---
320
- if _wall_discovery_future is not None:
321
- wall_components, wall_protected_mask = _wall_discovery_future.result()
322
- _wall_pool.shutdown(wait=False)
323
- _log_stage("Wall Discovery (async)", _wall_discovery_started, f"components={len(wall_components)}")
 
 
 
 
 
324
 
325
  # --- Package segments ---
326
  if progress_callback:
@@ -340,49 +338,13 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
340
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
341
  shade_statistics=shade_statistics, lighting_source=lighting_source,
342
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
343
- # A floor is horizontal by definition, so its normal is true vertical in
344
- # whatever frame the point cloud uses. Walls need that rather than +Y,
345
- # which is camera-up and tilts the tile grid with the camera.
346
- floor_up = None
347
- if surface_mapping is not None:
348
- for candidate in (surface_mapping.get('planes') or []):
349
- if candidate.get('isFloor'):
350
- floor_up = np.asarray(candidate['normal'], dtype=np.float32)
351
- break
352
- if floor_up is not None:
353
- print(f'[WALL_UP] using floor normal as vertical: {floor_up.round(3).tolist()}', flush=True)
354
-
355
- # --- Parallel wall packaging ---
356
- # Each build_wall_segment is independent (no shared mutable state).
357
- wall_segments = []
358
- if wall_components:
359
- def _package_one_wall(wi_cm_planes):
360
- wi, cm, planes = wi_cm_planes
361
- return build_wall_segment(
362
- wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
363
- precomputed_lighting=None,
364
- up_vector=floor_up,
365
- lighting_enabled=wall_lighting_enabled,
366
- geometry_maps=wall_geometry_maps,
367
- precomputed_planes=planes,
368
- )
369
-
370
- wall_args = [(wi, cm, planes) for wi, (_, cm, planes) in enumerate(wall_components)]
371
- if len(wall_args) > 1:
372
- with ThreadPoolExecutor(max_workers=min(4, len(wall_args))) as wall_pkg_pool:
373
- wall_results = list(wall_pkg_pool.map(_package_one_wall, wall_args))
374
- else:
375
- wall_results = [_package_one_wall(wall_args[0])]
376
- for ws in wall_results:
377
- if ws:
378
- segments.append(ws)
379
- wall_segments.append(ws)
380
-
381
- # Only when wall discovery actually ran. With ENABLE_WALL_SEGMENTS off
382
- # there is no protected mask and nothing to report.
383
- if d and ENABLE_WALL_SEGMENTS:
384
- debug_stages.record_walls(d, img_np, wall_mask, wall_protected_mask, wall_components,
385
- wall_segments, (time.perf_counter() - t0) * 1000)
386
  if not segments:
387
  segments = build_fallback_segments(seg_map, depth, models)
388
 
 
251
  wall_mask = seg_class_mask(seg_map, class_ids({"wall"}))
252
  wall_components = []
253
  wall_protected_mask = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  if ENABLE_WALL_SEGMENTS:
255
+ t0 = time.perf_counter()
256
+ wall_components, wall_protected_mask = wall_surface_components(
 
 
257
  seg_map, min_floor_area, geometry,
 
258
  )
259
+ _log_stage("Wall Discovery", t0, f"components={len(wall_components)}")
260
 
261
+ # --- Pre-compute wall lighting in parallel with floor direction ---
262
+ # Wall lighting was previously computed inside build_wall_segment (in the
263
+ # "Packaging" phase), adding ~5s for large images. Moving it here lets it
264
+ # overlap with floor-direction detection.
265
+ from concurrent.futures import ThreadPoolExecutor, Future
266
+
267
+ def _compute_wall_lighting(component_mask):
268
+ return build_luminance_lighting_maps(img_np, component_mask)
269
+
270
+ wall_lighting_futures: list[Future] = []
271
+ wall_executor = ThreadPoolExecutor(max_workers=max(1, len(wall_components))) if wall_components else None
272
+ if wall_executor:
273
+ for _, cm in wall_components:
274
+ wall_lighting_futures.append(wall_executor.submit(_compute_wall_lighting, cm))
275
 
276
  if progress_callback:
277
  progress_callback(PipelinePhase.LIGHTING, 100)
 
309
  if progress_callback:
310
  progress_callback(PipelinePhase.DIRECTION, 100)
311
 
312
+ # Collect pre-computed wall lighting results
313
+ wall_lighting_results: list[dict | None] = []
314
+ if wall_executor:
315
+ t0 = time.perf_counter()
316
+ for fut in wall_lighting_futures:
317
+ wall_lighting_results.append(fut.result())
318
+ wall_executor.shutdown(wait=False)
319
+ _log_stage("Wall Lighting Wait", t0, f"components={len(wall_components)}")
320
+ else:
321
+ wall_lighting_results = [None] * len(wall_components)
322
 
323
  # --- Package segments ---
324
  if progress_callback:
 
338
  edge_metadata=edge_metadata, mapping_metadata=mapping_metadata,
339
  shade_statistics=shade_statistics, lighting_source=lighting_source,
340
  intrinsic_lighting_used=intrinsic_lighting_used, models=models, depth=depth, geometry=geometry))
341
+ for wi, (_, cm) in enumerate(wall_components):
342
+ ws = build_wall_segment(
343
+ wi, cm, wall_protected_mask, geometry, img_np, wall_components, models,
344
+ precomputed_lighting=wall_lighting_results[wi] if wi < len(wall_lighting_results) else None,
345
+ )
346
+ if ws:
347
+ segments.append(ws)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
  if not segments:
349
  segments = build_fallback_segments(seg_map, depth, models)
350
 
services/pipeline/bundle_assembly.py CHANGED
@@ -21,10 +21,8 @@ from config.runtime import (
21
  ENABLE_SAM_REFINEMENT,
22
  ENABLE_SHADING_TRANSFER,
23
  )
24
- from config.surface import SURFACE_UV_WALL_MIN_COVERAGE
25
  from models.segmentation import segmenter_metadata_name
26
  from state import class_ids, class_name_for_id
27
- from services.geometry.uv_mapping import build_surface_uv_mapping
28
  from services.lighting.shading import build_luminance_lighting_maps
29
  from services.wall.plane import estimate_wall_plane
30
  from enums import SurfaceType, TextureMappingMode
@@ -143,57 +141,13 @@ def build_wall_segment(
143
  wall_components: list,
144
  models: dict,
145
  precomputed_lighting: dict | None = None,
146
- up_vector=None,
147
- lighting_enabled: bool = True,
148
- geometry_maps: dict | None = None,
149
- precomputed_planes: list[dict] | None = None,
150
  ) -> dict | None:
151
- # True vertical, taken from the floor, reaches the plane fit as well as the
152
- # UV mapping below. The plane's basis is what the renderer falls back to
153
- # when there is no per-pixel UV, and its extents are what tile density is
154
- # computed from, so a camera-aligned basis here tilts and mis-scales the
155
- # grid even when the UV path is gravity-aligned.
156
- wall_homography, wall_plane = estimate_wall_plane(
157
- component_mask, geometry, vertical_ref=up_vector
158
- )
159
  if wall_homography is None or wall_plane is None:
160
  return None
161
- # The flag wins over a pre-computed map, so lighting cannot leak back in
162
- # from a stale hand-off. Checked before the fallback too: skipping only the
163
- # caller's pre-compute would move this work into packaging rather than
164
- # remove it, and serially at that.
165
- if not lighting_enabled:
166
- wall_lighting_maps = None
167
- elif precomputed_lighting is not None:
168
- wall_lighting_maps = precomputed_lighting
169
- else:
170
- wall_lighting_maps = build_luminance_lighting_maps(img_np, component_mask)
171
  wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
172
- # Only objects sitting on *this* wall occlude it. Shipping the global
173
- # protected mask made every wall claim every mirror, cabinet and door in the
174
- # room, so the renderer punched other walls' furniture through this one.
175
- # Intersecting with the component also excludes barrier classes for free,
176
- # because a refined component never contains them.
177
- wall_occlusion_mask = (wall_protected_mask > 0) & (component_mask > 0)
178
- wall_occlusion_indices = np.flatnonzero(wall_occlusion_mask.ravel()).astype(np.uint32)
179
-
180
- # Per-pixel UV, exactly as the floor gets it. Walls previously shipped a
181
- # single homography, so tile scale came from the wall's bounding box rather
182
- # than from measured geometry. mark_floor=False keeps the UV basis
183
- # gravity-aligned: v runs up the wall, u runs along it.
184
- wall_mapping = build_surface_uv_mapping(
185
- component_mask, wall_indices, geometry,
186
- geometry_maps=geometry_maps,
187
- mark_floor=False, min_coverage=SURFACE_UV_WALL_MIN_COVERAGE,
188
- fill_missing_from_plane=True,
189
- # True vertical, taken from the floor. Geometry providers work in
190
- # camera coordinates, so assuming +Y is up rotates every wall's tile
191
- # grid by the camera's tilt.
192
- vertical_ref=up_vector,
193
- precomputed_planes=precomputed_planes,
194
- )
195
- use_wall_uv = bool(wall_mapping and wall_mapping.get("useSurfaceUv"))
196
- wall_mapping_metadata = wall_mapping["metadata"] if wall_mapping is not None else {}
197
  wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
198
  wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
199
  wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
@@ -207,10 +161,9 @@ def build_wall_segment(
207
  "floorTransform": wall_plane.get("floorTransform"),
208
  "surfaceTransform": wall_plane.get("surfaceTransform"),
209
  "plane": wall_plane,
210
- # Raw numpy arrays; packaging writes them straight to disk as lazy assets.
211
- "surfaceUv": wall_mapping["uv"].astype(np.float32) if use_wall_uv else None,
212
- "surfacePlaneIds": wall_mapping["planeIds"].astype(np.uint8) if use_wall_uv else None,
213
- "surfacePlanes": wall_mapping["planes"] if wall_mapping is not None else None,
214
  "shadeMap": wall_shade_map,
215
  "showroomShadeMap": wall_showroom,
216
  "reflectionMap": wall_reflection,
@@ -220,18 +173,11 @@ def build_wall_segment(
220
  "wallPixels": int(component_mask.sum()),
221
  "wallComponent": wall_index,
222
  "wallComponentCount": len(wall_components),
223
- "protectedPixels": int(wall_occlusion_mask.sum()),
224
  "shadingEnabled": wall_shade_map is not None,
225
  "reflectionTransferEnabled": wall_reflection is not None,
226
- # Spread first so the explicit mode below wins: the UV analyzer
227
- # reports REGULARIZED_FLOOR_PLANE when it declines, which is not a
228
- # meaningful value for a wall.
229
- **wall_mapping_metadata,
230
- "surfaceUvEnabled": use_wall_uv,
231
  "textureMappingMode": (
232
- TextureMappingMode.SURFACE_UV if use_wall_uv
233
- else TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform")
234
- else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
235
  ),
236
  "geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
237
  "geometryProvider": wall_plane.get("geometryProvider"),
 
21
  ENABLE_SAM_REFINEMENT,
22
  ENABLE_SHADING_TRANSFER,
23
  )
 
24
  from models.segmentation import segmenter_metadata_name
25
  from state import class_ids, class_name_for_id
 
26
  from services.lighting.shading import build_luminance_lighting_maps
27
  from services.wall.plane import estimate_wall_plane
28
  from enums import SurfaceType, TextureMappingMode
 
141
  wall_components: list,
142
  models: dict,
143
  precomputed_lighting: dict | None = None,
 
 
 
 
144
  ) -> dict | None:
145
+ wall_homography, wall_plane = estimate_wall_plane(component_mask, geometry)
 
 
 
 
 
 
 
146
  if wall_homography is None or wall_plane is None:
147
  return None
148
+ wall_lighting_maps = precomputed_lighting if precomputed_lighting is not None else build_luminance_lighting_maps(img_np, component_mask)
 
 
 
 
 
 
 
 
 
149
  wall_indices = np.flatnonzero(component_mask.ravel()).astype(np.uint32)
150
+ wall_occlusion_indices = np.flatnonzero(wall_protected_mask.ravel()).astype(np.uint32)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  wall_shade_map = wall_lighting_maps.get("shadeMap") if wall_lighting_maps else None
152
  wall_showroom = wall_lighting_maps.get("showroomShadeMap") if wall_lighting_maps else None
153
  wall_reflection = wall_lighting_maps.get("reflectionMap") if wall_lighting_maps else None
 
161
  "floorTransform": wall_plane.get("floorTransform"),
162
  "surfaceTransform": wall_plane.get("surfaceTransform"),
163
  "plane": wall_plane,
164
+ "surfaceUv": None,
165
+ "surfacePlaneIds": None,
166
+ "surfacePlanes": None,
 
167
  "shadeMap": wall_shade_map,
168
  "showroomShadeMap": wall_showroom,
169
  "reflectionMap": wall_reflection,
 
173
  "wallPixels": int(component_mask.sum()),
174
  "wallComponent": wall_index,
175
  "wallComponentCount": len(wall_components),
176
+ "protectedPixels": int(wall_protected_mask.sum()),
177
  "shadingEnabled": wall_shade_map is not None,
178
  "reflectionTransferEnabled": wall_reflection is not None,
 
 
 
 
 
179
  "textureMappingMode": (
180
+ TextureMappingMode.WALL_PLANE if wall_plane.get("surfaceTransform") else TextureMappingMode.WALL_CONTOUR_HOMOGRAPHY
 
 
181
  ),
182
  "geometryConfidence": wall_plane.get("geometryConfidence", 0.0),
183
  "geometryProvider": wall_plane.get("geometryProvider"),
services/pipeline/debug_stages.py CHANGED
@@ -15,7 +15,6 @@ from services.debug.overlays import (
15
  debug_segmentation_overlay,
16
  debug_surface_overlay,
17
  debug_uv_checkerboard,
18
- debug_wall_components_overlay,
19
  )
20
  from state import class_name_for_id
21
 
@@ -61,59 +60,6 @@ def record_floor_mask(debug: PipelineDebugCapture, img_np, raw_mask, cleaned_mas
61
  )
62
 
63
 
64
- def record_walls(debug: PipelineDebugCapture, img_np, raw_wall_mask, protected_mask,
65
- components, wall_segments, elapsed_ms):
66
- """Record wall detection so the wall path is inspectable like the floor path.
67
-
68
- Three views answer the three ways wall detection goes wrong:
69
- * Raw wall class - did segmentation find the wall at all?
70
- * Protected (removed) - what wall_surface_components() strips out before
71
- splitting (mirrors, doors, windows, curtains,
72
- paintings, occluders). Holes here become holes in
73
- the tiled result.
74
- * Wall components - how the wall was split into renderable regions.
75
- Followed by one plane overlay per accepted wall segment.
76
- """
77
- # The protected mask only exists when wall discovery ran. With walls
78
- # switched off there is nothing to show, and diagnostics must not be what
79
- # takes a conversion down -- turning walls off is how the feature gets
80
- # backed out, so a crash here would break the rollback itself.
81
- images = [("Raw wall class", debug_mask_overlay(img_np, raw_wall_mask))]
82
- if protected_mask is not None:
83
- images.append(
84
- ("Protected (removed)", debug_mask_overlay(img_np, protected_mask, (220, 80, 80)))
85
- )
86
- images.append(("Wall components", debug_wall_components_overlay(img_np, components)))
87
- for index, segment in enumerate(wall_segments):
88
- plane = segment.get("plane") if isinstance(segment, dict) else None
89
- if plane:
90
- images.append((f"Wall {index + 1} plane", debug_plane_overlay(img_np, plane)))
91
-
92
- component_pixels = [int(item[1].sum()) for item in components]
93
- debug.record_images(
94
- "wall-surfaces", "Wall surfaces",
95
- "Wall mask, the protected classes removed before splitting, and the resulting "
96
- "renderable wall components with their fitted planes.",
97
- images,
98
- {
99
- "rawWallPixels": int(raw_wall_mask.sum()),
100
- "protectedPixels": int(protected_mask.sum()) if protected_mask is not None else 0,
101
- "componentCount": len(components),
102
- "componentPixels": component_pixels,
103
- "acceptedWallSegments": len(wall_segments),
104
- "textureMappingModes": [
105
- (s.get("metadata") or {}).get("textureMappingMode")
106
- for s in wall_segments if isinstance(s, dict)
107
- ],
108
- "surfaceUvAvailable": [
109
- bool(s.get("surfaceUv") is not None)
110
- for s in wall_segments if isinstance(s, dict)
111
- ],
112
- },
113
- elapsed_ms,
114
- )
115
-
116
-
117
  def record_geometry(debug: PipelineDebugCapture, depth, floor_mask, geometry, elapsed_ms):
118
  imgs = [("Depth", debug_scalar_map(depth, floor_mask))] if depth is not None else []
119
  debug.record_images(
 
15
  debug_segmentation_overlay,
16
  debug_surface_overlay,
17
  debug_uv_checkerboard,
 
18
  )
19
  from state import class_name_for_id
20
 
 
60
  )
61
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  def record_geometry(debug: PipelineDebugCapture, depth, floor_mask, geometry, elapsed_ms):
64
  imgs = [("Depth", debug_scalar_map(depth, floor_mask))] if depth is not None else []
65
  debug.record_images(
services/pipeline/packaging.py CHANGED
@@ -12,11 +12,7 @@ import numpy as np
12
  from PIL import Image
13
 
14
  from config.paths import JOB_DIR
15
- from config.runtime import (
16
- BUNDLE_COMPRESSION_LEVEL,
17
- BUNDLE_IMAGE_FORMAT,
18
- BUNDLE_IMAGE_QUALITY,
19
- )
20
  from state import OCCLUDER_CLASSES, class_ids
21
  from utils import seg_class_mask
22
 
@@ -181,15 +177,7 @@ def build_manifest_segmentation_bundle(
181
  asset_dir.mkdir(parents=True, exist_ok=True)
182
 
183
  buffer = io.BytesIO()
184
- compression = (
185
- zipfile.ZIP_DEFLATED if BUNDLE_COMPRESSION_LEVEL > 0 else zipfile.ZIP_STORED
186
- )
187
- with zipfile.ZipFile(
188
- buffer,
189
- "w",
190
- compression=compression,
191
- compresslevel=BUNDLE_COMPRESSION_LEVEL or None,
192
- ) as archive:
193
  if include_image:
194
  pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
195
  image_path = f"image.{bundle_image_extension(pixels_mime)}"
 
12
  from PIL import Image
13
 
14
  from config.paths import JOB_DIR
15
+ from config.runtime import BUNDLE_IMAGE_FORMAT, BUNDLE_IMAGE_QUALITY
 
 
 
 
16
  from state import OCCLUDER_CLASSES, class_ids
17
  from utils import seg_class_mask
18
 
 
177
  asset_dir.mkdir(parents=True, exist_ok=True)
178
 
179
  buffer = io.BytesIO()
180
+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_STORED) as archive:
 
 
 
 
 
 
 
 
181
  if include_image:
182
  pixels_mime, pixels = data_url_to_bytes(bundle["pixels"])
183
  image_path = f"image.{bundle_image_extension(pixels_mime)}"
services/wall/components.py CHANGED
@@ -13,137 +13,24 @@ from services.geometry.multi_plane import (
13
  assign_points_to_surface_planes,
14
  fit_multi_surface_planes,
15
  geometry_point_maps,
16
- merge_coplanar_planes,
17
- merge_planes_by_point_consistency,
18
  )
19
  from services.geometry.normals import normalize_vectors
20
- from services.geometry.plane_fitting import surface_distance_threshold
21
- from services.wall.corner import straighten_piece_seams
22
- from services.wall.mask import refine_wall_component_mask, wall_region_masks
23
  from state import OCCLUDER_CLASSES, class_ids
24
  from utils import seg_class_mask
25
 
26
 
27
- def split_region_if_not_planar(region: np.ndarray, geometry: dict | None, min_area: int,
28
- *, geometry_maps: dict | None = None):
29
- """Return [(mask, planes)] tuples — one flat wall or several split pieces.
30
-
31
- Each returned item is ``(mask, planes_list)`` where *planes_list* carries
32
- the fitted plane dicts so downstream stages can skip a duplicate RANSAC.
33
-
34
- Connectivity alone is not quite enough: where two walls meet at a corner
35
- with nothing between them, segmentation bridges the corner and hands us one
36
- region covering both. Those need separating, or one warped transform gets
37
- stretched across an angle.
38
-
39
- So geometry gets a narrow, well-posed job: decide whether this region is
40
- flat. A single least-squares plane is fitted and the 90th-percentile
41
- residual measured. A real wall sits within a couple of centimetres of its
42
- own plane; a region spanning a corner does not come close. Only when the
43
- region fails that test do we fall back to multi-plane splitting.
44
- """
45
- if geometry is None:
46
- return [(region, None)]
47
- maps = geometry_maps if geometry_maps is not None else geometry_point_maps(region, geometry)
48
- if maps is None:
49
- return [(region, None)]
50
-
51
- valid = maps["validMask"] & (region > 0)
52
- ys, xs = np.where(valid)
53
- if len(xs) < SURFACE_MIN_PLANE_PIXELS:
54
- return [(region, None)]
55
- points = maps["points"][ys, xs].astype(np.float32)
56
- normals = maps["normals"][ys, xs].astype(np.float32)
57
- finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
58
- points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
59
- if len(points) < SURFACE_MIN_PLANE_PIXELS:
60
- return [(region, None)]
61
-
62
- threshold = surface_distance_threshold(points)
63
- centered = points - points.mean(axis=0)
64
- # Smallest-eigenvalue eigenvector of the covariance is the plane normal.
65
- _eigenvalues, eigenvectors = np.linalg.eigh(centered.T @ centered)
66
- residual = np.abs(centered @ eigenvectors[:, 0].astype(np.float32))
67
- flatness = float(np.percentile(residual, 90))
68
- print(
69
- f"[WALL_REGION] {int(region.sum())} px p90Flatness={flatness:.3f}m "
70
- f"threshold={threshold:.3f}m {'FLAT (keep whole)' if flatness <= threshold else 'not flat -> split by plane'}",
71
- flush=True,
72
- )
73
- if flatness <= threshold:
74
- return [(region, None)]
75
-
76
- lengths = np.linalg.norm(normals, axis=1)
77
- usable = lengths > 1e-4
78
- if int(usable.sum()) < SURFACE_MIN_PLANE_PIXELS:
79
- return [(region, None)]
80
- points, ys, xs = points[usable], ys[usable], xs[usable]
81
- normals = normalize_vectors(normals[usable])
82
-
83
- planes = fit_multi_surface_planes(points, normals, True, mark_floor=False)
84
- planes = merge_coplanar_planes(planes, threshold)
85
- wall_planes = [plane for plane in planes if abs(float(plane["normal"][1])) <= 0.45]
86
- if len(wall_planes) <= 1:
87
- return [(region, wall_planes if wall_planes else None)]
88
-
89
- assignment = assign_points_to_surface_planes(points, normals, wall_planes, True)
90
- assignment, wall_planes = merge_planes_by_point_consistency(
91
- points, assignment, wall_planes, threshold
92
- )
93
- if len(wall_planes) <= 1:
94
- return [(region, wall_planes if wall_planes else None)]
95
-
96
- pieces = []
97
- for plane_index in range(len(wall_planes)):
98
- selected = assignment == plane_index
99
- if int(selected.sum()) < min_area:
100
- continue
101
- piece = np.zeros_like(region)
102
- piece[ys[selected], xs[selected]] = 1
103
- pieces.append((plane_index, piece))
104
- if not pieces:
105
- return [(region, None)]
106
-
107
- # Per-pixel assignment is the wrong tool for the seam *between* these
108
- # pieces. At the corner every plane is equidistant, so the score collapses
109
- # onto blended depth normals and the boundary ends up both biased and
110
- # ragged. Put each seam back on the line where its two planes actually
111
- # intersect -- see services/wall/corner.py for the measurements.
112
- straightened = straighten_piece_seams(pieces, wall_planes, maps.get("intrinsics"), min_area)
113
- result = []
114
- for i, mask in enumerate(straightened):
115
- plane_idx = pieces[i][0] if i < len(pieces) else 0
116
- piece_plane = [wall_planes[plane_idx]] if plane_idx < len(wall_planes) else None
117
- result.append((mask, piece_plane))
118
- return result
119
-
120
-
121
- def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None,
122
- image_rgb: np.ndarray | None = None,
123
- *, geometry_maps: dict | None = None):
124
  """Create clean, independently renderable wall regions.
125
 
126
- Returns ``(components, protected)`` where each component is
127
- ``(area, mask, precomputed_planes)`` — the planes fitted during discovery
128
- so downstream stages can reuse them instead of running RANSAC again.
129
-
130
  Semantic wall predictions often bridge across corners and openings. Removing
131
  protected classes before connected-component analysis prevents one warped
132
  transform from being applied to several physically different walls.
133
  """
134
- # Components may occupy the wall itself plus anything mounted on it; those
135
- # objects are re-drawn over the tile via the segment occlusion mask instead
136
- # of being cut out of the surface. See services/wall/mask.py.
137
- wall_raw, barrier_mask, reclaimable_mask = wall_region_masks(seg_map)
138
-
139
- wall = wall_raw.copy()
140
  protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
141
  "door", "window", "column", "base", "railing", "ceiling",
142
  "building", "painting", "mirror", "curtain",
143
  }))
144
- # Wide enough to close the gap a wall-mounted TV or mirror leaves behind,
145
- # narrow enough that a doorway or a room corner still separates two walls.
146
- bridge_kernel_size = max(3, int(round(min(seg_map.shape[:2]) * 0.05))) | 1
147
  radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
148
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
149
  protected = cv2.dilate(protected, kernel, iterations=1)
@@ -152,70 +39,54 @@ def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict |
152
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
153
  wall[protected > 0] = 0
154
 
155
- # --- Stage 1: connectivity decides what counts as one wall ----------------
156
- # Geometry used to decide this, by fitting planes over every wall pixel and
157
- # assigning each pixel to its nearest plane. Per-pixel normals from depth are
158
- # noisy, so that assignment banded single walls into vertical depth slabs: a
159
- # living room with three walls produced three planes but five segments, each
160
- # with its own UV frame, so the tile grid restarted and rotated at every
161
- # seam. Spatial connectivity is far more reliable for "is this one wall",
162
- # because walls are separated by corners, which are visible discontinuities.
163
- bridge = cv2.morphologyEx(
164
- wall,
165
- cv2.MORPH_CLOSE,
166
- cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (bridge_kernel_size, bridge_kernel_size)),
167
- )
168
- region_count, region_labels, _region_stats, _ = cv2.connectedComponentsWithStats(
169
- bridge, connectivity=8
170
- )
171
- regions = []
172
- for region_id in range(1, region_count):
173
- region = ((region_labels == region_id) & (wall > 0)).astype(np.uint8)
174
- if int(region.sum()) >= min_area:
175
- regions.append(region)
176
- print(f"[WALL_COMPONENTS] {len(regions)} connected wall region(s)", flush=True)
177
-
178
- # --- Stage 2: geometry only splits a region that is not actually flat -----
179
- # components is a list of (area, mask, planes) tuples; planes are carried
180
- # through so build_wall_segment can skip a duplicate RANSAC.
181
  components = []
182
- for region in regions:
183
- for piece, planes in split_region_if_not_planar(
184
- region, geometry, min_area, geometry_maps=geometry_maps,
185
- ):
186
- area = int(piece.sum())
187
- if area >= min_area:
188
- components.append((area, piece.astype(np.uint8), planes))
189
-
190
- # --- Repair pass -------------------------------------------------------
191
- # Splitting above deliberately runs on the protected-subtracted mask, so one
192
- # warped transform is never stretched across a corner or an opening. Now
193
- # that the split is settled, each component reclaims the holes that plane
194
- # assignment and protection punched through it.
195
- #
196
- # Largest first, subtracting whatever earlier components already claimed, so
197
- # the refined masks stay disjoint — otherwise the edge-repair dilation would
198
- # let two walls overlap at a corner and that seam would be tiled twice.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  components.sort(key=lambda item: item[0], reverse=True)
200
- claimed = np.zeros(wall_raw.shape[:2], dtype=bool)
201
- refined_components = []
202
- for _, component_mask, planes in components:
203
- refined, _metadata = refine_wall_component_mask(
204
- component_mask, wall_raw, reclaimable_mask, barrier_mask, image_rgb
205
- )
206
- refined[claimed] = 0
207
- area = int(refined.sum())
208
- if area < min_area:
209
- continue
210
- claimed |= refined.astype(bool)
211
- refined_components.append((area, refined, planes))
212
-
213
- if refined_components:
214
- refined_components.sort(key=lambda item: item[0], reverse=True)
215
- print(
216
- f"[WALL_COMPONENTS] emitting {len(refined_components)} wall segment(s): "
217
- f"{[area for area, _ , _ in refined_components]} px",
218
- flush=True,
219
- )
220
- return refined_components, protected
221
  return components, protected
 
13
  assign_points_to_surface_planes,
14
  fit_multi_surface_planes,
15
  geometry_point_maps,
 
 
16
  )
17
  from services.geometry.normals import normalize_vectors
 
 
 
18
  from state import OCCLUDER_CLASSES, class_ids
19
  from utils import seg_class_mask
20
 
21
 
22
+ def wall_surface_components(seg_map: np.ndarray, min_area: int, geometry: dict | None = None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """Create clean, independently renderable wall regions.
24
 
 
 
 
 
25
  Semantic wall predictions often bridge across corners and openings. Removing
26
  protected classes before connected-component analysis prevents one warped
27
  transform from being applied to several physically different walls.
28
  """
29
+ wall = seg_class_mask(seg_map, class_ids({"wall"}))
 
 
 
 
 
30
  protected = seg_class_mask(seg_map, class_ids(OCCLUDER_CLASSES | {
31
  "door", "window", "column", "base", "railing", "ceiling",
32
  "building", "painting", "mirror", "curtain",
33
  }))
 
 
 
34
  radius = max(1, int(round(min(seg_map.shape[:2]) * 0.006)))
35
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
36
  protected = cv2.dilate(protected, kernel, iterations=1)
 
39
  wall = cv2.morphologyEx(wall, cv2.MORPH_OPEN, kernel)
40
  wall[protected > 0] = 0
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  components = []
43
+ if geometry is not None:
44
+ maps = geometry_point_maps(wall, geometry)
45
+ if maps is not None:
46
+ valid = maps["validMask"] & (wall > 0)
47
+ ys, xs = np.where(valid)
48
+ if len(xs) >= SURFACE_MIN_PLANE_PIXELS:
49
+ points = maps["points"][ys, xs].astype(np.float32)
50
+ normals = maps["normals"][ys, xs].astype(np.float32)
51
+ finite = np.isfinite(points).all(axis=1) & np.isfinite(normals).all(axis=1)
52
+ points, normals, ys, xs = points[finite], normals[finite], ys[finite], xs[finite]
53
+ if len(points) >= SURFACE_MIN_PLANE_PIXELS:
54
+ normals_reliable = np.linalg.norm(normals, axis=1) > 1e-4
55
+ if normals_reliable.sum() >= SURFACE_MIN_PLANE_PIXELS:
56
+ points = points[normals_reliable]
57
+ normals = normalize_vectors(normals[normals_reliable])
58
+ ys, xs = ys[normals_reliable], xs[normals_reliable]
59
+ planes = fit_multi_surface_planes(points, normals, True)
60
+ wall_planes = [
61
+ plane for plane in planes
62
+ if abs(float(plane["normal"][1])) <= 0.45
63
+ ]
64
+ if wall_planes:
65
+ assignment = assign_points_to_surface_planes(
66
+ points, normals, wall_planes, True
67
+ )
68
+ for plane_index in range(len(wall_planes)):
69
+ selected = assignment == plane_index
70
+ if int(selected.sum()) < min_area:
71
+ continue
72
+ plane_mask = np.zeros_like(wall)
73
+ plane_mask[ys[selected], xs[selected]] = 1
74
+ count, labels, stats, _ = cv2.connectedComponentsWithStats(
75
+ plane_mask, connectivity=8
76
+ )
77
+ for component_id in range(1, count):
78
+ area = int(stats[component_id, cv2.CC_STAT_AREA])
79
+ if area >= min_area:
80
+ components.append((area, (labels == component_id).astype(np.uint8)))
81
+
82
+ # Geometry can be unavailable or too noisy. In that case retain the safe
83
+ # semantic connected-component fallback instead of emitting no walls.
84
+ if not components:
85
+ count, labels, stats, _ = cv2.connectedComponentsWithStats(wall, connectivity=8)
86
+ for component_id in range(1, count):
87
+ area = int(stats[component_id, cv2.CC_STAT_AREA])
88
+ if area < min_area:
89
+ continue
90
+ components.append((area, (labels == component_id).astype(np.uint8)))
91
  components.sort(key=lambda item: item[0], reverse=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  return components, protected
services/wall/plane.py CHANGED
@@ -16,29 +16,14 @@ from services.geometry.plane_fitting import (
16
  fit_metric_floor_transform,
17
  )
18
 
19
- # Assumed floor-to-ceiling height, in metres, for a wall with no depth to
20
- # measure. Only the wall's *aspect* can be recovered from a single view without
21
- # metric geometry, so this sets the absolute scale; the metric fit overrides
22
- # both extents whenever it succeeds.
23
- WALL_HEIGHT_PRIOR_METERS = 2.4
24
 
25
-
26
- def estimate_wall_plane(
27
- mask: np.ndarray,
28
- geometry: dict | None = None,
29
- vertical_ref: np.ndarray | None = None,
30
- ):
31
  """Return a stable image-space homography for a semantic wall mask.
32
 
33
  Walls do not currently have metric depth fitting, so use the visible wall
34
  contour as the source quad and its bounding rectangle as the planar target.
35
  This preserves perspective convergence while keeping physical tile sizes
36
  deterministic until wall-specific depth calibration is available.
37
-
38
- `vertical_ref` is which direction gravity-up points, in the same frame as
39
- the geometry's points. Geometry providers work in camera coordinates, so
40
- without it the metric fit assumes camera +Y is up and rotates the wall's
41
- tile grid by the camera's roll. Callers should pass the floor normal.
42
  """
43
  ys, xs = np.where(mask > 0)
44
  if len(xs) < 1000:
@@ -78,23 +63,6 @@ def estimate_wall_plane(
78
  if x2 - x1 < 20 or y2 - y1 < 20:
79
  return None, None
80
 
81
- # Measure the wall along its own edges, averaging opposite pairs.
82
- #
83
- # The axis-aligned bounding box was standing in for these, which overstates
84
- # a tilted wall: a slanted mask falls through to `minAreaRect`, whose
85
- # corners can sit well outside the image, and the box around that rotated
86
- # rect is far wider than the wall. Edge lengths are unaffected by the tilt
87
- # and by corners leaving the frame, and for an axis-aligned quad they are
88
- # exactly the box dimensions, so only genuinely tilted walls move.
89
- quad_width = 0.5 * (
90
- float(np.linalg.norm(ordered[1] - ordered[0]))
91
- + float(np.linalg.norm(ordered[2] - ordered[3]))
92
- )
93
- quad_height = 0.5 * (
94
- float(np.linalg.norm(ordered[3] - ordered[0]))
95
- + float(np.linalg.norm(ordered[2] - ordered[1]))
96
- )
97
-
98
  destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
99
  homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
100
  metric_geometry = None
@@ -109,7 +77,6 @@ def estimate_wall_plane(
109
  geometry.get("intrinsics"),
110
  geometry.get("provider", GeometryProvider.METRIC_DEPTH),
111
  surface_kind="wall",
112
- vertical_ref=vertical_ref,
113
  )
114
  if metric_geometry is None:
115
  metric_geometry = estimate_metric_floor_transform(
@@ -118,7 +85,6 @@ def estimate_wall_plane(
118
  geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
119
  geometry.get("intrinsics"),
120
  surface_kind="wall",
121
- vertical_ref=vertical_ref,
122
  )
123
 
124
  plane = {
@@ -132,10 +98,8 @@ def estimate_wall_plane(
132
  "floorTransform": None,
133
  "surfaceTransform": None,
134
  "surfaceType": SurfaceType.WALL,
135
- "surfaceWidthMeters": max(
136
- 0.5, WALL_HEIGHT_PRIOR_METERS * quad_width / max(quad_height, 1.0)
137
- ),
138
- "surfaceHeightMeters": WALL_HEIGHT_PRIOR_METERS,
139
  "metersPerUnit": None,
140
  "cameraIntrinsics": None,
141
  "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
 
16
  fit_metric_floor_transform,
17
  )
18
 
 
 
 
 
 
19
 
20
+ def estimate_wall_plane(mask: np.ndarray, geometry: dict | None = None):
 
 
 
 
 
21
  """Return a stable image-space homography for a semantic wall mask.
22
 
23
  Walls do not currently have metric depth fitting, so use the visible wall
24
  contour as the source quad and its bounding rectangle as the planar target.
25
  This preserves perspective convergence while keeping physical tile sizes
26
  deterministic until wall-specific depth calibration is available.
 
 
 
 
 
27
  """
28
  ys, xs = np.where(mask > 0)
29
  if len(xs) < 1000:
 
63
  if x2 - x1 < 20 or y2 - y1 < 20:
64
  return None, None
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  destination = np.float32([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])
67
  homography = cv2.getPerspectiveTransform(ordered, destination).flatten().tolist()
68
  metric_geometry = None
 
77
  geometry.get("intrinsics"),
78
  geometry.get("provider", GeometryProvider.METRIC_DEPTH),
79
  surface_kind="wall",
 
80
  )
81
  if metric_geometry is None:
82
  metric_geometry = estimate_metric_floor_transform(
 
85
  geometry.get("provider", GeometryProvider.DEPTH_ANYTHING),
86
  geometry.get("intrinsics"),
87
  surface_kind="wall",
 
88
  )
89
 
90
  plane = {
 
98
  "floorTransform": None,
99
  "surfaceTransform": None,
100
  "surfaceType": SurfaceType.WALL,
101
+ "surfaceWidthMeters": max(0.5, 2.4 * (x2 - x1) / max(y2 - y1, 1.0)),
102
+ "surfaceHeightMeters": 2.4,
 
 
103
  "metersPerUnit": None,
104
  "cameraIntrinsics": None,
105
  "camera": {"focalLength": float(max(h, w) * 0.95), "horizonY": y1, "confidence": 0.45},
visualizer.gpu.toml CHANGED
@@ -17,10 +17,10 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
- enable_fast_shadow_transfer = false
24
  fast_shadow_max_dimension = 640
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = true
@@ -34,7 +34,7 @@ data_dir = "data"
34
 
35
  [surface_mapping]
36
  ransac_distance_threshold = 0.04
37
- max_planes = 5
38
  normal_angle_threshold_degrees = 35
39
  normal_smoothing_kernel = 5
40
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
+ enable_fast_shadow_transfer = true
24
  fast_shadow_max_dimension = 640
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = true
 
34
 
35
  [surface_mapping]
36
  ransac_distance_threshold = 0.04
37
+ max_planes = 1
38
  normal_angle_threshold_degrees = 35
39
  normal_smoothing_kernel = 5
40
  min_plane_pixels = 1500
visualizer.hf.toml CHANGED
@@ -17,10 +17,10 @@ enable_depth_estimation = true
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
- enable_wall_segments = true
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
- enable_fast_shadow_transfer = false
24
  fast_shadow_max_dimension = 640
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = true
@@ -31,7 +31,7 @@ data_dir = "data"
31
 
32
  [surface_mapping]
33
  ransac_distance_threshold = 0.04
34
- max_planes = 5
35
  normal_angle_threshold_degrees = 35
36
  normal_smoothing_kernel = 5
37
  min_plane_pixels = 1500
 
17
  enable_moge_geometry = true
18
  enable_plane_fit = true
19
  enable_multi_plane_surfaces = true
20
+ enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
+ enable_fast_shadow_transfer = true
24
  fast_shadow_max_dimension = 640
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = true
 
31
 
32
  [surface_mapping]
33
  ransac_distance_threshold = 0.04
34
+ max_planes = 1
35
  normal_angle_threshold_degrees = 35
36
  normal_smoothing_kernel = 5
37
  min_plane_pixels = 1500
visualizer.local.toml CHANGED
@@ -13,10 +13,10 @@ sam2_checkpoint = ""
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
- enable_wall_segments = true
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
- enable_fast_shadow_transfer = false
20
  fast_shadow_max_dimension = 640
21
  enable_sam_refinement = false
22
  warm_start_models = true
 
13
  enable_depth_estimation = false
14
  enable_plane_fit = true
15
  enable_multi_plane_surfaces = true
16
+ enable_wall_segments = false
17
  enable_intrinsic_shading = false
18
  enable_shading_transfer = false
19
+ enable_fast_shadow_transfer = true
20
  fast_shadow_max_dimension = 640
21
  enable_sam_refinement = false
22
  warm_start_models = true