github-actions[bot] commited on
Commit
94b277a
·
1 Parent(s): 91331b9

Automated Deploy: 4ce7ead7f9ba449c89aa3dad14bf1ad0877874f5

Browse files
services/direction/analysis.py CHANGED
@@ -13,10 +13,11 @@ def floor_direction_geometry_inputs(
13
  surface_mapping: dict | None,
14
  *,
15
  use_surface_uv: bool,
 
16
  ) -> dict:
17
  direction_maps = surface_mapping
18
  if direction_maps is None:
19
- raw_maps = geometry_point_maps(surface_mask, geometry)
20
  if raw_maps is not None:
21
  direction_maps = {
22
  "normalMap": raw_maps["normals"],
 
13
  surface_mapping: dict | None,
14
  *,
15
  use_surface_uv: bool,
16
+ geometry_maps: dict | None = None,
17
  ) -> dict:
18
  direction_maps = surface_mapping
19
  if direction_maps is None:
20
+ raw_maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry)
21
  if raw_maps is not None:
22
  direction_maps = {
23
  "normalMap": raw_maps["normals"],
services/floor/geometry_filter.py CHANGED
@@ -25,6 +25,8 @@ def filter_surface_by_floor_geometry(
25
  surface: np.ndarray,
26
  geometry: dict | None,
27
  plane: dict | None,
 
 
28
  ) -> tuple[np.ndarray, dict]:
29
  before = int(surface.sum())
30
  metadata = {
@@ -43,7 +45,7 @@ def filter_surface_by_floor_geometry(
43
  if not plane.get("planeNormal") or not plane.get("planeOrigin"):
44
  return surface, metadata
45
 
46
- maps = geometry_point_maps(surface, geometry)
47
  if maps is None:
48
  metadata["geometrySurfaceFilterReason"] = "point-map-unavailable"
49
  return surface, metadata
@@ -68,13 +70,17 @@ def filter_surface_by_floor_geometry(
68
  keep = valid & (distances <= SURFACE_PLANE_DISTANCE_METERS)
69
 
70
  if normals is not None and normals.shape[:2] == surface.shape:
71
- normal_lengths = np.linalg.norm(normals, axis=2)
72
- normal_valid = valid & np.isfinite(normals).all(axis=2) & (normal_lengths > 1e-4)
 
 
 
 
73
  if int(normal_valid.sum()) >= SURFACE_MIN_PLANE_PIXELS:
74
- normalized_normals = np.zeros_like(normals, dtype=np.float32)
75
- normalized_normals[normal_valid] = normals[normal_valid] / normal_lengths[normal_valid, None]
76
- alignment = np.zeros(surface.shape, dtype=np.float32)
77
- alignment[normal_valid] = np.abs(normalized_normals[normal_valid] @ plane_normal)
78
  keep &= (~normal_valid) | (alignment >= SURFACE_PLANE_NORMAL_MIN_COS)
79
  metadata["geometrySurfaceNormalPixels"] = int(normal_valid.sum())
80
 
 
25
  surface: np.ndarray,
26
  geometry: dict | None,
27
  plane: dict | None,
28
+ *,
29
+ geometry_maps: dict | None = None,
30
  ) -> tuple[np.ndarray, dict]:
31
  before = int(surface.sum())
32
  metadata = {
 
45
  if not plane.get("planeNormal") or not plane.get("planeOrigin"):
46
  return surface, metadata
47
 
48
+ maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface, geometry)
49
  if maps is None:
50
  metadata["geometrySurfaceFilterReason"] = "point-map-unavailable"
51
  return surface, metadata
 
70
  keep = valid & (distances <= SURFACE_PLANE_DISTANCE_METERS)
71
 
72
  if normals is not None and normals.shape[:2] == surface.shape:
73
+ prepared_normal_valid = maps.get("normalValidMask")
74
+ normal_valid = valid & (
75
+ prepared_normal_valid
76
+ if prepared_normal_valid is not None and prepared_normal_valid.shape == surface.shape
77
+ else np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4)
78
+ )
79
  if int(normal_valid.sum()) >= SURFACE_MIN_PLANE_PIXELS:
80
+ # geometry_point_maps returns normalized normals. Reuse them
81
+ # directly instead of allocating and normalizing another full-size
82
+ # HxWx3 array for every surface-filter pass.
83
+ alignment = np.abs(np.einsum("ijk,k->ij", normals, plane_normal, optimize=True))
84
  keep &= (~normal_valid) | (alignment >= SURFACE_PLANE_NORMAL_MIN_COS)
85
  metadata["geometrySurfaceNormalPixels"] = int(normal_valid.sum())
86
 
services/floor/mask.py CHANGED
@@ -7,6 +7,8 @@ wall_subtract - remove wall/reject pixels from a floor mask
7
  build_floor_surface_mask - composite floor surface from segmentation, depth, and geometry
8
  """
9
 
 
 
10
  import cv2
11
  import numpy as np
12
 
@@ -86,7 +88,11 @@ def build_floor_surface_mask(
86
  depth: np.ndarray | None,
87
  geometry: dict | None,
88
  plane: dict | None,
 
 
89
  ):
 
 
90
  h, w = floor_mask.shape[:2]
91
  kern_size = max(5, min(h, w) // 160) | 1
92
  kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
@@ -137,19 +143,37 @@ def build_floor_surface_mask(
137
  surface[occluder_mask > 0] = 0
138
  surface[reject_mask > 0] = 0
139
  surface[soft_covering_mask > 0] = 0
 
140
 
141
- surface, geometry_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
 
 
 
 
 
 
 
142
  surface[occluder_mask > 0] = 0
143
  surface[reject_mask > 0] = 0
144
  surface[soft_covering_mask > 0] = 0
145
 
 
146
  surface = clean_floor_mask(surface)
147
  surface[occluder_mask > 0] = 0
148
  surface[reject_mask > 0] = 0
149
  surface[soft_covering_mask > 0] = 0
150
 
151
  surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask)
152
- surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
 
 
 
 
 
 
 
 
 
153
  surface[occluder_mask > 0] = 0
154
  surface[reject_mask > 0] = 0
155
  surface[soft_covering_mask > 0] = 0
@@ -158,22 +182,56 @@ def build_floor_surface_mask(
158
  for k, value in post_edge_filter_metadata.items()
159
  }
160
 
 
 
161
  surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings(
162
  surface,
163
  soft_covering_mask,
164
  hard_protected_mask,
165
  )
166
- surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  surface[occluder_mask > 0] = 0
168
  surface[reject_mask > 0] = 0
169
  post_soft_covering_filter_metadata = {
170
  f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value
171
  for k, value in post_soft_covering_filter_metadata.items()
172
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  return surface, {
174
  **geometry_filter_metadata,
175
  **edge_metadata,
176
  **post_edge_filter_metadata,
177
  **soft_covering_metadata,
178
  **post_soft_covering_filter_metadata,
 
179
  }
 
7
  build_floor_surface_mask - composite floor surface from segmentation, depth, and geometry
8
  """
9
 
10
+ import time
11
+
12
  import cv2
13
  import numpy as np
14
 
 
88
  depth: np.ndarray | None,
89
  geometry: dict | None,
90
  plane: dict | None,
91
+ *,
92
+ geometry_maps: dict | None = None,
93
  ):
94
+ total_started = time.perf_counter()
95
+ phase_started = total_started
96
  h, w = floor_mask.shape[:2]
97
  kern_size = max(5, min(h, w) // 160) | 1
98
  kern = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kern_size, kern_size))
 
143
  surface[occluder_mask > 0] = 0
144
  surface[reject_mask > 0] = 0
145
  surface[soft_covering_mask > 0] = 0
146
+ preparation_ms = (time.perf_counter() - phase_started) * 1000
147
 
148
+ phase_started = time.perf_counter()
149
+ surface, geometry_filter_metadata = filter_surface_by_floor_geometry(
150
+ surface,
151
+ geometry,
152
+ plane,
153
+ geometry_maps=geometry_maps,
154
+ )
155
+ initial_filter_ms = (time.perf_counter() - phase_started) * 1000
156
  surface[occluder_mask > 0] = 0
157
  surface[reject_mask > 0] = 0
158
  surface[soft_covering_mask > 0] = 0
159
 
160
+ phase_started = time.perf_counter()
161
  surface = clean_floor_mask(surface)
162
  surface[occluder_mask > 0] = 0
163
  surface[reject_mask > 0] = 0
164
  surface[soft_covering_mask > 0] = 0
165
 
166
  surface, edge_metadata = improve_surface_edge_coverage(surface, normal_edge_protected_mask)
167
+ cleanup_and_edge_ms = (time.perf_counter() - phase_started) * 1000
168
+
169
+ phase_started = time.perf_counter()
170
+ surface, post_edge_filter_metadata = filter_surface_by_floor_geometry(
171
+ surface,
172
+ geometry,
173
+ plane,
174
+ geometry_maps=geometry_maps,
175
+ )
176
+ post_edge_filter_ms = (time.perf_counter() - phase_started) * 1000
177
  surface[occluder_mask > 0] = 0
178
  surface[reject_mask > 0] = 0
179
  surface[soft_covering_mask > 0] = 0
 
182
  for k, value in post_edge_filter_metadata.items()
183
  }
184
 
185
+ phase_started = time.perf_counter()
186
+ surface_before_soft_covering = surface
187
  surface, soft_covering_metadata = expand_surface_over_soft_floor_coverings(
188
  surface,
189
  soft_covering_mask,
190
  hard_protected_mask,
191
  )
192
+ soft_covering_ms = (time.perf_counter() - phase_started) * 1000
193
+
194
+ phase_started = time.perf_counter()
195
+ if surface is surface_before_soft_covering or not soft_covering_metadata["softFloorCoveringExpansionApplied"]:
196
+ post_soft_covering_filter_metadata = {
197
+ "geometrySurfaceFilterApplied": False,
198
+ "geometrySurfaceFilterReason": "soft-floor-surface-unchanged",
199
+ "geometrySurfacePixelsBefore": int(surface.sum()),
200
+ "geometrySurfacePixelsAfter": int(surface.sum()),
201
+ }
202
+ else:
203
+ surface, post_soft_covering_filter_metadata = filter_surface_by_floor_geometry(
204
+ surface,
205
+ geometry,
206
+ plane,
207
+ geometry_maps=geometry_maps,
208
+ )
209
+ post_soft_filter_ms = (time.perf_counter() - phase_started) * 1000
210
  surface[occluder_mask > 0] = 0
211
  surface[reject_mask > 0] = 0
212
  post_soft_covering_filter_metadata = {
213
  f"postSoftFloorCovering{k[0].upper()}{k[1:]}": value
214
  for k, value in post_soft_covering_filter_metadata.items()
215
  }
216
+ timing_ms = {
217
+ "preparation": round(preparation_ms, 2),
218
+ "initialGeometryFilter": round(initial_filter_ms, 2),
219
+ "cleanupAndEdgeRepair": round(cleanup_and_edge_ms, 2),
220
+ "postEdgeGeometryFilter": round(post_edge_filter_ms, 2),
221
+ "softFloorExpansion": round(soft_covering_ms, 2),
222
+ "postSoftFloorGeometryFilter": round(post_soft_filter_ms, 2),
223
+ "total": round((time.perf_counter() - total_started) * 1000, 2),
224
+ }
225
+ print(
226
+ "[SURFACE_MASKING_TIMING] "
227
+ + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()),
228
+ flush=True,
229
+ )
230
  return surface, {
231
  **geometry_filter_metadata,
232
  **edge_metadata,
233
  **post_edge_filter_metadata,
234
  **soft_covering_metadata,
235
  **post_soft_covering_filter_metadata,
236
+ "surfaceMaskingTimingMs": timing_ms,
237
  }
services/geometry/multi_plane.py CHANGED
@@ -45,12 +45,12 @@ def geometry_point_maps(mask: np.ndarray, geometry: dict | None):
45
  valid_mask = np.isfinite(depth_for_points) & (depth_for_points > 0.05)
46
  point_source = f"{provider or 'depth'}-backprojection"
47
  else:
48
- points = points.astype(np.float32)
49
  pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h)
50
  if valid_mask is None:
51
  valid_mask = np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05)
52
 
53
- valid_mask = valid_mask.astype(bool) & np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05)
54
  print(
55
  "[FLOOR_3D_POINTS] point map ready for floor mapping "
56
  f"source={point_source} provider={geometry.get('provider')} shape={points.shape} "
@@ -61,11 +61,13 @@ def geometry_point_maps(mask: np.ndarray, geometry: dict | None):
61
  if normals is None or normals.shape[:2] != mask.shape:
62
  normals = compute_normals_from_points(points, valid_mask, SURFACE_NORMAL_SMOOTHING_KERNEL)
63
  else:
64
- normals = smooth_normal_map(normals.astype(np.float32), SURFACE_NORMAL_SMOOTHING_KERNEL)
 
65
 
66
  return {
67
- "points": points.astype(np.float32),
68
- "normals": normals.astype(np.float32),
 
69
  "validMask": valid_mask,
70
  "intrinsics": pixel_intrinsics.astype(np.float32),
71
  "depthScale": depth_scale,
 
45
  valid_mask = np.isfinite(depth_for_points) & (depth_for_points > 0.05)
46
  point_source = f"{provider or 'depth'}-backprojection"
47
  else:
48
+ points = points.astype(np.float32, copy=False)
49
  pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h)
50
  if valid_mask is None:
51
  valid_mask = np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05)
52
 
53
+ valid_mask = valid_mask.astype(bool, copy=False) & np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05)
54
  print(
55
  "[FLOOR_3D_POINTS] point map ready for floor mapping "
56
  f"source={point_source} provider={geometry.get('provider')} shape={points.shape} "
 
61
  if normals is None or normals.shape[:2] != mask.shape:
62
  normals = compute_normals_from_points(points, valid_mask, SURFACE_NORMAL_SMOOTHING_KERNEL)
63
  else:
64
+ normals = smooth_normal_map(normals.astype(np.float32, copy=False), SURFACE_NORMAL_SMOOTHING_KERNEL)
65
+ normal_valid_mask = np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4)
66
 
67
  return {
68
+ "points": points.astype(np.float32, copy=False),
69
+ "normals": normals.astype(np.float32, copy=False),
70
+ "normalValidMask": normal_valid_mask,
71
  "validMask": valid_mask,
72
  "intrinsics": pixel_intrinsics.astype(np.float32),
73
  "depthScale": depth_scale,
services/geometry/ransac.py CHANGED
@@ -5,6 +5,64 @@ import numpy as np
5
  from config.surface import SURFACE_MIN_PLANE_PIXELS
6
  from services.geometry.plane_fitting import refine_plane
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  def ransac_plane_fit(points: np.ndarray):
10
  if len(points) < 1000:
@@ -53,31 +111,25 @@ def ransac_surface_plane(
53
  return None
54
 
55
  rng = np.random.default_rng(41)
56
- best_normal = None
57
- best_origin = None
58
- best_count = 0
59
  candidate_points = points[candidate_indices]
60
  candidate_normals = normals[candidate_indices]
61
  relaxed_cos = max(0.0, normal_cos - 0.15)
62
-
63
- for _ in range(220):
64
- local = rng.choice(len(candidate_indices), size=3, replace=False)
65
- p0, p1, p2 = candidate_points[local]
66
- normal = np.cross(p1 - p0, p2 - p0).astype(np.float32)
67
- length = float(np.linalg.norm(normal))
68
- if length < 1e-6:
69
- continue
70
- normal /= length
71
- align = np.abs(candidate_normals @ normal)
72
- distances = np.abs((candidate_points - p0) @ normal)
73
- count = int(((distances <= distance_threshold) & (align >= relaxed_cos)).sum())
74
- if count > best_count:
75
- best_count = count
76
- best_origin = p0
77
- best_normal = normal
78
-
79
- if best_normal is None:
80
  return None
 
81
 
82
  distances = np.abs((points - best_origin) @ best_normal)
83
  align = np.abs(normals @ best_normal)
@@ -111,28 +163,21 @@ def ransac_surface_plane_by_distance(
111
  return None
112
 
113
  rng = np.random.default_rng(53)
114
- best_normal = None
115
- best_origin = None
116
- best_count = 0
117
  candidate_points = points[candidate_indices]
118
-
119
- for _ in range(260):
120
- local = rng.choice(len(candidate_indices), size=3, replace=False)
121
- p0, p1, p2 = candidate_points[local]
122
- normal = np.cross(p1 - p0, p2 - p0).astype(np.float32)
123
- length = float(np.linalg.norm(normal))
124
- if length < 1e-6:
125
- continue
126
- normal /= length
127
- distances = np.abs((candidate_points - p0) @ normal)
128
- count = int((distances <= distance_threshold).sum())
129
- if count > best_count:
130
- best_count = count
131
- best_origin = p0
132
- best_normal = normal
133
-
134
- if best_normal is None:
135
  return None
 
136
 
137
  distances = np.abs((points - best_origin) @ best_normal)
138
  inliers = remaining & (distances <= distance_threshold)
 
5
  from config.surface import SURFACE_MIN_PLANE_PIXELS
6
  from services.geometry.plane_fitting import refine_plane
7
 
8
+ _HYPOTHESIS_BATCH_SIZE = 32
9
+
10
+
11
+ def _candidate_hypotheses(
12
+ candidate_points: np.ndarray,
13
+ *,
14
+ iterations: int,
15
+ rng: np.random.Generator,
16
+ ) -> tuple[np.ndarray, np.ndarray]:
17
+ """Generate the same deterministic RANSAC hypotheses without scoring each one separately."""
18
+ origins = []
19
+ normals = []
20
+ for _ in range(iterations):
21
+ local = rng.choice(len(candidate_points), size=3, replace=False)
22
+ p0, p1, p2 = candidate_points[local]
23
+ normal = np.cross(p1 - p0, p2 - p0).astype(np.float32)
24
+ length = float(np.linalg.norm(normal))
25
+ if length < 1e-6:
26
+ continue
27
+ origins.append(p0)
28
+ normals.append(normal / length)
29
+ if not origins:
30
+ return np.empty((0, 3), dtype=np.float32), np.empty((0, 3), dtype=np.float32)
31
+ return np.asarray(origins, dtype=np.float32), np.asarray(normals, dtype=np.float32)
32
+
33
+
34
+ def _best_surface_hypothesis(
35
+ candidate_points: np.ndarray,
36
+ origins: np.ndarray,
37
+ normals: np.ndarray,
38
+ distance_threshold: float,
39
+ *,
40
+ candidate_normals: np.ndarray | None = None,
41
+ normal_cos: float | None = None,
42
+ ) -> tuple[np.ndarray, np.ndarray] | None:
43
+ """Score RANSAC hypotheses in bounded batches to avoid hundreds of tiny NumPy calls."""
44
+ best_count = 0
45
+ best_index = -1
46
+ for start in range(0, len(origins), _HYPOTHESIS_BATCH_SIZE):
47
+ stop = min(start + _HYPOTHESIS_BATCH_SIZE, len(origins))
48
+ batch_normals = normals[start:stop]
49
+ batch_origins = origins[start:stop]
50
+ offsets = np.sum(batch_origins * batch_normals, axis=1)
51
+ distances = np.abs(candidate_points @ batch_normals.T - offsets[None, :])
52
+ accepted = distances <= distance_threshold
53
+ if candidate_normals is not None and normal_cos is not None:
54
+ alignments = np.abs(candidate_normals @ batch_normals.T)
55
+ accepted &= alignments >= normal_cos
56
+ counts = accepted.sum(axis=0)
57
+ local_index = int(np.argmax(counts))
58
+ local_count = int(counts[local_index])
59
+ if local_count > best_count:
60
+ best_count = local_count
61
+ best_index = start + local_index
62
+ if best_index < 0:
63
+ return None
64
+ return origins[best_index], normals[best_index]
65
+
66
 
67
  def ransac_plane_fit(points: np.ndarray):
68
  if len(points) < 1000:
 
111
  return None
112
 
113
  rng = np.random.default_rng(41)
 
 
 
114
  candidate_points = points[candidate_indices]
115
  candidate_normals = normals[candidate_indices]
116
  relaxed_cos = max(0.0, normal_cos - 0.15)
117
+ origins, hypothesis_normals = _candidate_hypotheses(
118
+ candidate_points,
119
+ iterations=220,
120
+ rng=rng,
121
+ )
122
+ best = _best_surface_hypothesis(
123
+ candidate_points,
124
+ origins,
125
+ hypothesis_normals,
126
+ distance_threshold,
127
+ candidate_normals=candidate_normals,
128
+ normal_cos=relaxed_cos,
129
+ )
130
+ if best is None:
 
 
 
 
131
  return None
132
+ best_origin, best_normal = best
133
 
134
  distances = np.abs((points - best_origin) @ best_normal)
135
  align = np.abs(normals @ best_normal)
 
163
  return None
164
 
165
  rng = np.random.default_rng(53)
 
 
 
166
  candidate_points = points[candidate_indices]
167
+ origins, hypothesis_normals = _candidate_hypotheses(
168
+ candidate_points,
169
+ iterations=260,
170
+ rng=rng,
171
+ )
172
+ best = _best_surface_hypothesis(
173
+ candidate_points,
174
+ origins,
175
+ hypothesis_normals,
176
+ distance_threshold,
177
+ )
178
+ if best is None:
 
 
 
 
 
179
  return None
180
+ best_origin, best_normal = best
181
 
182
  distances = np.abs((points - best_origin) @ best_normal)
183
  inliers = remaining & (distances <= distance_threshold)
services/geometry/uv_mapping.py CHANGED
@@ -1,5 +1,7 @@
1
  from __future__ import annotations
2
 
 
 
3
  import numpy as np
4
 
5
  from enums import TextureMappingMode, TextureMappingReason, PlaneFitMode
@@ -124,8 +126,13 @@ def build_surface_uv_mapping(
124
  surface_mask: np.ndarray,
125
  surface_indices: np.ndarray,
126
  geometry: dict | None,
 
 
127
  ):
128
- maps = geometry_point_maps(surface_mask, geometry)
 
 
 
129
  if maps is None:
130
  print(
131
  "[SURFACE_MAPPING] skipped: no point maps "
@@ -138,19 +145,17 @@ def build_surface_uv_mapping(
138
  points_map = maps["points"]
139
  normals_map = maps["normals"]
140
  valid_mask = maps["validMask"] & (surface_mask > 0)
141
- ys, xs = np.where(valid_mask)
142
- if len(xs) < SURFACE_MIN_PLANE_PIXELS:
143
  print(
144
  "[SURFACE_MAPPING] skipped: too few valid surface pixels "
145
- f"valid={len(xs)} min={SURFACE_MIN_PLANE_PIXELS}",
146
  flush=True,
147
  )
148
  return None
149
 
150
- valid_flat = (ys * surface_mask.shape[1] + xs).astype(np.uint32)
151
- points = points_map[ys, xs].astype(np.float32)
152
- normals_raw = normals_map[ys, xs].astype(np.float32)
153
- normal_lengths = np.linalg.norm(normals_raw, axis=1)
154
  good_points = np.isfinite(points).all(axis=1)
155
  if int(good_points.sum()) < SURFACE_MIN_PLANE_PIXELS:
156
  print(
@@ -162,13 +167,14 @@ def build_surface_uv_mapping(
162
 
163
  valid_flat = valid_flat[good_points]
164
  points = points[good_points]
165
- normals_raw = normals_raw[good_points]
166
- normal_lengths = normal_lengths[good_points]
167
- normal_good = np.isfinite(normals_raw).all(axis=1) & (normal_lengths > 1e-4)
168
- normals = np.zeros_like(points, dtype=np.float32)
169
- if normal_good.any():
170
- normals[normal_good] = normals_raw[normal_good] / normal_lengths[normal_good, None]
171
  normals_reliable = int(normal_good.sum()) >= SURFACE_MIN_PLANE_PIXELS
 
172
 
173
  print(
174
  "[SURFACE_MAPPING] candidates "
@@ -178,7 +184,9 @@ def build_surface_uv_mapping(
178
  flush=True,
179
  )
180
 
 
181
  planes = fit_multi_surface_planes(points, normals, normals_reliable)
 
182
  if not planes:
183
  print(
184
  "[SURFACE_MAPPING] skipped: no dominant planes fitted "
@@ -188,7 +196,11 @@ def build_surface_uv_mapping(
188
  )
189
  return None
190
 
 
191
  assignment = assign_points_to_surface_planes(points, normals, planes, normals_reliable)
 
 
 
192
  uv_by_mask = np.full((len(surface_indices), 2), np.nan, dtype=np.float32)
193
  plane_ids = np.full(len(surface_indices), 255, dtype=np.uint8)
194
  ordinal = np.full(surface_mask.size, -1, dtype=np.int32)
@@ -250,11 +262,24 @@ def build_surface_uv_mapping(
250
  "uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)),
251
  "uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)),
252
  })
 
253
 
 
254
  finite_uv = np.isfinite(uv_by_mask).all(axis=1)
255
  uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids)
 
256
  uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit)
257
  uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance)
 
 
 
 
 
 
 
 
 
 
258
  print(
259
  "[SURFACE_MAPPING] success "
260
  f"planes={len(serializable_planes)} assignedPixels={int(finite_uv.sum())}/{len(surface_indices)} "
@@ -262,6 +287,11 @@ def build_surface_uv_mapping(
262
  f"mode={uv_quality['textureMappingMode']} reason={uv_quality['textureMappingReason']}",
263
  flush=True,
264
  )
 
 
 
 
 
265
 
266
  return {
267
  "uv": uv_by_mask,
 
1
  from __future__ import annotations
2
 
3
+ import time
4
+
5
  import numpy as np
6
 
7
  from enums import TextureMappingMode, TextureMappingReason, PlaneFitMode
 
126
  surface_mask: np.ndarray,
127
  surface_indices: np.ndarray,
128
  geometry: dict | None,
129
+ *,
130
+ geometry_maps: dict | None = None,
131
  ):
132
+ total_started = time.perf_counter()
133
+ phase_started = total_started
134
+ maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry)
135
+ geometry_maps_ms = (time.perf_counter() - phase_started) * 1000
136
  if maps is None:
137
  print(
138
  "[SURFACE_MAPPING] skipped: no point maps "
 
145
  points_map = maps["points"]
146
  normals_map = maps["normals"]
147
  valid_mask = maps["validMask"] & (surface_mask > 0)
148
+ valid_flat = np.flatnonzero(valid_mask.ravel()).astype(np.uint32)
149
+ if len(valid_flat) < SURFACE_MIN_PLANE_PIXELS:
150
  print(
151
  "[SURFACE_MAPPING] skipped: too few valid surface pixels "
152
+ f"valid={len(valid_flat)} min={SURFACE_MIN_PLANE_PIXELS}",
153
  flush=True,
154
  )
155
  return None
156
 
157
+ points = points_map.reshape(-1, 3)[valid_flat]
158
+ normals = normals_map.reshape(-1, 3)[valid_flat]
 
 
159
  good_points = np.isfinite(points).all(axis=1)
160
  if int(good_points.sum()) < SURFACE_MIN_PLANE_PIXELS:
161
  print(
 
167
 
168
  valid_flat = valid_flat[good_points]
169
  points = points[good_points]
170
+ normals = normals[good_points]
171
+ prepared_normal_valid = maps.get("normalValidMask")
172
+ if prepared_normal_valid is not None and prepared_normal_valid.shape == surface_mask.shape:
173
+ normal_good = prepared_normal_valid.ravel()[valid_flat]
174
+ else:
175
+ normal_good = np.isfinite(normals).all(axis=1) & (np.linalg.norm(normals, axis=1) > 1e-4)
176
  normals_reliable = int(normal_good.sum()) >= SURFACE_MIN_PLANE_PIXELS
177
+ gather_ms = (time.perf_counter() - phase_started) * 1000 - geometry_maps_ms
178
 
179
  print(
180
  "[SURFACE_MAPPING] candidates "
 
184
  flush=True,
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(
192
  "[SURFACE_MAPPING] skipped: no dominant planes fitted "
 
196
  )
197
  return None
198
 
199
+ phase_started = time.perf_counter()
200
  assignment = assign_points_to_surface_planes(points, normals, planes, normals_reliable)
201
+ assignment_ms = (time.perf_counter() - phase_started) * 1000
202
+
203
+ phase_started = time.perf_counter()
204
  uv_by_mask = np.full((len(surface_indices), 2), np.nan, dtype=np.float32)
205
  plane_ids = np.full(len(surface_indices), 255, dtype=np.uint8)
206
  ordinal = np.full(surface_mask.size, -1, dtype=np.int32)
 
262
  "uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)),
263
  "uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)),
264
  })
265
+ projection_ms = (time.perf_counter() - phase_started) * 1000
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)
273
+ timing_ms = {
274
+ "geometryMaps": round(geometry_maps_ms, 2),
275
+ "pixelGather": round(gather_ms, 2),
276
+ "planeFit": round(plane_fit_ms, 2),
277
+ "planeAssignment": round(assignment_ms, 2),
278
+ "projection": round(projection_ms, 2),
279
+ "qualityAnalysis": round(quality_ms, 2),
280
+ "total": round((time.perf_counter() - total_started) * 1000, 2),
281
+ }
282
+ uv_quality["surfaceUvTimingMs"] = timing_ms
283
  print(
284
  "[SURFACE_MAPPING] success "
285
  f"planes={len(serializable_planes)} assignedPixels={int(finite_uv.sum())}/{len(surface_indices)} "
 
287
  f"mode={uv_quality['textureMappingMode']} reason={uv_quality['textureMappingReason']}",
288
  flush=True,
289
  )
290
+ print(
291
+ "[SURFACE_MAPPING_TIMING] "
292
+ + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()),
293
+ flush=True,
294
+ )
295
 
296
  return {
297
  "uv": uv_by_mask,
services/pipeline/builder.py CHANGED
@@ -18,6 +18,7 @@ from services.direction.analysis import floor_direction_geometry_inputs
18
  from services.floor.edge_coverage import scaled_odd_kernel_size
19
  from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
20
  from services.floor.detection import estimate_floor_plane
 
21
  from services.geometry.uv_mapping import build_surface_uv_mapping
22
  from services.lighting.intrinsic import build_intrinsic_lighting_maps
23
  from services.lighting.shading import build_luminance_lighting_maps, lighting_map_statistics
@@ -139,14 +140,35 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
139
 
140
  # --- Surface mask ---
141
  t0 = time.perf_counter()
 
 
 
142
  quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
143
- surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
 
 
 
 
 
 
 
 
144
  replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8)
145
  surface_indices = mask_to_indices(surface_mask)
146
  occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
147
  occlusion_indices = mask_to_indices(occlusion_mask)
148
  el = (time.perf_counter() - t0) * 1000
149
- _log_stage("Surface Masking", t0)
 
 
 
 
 
 
 
 
 
 
150
  if d:
151
  debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
152
 
@@ -154,12 +176,25 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
154
  if progress_callback:
155
  progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
156
  t0 = time.perf_counter()
157
- surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
 
 
 
 
 
158
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
159
  mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
160
  **_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
161
  el = (time.perf_counter() - t0) * 1000
162
- _log_stage("UV Mapping", t0, f"uv={'yes' if use_surface_uv else 'no'}")
 
 
 
 
 
 
 
 
163
  if d:
164
  debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
165
  if progress_callback:
@@ -226,7 +261,14 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
226
  progress_callback(PipelinePhase.DIRECTION, 0)
227
  t0 = time.perf_counter()
228
  dir_xform = plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography
229
- dir_inputs = floor_direction_geometry_inputs(surface_mask, geometry, plane, surface_mapping, use_surface_uv=use_surface_uv)
 
 
 
 
 
 
 
230
  struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
231
  sk = scaled_odd_kernel_size(h, w, 0.006, minimum=3)
232
  struct_mask = cv2.dilate(struct_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (sk, sk)), iterations=1)
 
18
  from services.floor.edge_coverage import scaled_odd_kernel_size
19
  from services.floor.mask import build_floor_surface_mask, clean_floor_mask, wall_subtract
20
  from services.floor.detection import estimate_floor_plane
21
+ from services.geometry.multi_plane import geometry_point_maps
22
  from services.geometry.uv_mapping import build_surface_uv_mapping
23
  from services.lighting.intrinsic import build_intrinsic_lighting_maps
24
  from services.lighting.shading import build_luminance_lighting_maps, lighting_map_statistics
 
140
 
141
  # --- Surface mask ---
142
  t0 = time.perf_counter()
143
+ geometry_maps_started = time.perf_counter()
144
+ prepared_geometry_maps = geometry_point_maps(floor_mask, geometry)
145
+ geometry_maps_ms = (time.perf_counter() - geometry_maps_started) * 1000
146
  quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
147
+ surface_mask, edge_metadata = build_floor_surface_mask(
148
+ floor_mask,
149
+ seg_map,
150
+ quad,
151
+ depth,
152
+ geometry,
153
+ plane,
154
+ geometry_maps=prepared_geometry_maps,
155
+ )
156
  replaced_material_mask = (seg_class_mask(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES)).astype(bool) & (surface_mask > 0)).astype(np.uint8)
157
  surface_indices = mask_to_indices(surface_mask)
158
  occlusion_mask = foreground_occlusion_mask(surface_mask, seg_map)
159
  occlusion_indices = mask_to_indices(occlusion_mask)
160
  el = (time.perf_counter() - t0) * 1000
161
+ surface_timing = edge_metadata.get("surfaceMaskingTimingMs") or {}
162
+ filter_ms = sum(float(surface_timing.get(name) or 0.0) for name in (
163
+ "initialGeometryFilter",
164
+ "postEdgeGeometryFilter",
165
+ "postSoftFloorGeometryFilter",
166
+ ))
167
+ _log_stage(
168
+ "Surface Masking",
169
+ t0,
170
+ f"geometry-prep={geometry_maps_ms:.0f}ms filters={filter_ms:.0f}ms",
171
+ )
172
  if d:
173
  debug_stages.record_surface(d, img_np, floor_mask, surface_mask, occlusion_mask, edge_metadata, el)
174
 
 
176
  if progress_callback:
177
  progress_callback(PipelinePhase.SURFACE_MAPPING, 0)
178
  t0 = time.perf_counter()
179
+ surface_mapping = build_surface_uv_mapping(
180
+ surface_mask,
181
+ surface_indices,
182
+ geometry,
183
+ geometry_maps=prepared_geometry_maps,
184
+ )
185
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
186
  mapping_metadata = surface_mapping["metadata"] if surface_mapping is not None else {
187
  **_DEFAULT_MAPPING_META, "surfaceUvTotalPixels": int(len(surface_indices))}
188
  el = (time.perf_counter() - t0) * 1000
189
+ uv_timing = mapping_metadata.get("surfaceUvTimingMs") or {}
190
+ uv_detail = f"uv={'yes' if use_surface_uv else 'no'}"
191
+ if uv_timing:
192
+ uv_detail += (
193
+ f" fit={float(uv_timing.get('planeFit') or 0.0):.0f}ms"
194
+ f" assign={float(uv_timing.get('planeAssignment') or 0.0):.0f}ms"
195
+ f" quality={float(uv_timing.get('qualityAnalysis') or 0.0):.0f}ms"
196
+ )
197
+ _log_stage("UV Mapping", t0, uv_detail)
198
  if d:
199
  debug_stages.record_surface_mapping(d, h, w, surface_indices, surface_mapping, use_surface_uv, mapping_metadata, el)
200
  if progress_callback:
 
261
  progress_callback(PipelinePhase.DIRECTION, 0)
262
  t0 = time.perf_counter()
263
  dir_xform = plane.get("floorTransform") if plane and plane.get("floorTransform") and float(plane.get("geometryConfidence") or 0.0) >= 0.35 else homography
264
+ dir_inputs = floor_direction_geometry_inputs(
265
+ surface_mask,
266
+ geometry,
267
+ plane,
268
+ surface_mapping,
269
+ use_surface_uv=use_surface_uv,
270
+ geometry_maps=prepared_geometry_maps,
271
+ )
272
  struct_mask = seg_class_mask(seg_map, class_ids({"wall", "ceiling", "door", "window", "column", "base", "railing"}))
273
  sk = scaled_odd_kernel_size(h, w, 0.006, minimum=3)
274
  struct_mask = cv2.dilate(struct_mask, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (sk, sk)), iterations=1)
test_geometry_optimization.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+
5
+ from services.floor.geometry_filter import filter_surface_by_floor_geometry
6
+ from services.geometry.multi_plane import geometry_point_maps
7
+ from services.geometry.ransac import (
8
+ _best_surface_hypothesis,
9
+ _candidate_hypotheses,
10
+ )
11
+
12
+
13
+ class GeometryOptimizationTests(unittest.TestCase):
14
+ def test_batched_ransac_scoring_matches_sequential_scoring(self):
15
+ rng = np.random.default_rng(7)
16
+ xz = rng.uniform(-2, 2, size=(4_000, 2)).astype(np.float32)
17
+ points = np.column_stack((
18
+ xz[:, 0],
19
+ rng.normal(0, 0.008, len(xz)),
20
+ xz[:, 1],
21
+ )).astype(np.float32)
22
+ normals = np.tile(np.array([0, 1, 0], dtype=np.float32), (len(points), 1))
23
+ normals += rng.normal(0, 0.02, normals.shape).astype(np.float32)
24
+ normals /= np.linalg.norm(normals, axis=1, keepdims=True)
25
+
26
+ origins, hypotheses = _candidate_hypotheses(
27
+ points,
28
+ iterations=90,
29
+ rng=np.random.default_rng(41),
30
+ )
31
+ distance_threshold = 0.03
32
+ normal_cos = 0.75
33
+ expected_index = -1
34
+ expected_count = 0
35
+ for index, (origin, normal) in enumerate(zip(origins, hypotheses, strict=True)):
36
+ distances = np.abs((points - origin) @ normal)
37
+ alignments = np.abs(normals @ normal)
38
+ count = int(((distances <= distance_threshold) & (alignments >= normal_cos)).sum())
39
+ if count > expected_count:
40
+ expected_count = count
41
+ expected_index = index
42
+
43
+ result = _best_surface_hypothesis(
44
+ points,
45
+ origins,
46
+ hypotheses,
47
+ distance_threshold,
48
+ candidate_normals=normals,
49
+ normal_cos=normal_cos,
50
+ )
51
+
52
+ self.assertIsNotNone(result)
53
+ origin, normal = result
54
+ np.testing.assert_array_equal(origin, origins[expected_index])
55
+ np.testing.assert_array_equal(normal, hypotheses[expected_index])
56
+
57
+ def test_prepared_geometry_maps_preserve_filter_output(self):
58
+ height, width = 120, 160
59
+ y_coordinates = np.arange(height, dtype=np.float32)[:, None]
60
+ x_coordinates = np.arange(width, dtype=np.float32)[None, :]
61
+ points = np.empty((height, width, 3), dtype=np.float32)
62
+ points[:, :, 0] = (x_coordinates - width / 2) / 100
63
+ points[:, :, 1] = 0
64
+ points[:, :, 2] = 1 + y_coordinates / 100
65
+ normals = np.zeros_like(points)
66
+ normals[:, :, 1] = 1
67
+ surface = np.zeros((height, width), dtype=np.uint8)
68
+ surface[height // 3:] = 1
69
+ geometry = {
70
+ "provider": "moge-2",
71
+ "points": points,
72
+ "normals": normals,
73
+ "validMask": np.ones((height, width), dtype=bool),
74
+ "intrinsics": np.eye(3, dtype=np.float32),
75
+ }
76
+ plane = {
77
+ "planeNormal": [0, 1, 0],
78
+ "planeOrigin": [0, 0, 0],
79
+ }
80
+
81
+ expected, expected_metadata = filter_surface_by_floor_geometry(surface, geometry, plane)
82
+ prepared_maps = geometry_point_maps(surface, geometry)
83
+ actual, actual_metadata = filter_surface_by_floor_geometry(
84
+ surface,
85
+ geometry,
86
+ plane,
87
+ geometry_maps=prepared_maps,
88
+ )
89
+
90
+ np.testing.assert_array_equal(actual, expected)
91
+ self.assertEqual(
92
+ actual_metadata["geometrySurfaceFilterReason"],
93
+ expected_metadata["geometrySurfaceFilterReason"],
94
+ )
95
+
96
+
97
+ if __name__ == "__main__":
98
+ unittest.main()
visualizer.gpu.toml CHANGED
@@ -21,7 +21,7 @@ enable_wall_segments = false
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_sam_refinement = false
24
- enable_floor_mask_cleanup = false
25
  warm_start_models = true
26
  debug_artifacts_enabled = false
27
  inference_max_dimension = 1024
 
21
  enable_intrinsic_shading = false
22
  enable_shading_transfer = false
23
  enable_sam_refinement = false
24
+ enable_floor_mask_cleanup = true
25
  warm_start_models = true
26
  debug_artifacts_enabled = false
27
  inference_max_dimension = 1024