from __future__ import annotations import time import cv2 import numpy as np from enums import TextureMappingMode, TextureMappingReason, PlaneFitMode from config.surface import ( SURFACE_MIN_PLANE_PIXELS, SURFACE_PLANE_DISTANCE_METERS, SURFACE_RANSAC_DISTANCE, SURFACE_UV_ABSOLUTE_JUMP_METERS, SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO, SURFACE_UV_MAX_JUMP_RATIO, SURFACE_UV_EDGE_BAND_RATIO, SURFACE_UV_MIN_COVERAGE, ) from config.runtime import ENABLE_MULTI_PLANE_SURFACES from services.geometry.multi_plane import ( assign_points_to_surface_planes, fit_multi_surface_planes, geometry_point_maps, ) from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold from services.geometry.plane_uv import ray_plane_uv def analyze_surface_uv_quality( surface_mask: np.ndarray, surface_indices: np.ndarray, uv_by_mask: np.ndarray, plane_ids: np.ndarray, ) -> dict: total_pixels = int(len(surface_indices)) finite_uv = np.isfinite(uv_by_mask).all(axis=1) if total_pixels else np.zeros(0, dtype=bool) finite_pixels = int(finite_uv.sum()) coverage = float(finite_pixels / max(total_pixels, 1)) active_plane_ids = sorted({ int(plane_id) for plane_id in np.unique(plane_ids[finite_uv]) if int(plane_id) != 255 }) quality = { "surfaceUvEnabled": False, "textureMappingMode": TextureMappingMode.REGULARIZED_FLOOR_PLANE, "textureMappingReason": TextureMappingReason.SURFACE_UV_UNAVAILABLE, "surfaceUvCoverage": coverage, "surfaceUvFinitePixels": finite_pixels, "surfaceUvTotalPixels": total_pixels, "surfaceUvNeighborCount": 0, "surfaceUvMedianNeighborDelta": None, "surfaceUvP95NeighborDelta": None, "surfaceUvP99NeighborDelta": None, "surfaceUvJumpLimit": None, "surfaceUvBadNeighborRatio": None, "surfaceUvPlaneBoundaryRatio": None, "surfaceUvAssignedPlaneCount": len(active_plane_ids), } if total_pixels == 0: quality["textureMappingReason"] = TextureMappingReason.EMPTY_SURFACE return quality if coverage < SURFACE_UV_MIN_COVERAGE: quality["textureMappingReason"] = TextureMappingReason.INCOMPLETE_SURFACE_UV return quality h, w = surface_mask.shape[:2] uv_grid = np.full((h * w, 2), np.nan, dtype=np.float32) plane_grid = np.full(h * w, 255, dtype=np.uint8) uv_grid[surface_indices[finite_uv]] = uv_by_mask[finite_uv] plane_grid[surface_indices[finite_uv]] = plane_ids[finite_uv] uv_grid = uv_grid.reshape(h, w, 2) plane_grid = plane_grid.reshape(h, w) finite_grid = np.isfinite(uv_grid).all(axis=2) surface_bool = surface_mask.astype(bool) right = surface_bool[:, :-1] & surface_bool[:, 1:] & finite_grid[:, :-1] & finite_grid[:, 1:] down = surface_bool[:-1, :] & surface_bool[1:, :] & finite_grid[:-1, :] & finite_grid[1:, :] right_plane_boundary = right & (plane_grid[:, :-1] != plane_grid[:, 1:]) down_plane_boundary = down & (plane_grid[:-1, :] != plane_grid[1:, :]) same_right = right & ~right_plane_boundary same_down = down & ~down_plane_boundary deltas = [] if same_right.any(): deltas.append(np.linalg.norm(uv_grid[:, 1:][same_right] - uv_grid[:, :-1][same_right], axis=1)) if same_down.any(): deltas.append(np.linalg.norm(uv_grid[1:, :][same_down] - uv_grid[:-1, :][same_down], axis=1)) neighbor_count = int(right.sum() + down.sum()) plane_boundary_count = int(right_plane_boundary.sum() + down_plane_boundary.sum()) quality["surfaceUvNeighborCount"] = neighbor_count quality["surfaceUvPlaneBoundaryRatio"] = float(plane_boundary_count / max(neighbor_count, 1)) if not deltas: quality["textureMappingReason"] = TextureMappingReason.INSUFFICIENT_UV_NEIGHBORS return quality all_deltas = np.concatenate(deltas).astype(np.float32) median_delta = float(np.median(all_deltas)) p95_delta = float(np.percentile(all_deltas, 95)) p99_delta = float(np.percentile(all_deltas, 99)) jump_limit = max(SURFACE_UV_ABSOLUTE_JUMP_METERS, median_delta * SURFACE_UV_MAX_JUMP_RATIO) bad_ratio = float((all_deltas > jump_limit).mean()) quality.update({ "surfaceUvMedianNeighborDelta": median_delta, "surfaceUvP95NeighborDelta": p95_delta, "surfaceUvP99NeighborDelta": p99_delta, "surfaceUvJumpLimit": float(jump_limit), "surfaceUvBadNeighborRatio": bad_ratio, }) if bad_ratio > SURFACE_UV_MAX_BAD_NEIGHBOR_RATIO: quality["textureMappingReason"] = TextureMappingReason.NOISY_SURFACE_UV return quality quality["surfaceUvEnabled"] = True quality["textureMappingMode"] = TextureMappingMode.SURFACE_UV quality["textureMappingReason"] = ( TextureMappingReason.SURFACE_UV_QUALITY_OK if len(active_plane_ids) <= 1 else TextureMappingReason.MULTI_PLANE_SURFACE_UV_QUALITY_OK ) return quality def _plane_uvs_along_edge( surface_mask: np.ndarray, surface_indices: np.ndarray, intrinsics: np.ndarray, planes: list[dict], uv_by_mask: np.ndarray, plane_ids: np.ndarray, ray_fill_mask: np.ndarray | None, ) -> tuple[int, int]: """Floor-plane UVs where measured depth is unreliable: at the surface's edge. Depth is blurry where the floor meets a wall or furniture, and edge pixels often carry the 3D point of the object itself (a speaker's foot sits within the plane distance limit), which stretches the tile into a smear. In the outer half of the edge band the UV is where the pixel's camera ray meets the main plane; across the inner half it hands over to the measured point, so there is no seam. `ray_fill_mask` pixels with no UV at all also take the plane's UV. Returns (pixels filled, pixels blended); updates the arrays in place. """ if not planes or not len(surface_indices): return 0, 0 main = max(range(len(planes)), key=lambda idx: planes[idx].get("assignedCount", 0)) plane = planes[main] finite = np.isfinite(uv_by_mask).all(axis=1) on_main = finite & (plane_ids == main) band = SURFACE_UV_EDGE_BAND_RATIO * min(surface_mask.shape[:2]) # Distance (px) to the nearest pixel outside the surface; the photo's border is not an edge. distance = cv2.distanceTransform((surface_mask > 0).astype(np.uint8), cv2.DIST_L2, 3).ravel()[surface_indices] blend = (distance < band) & on_main fill = ~finite & ( ray_fill_mask.ravel()[surface_indices].astype(bool) if ray_fill_mask is not None else False ) targets = blend | fill if not targets.any(): return 0, 0 uv, hit = ray_plane_uv( surface_indices[targets], surface_mask.shape[1], intrinsics, plane["origin"], plane["normal"], plane["uAxis"], plane["vAxis"], ) positions = np.flatnonzero(targets)[hit] uv = uv[hit] # Plane UVs across the outer half of the band, then a linear hand-over to the measured ones. weight = np.clip(2.0 * (1.0 - distance[positions] / max(band, 1.0)), 0.0, 1.0)[:, None] measured = uv_by_mask[positions] has_measured = np.isfinite(measured).all(axis=1) uv_by_mask[positions] = np.where(has_measured[:, None], weight * uv + (1.0 - weight) * measured, uv) plane_ids[positions] = main return int((~has_measured).sum()), int(has_measured.sum()) def build_surface_uv_mapping( surface_mask: np.ndarray, surface_indices: np.ndarray, geometry: dict | None, *, geometry_maps: dict | None = None, ray_fill_mask: np.ndarray | None = None, ): """Per-pixel floor UVs from the 3D point map, plane by plane. `ray_fill_mask` marks pixels (edge refinement's additions along walls and furniture) whose measured depth is unreliable: where they get no UV from their own 3D point, the UV comes from their camera ray meeting the main plane. """ total_started = time.perf_counter() phase_started = total_started maps = geometry_maps if geometry_maps is not None else geometry_point_maps(surface_mask, geometry) geometry_maps_ms = (time.perf_counter() - phase_started) * 1000 if maps is None: print( "[SURFACE_MAPPING] skipped: no point maps " f"enabled={ENABLE_MULTI_PLANE_SURFACES} " f"provider={geometry.get('provider') if geometry else None}", flush=True, ) return None points_map = maps["points"] normals_map = maps["normals"] valid_mask = maps["validMask"] & (surface_mask > 0) valid_flat = np.flatnonzero(valid_mask.ravel()).astype(np.uint32) if len(valid_flat) < SURFACE_MIN_PLANE_PIXELS: print( "[SURFACE_MAPPING] skipped: too few valid surface pixels " f"valid={len(valid_flat)} min={SURFACE_MIN_PLANE_PIXELS}", flush=True, ) return None points = points_map.reshape(-1, 3)[valid_flat] normals = normals_map.reshape(-1, 3)[valid_flat] good_points = np.isfinite(points).all(axis=1) if int(good_points.sum()) < SURFACE_MIN_PLANE_PIXELS: print( "[SURFACE_MAPPING] skipped: too few finite 3D points " f"finitePoints={int(good_points.sum())} min={SURFACE_MIN_PLANE_PIXELS}", flush=True, ) return None valid_flat = valid_flat[good_points] points = points[good_points] normals = normals[good_points] prepared_normal_valid = maps.get("normalValidMask") if prepared_normal_valid is not None and prepared_normal_valid.shape == surface_mask.shape: normal_good = prepared_normal_valid.ravel()[valid_flat] else: normal_good = np.isfinite(normals).all(axis=1) & (np.linalg.norm(normals, axis=1) > 1e-4) normals_reliable = int(normal_good.sum()) >= SURFACE_MIN_PLANE_PIXELS gather_ms = (time.perf_counter() - phase_started) * 1000 - geometry_maps_ms print( "[SURFACE_MAPPING] candidates " f"surfacePixels={int(surface_mask.sum())} validPixels={len(points)} " f"normalPixels={int(normal_good.sum())} normalsReliable={normals_reliable} " f"provider={geometry.get('provider') if geometry else None}", flush=True, ) phase_started = time.perf_counter() planes = fit_multi_surface_planes(points, normals, normals_reliable) plane_fit_ms = (time.perf_counter() - phase_started) * 1000 if not planes: print( "[SURFACE_MAPPING] skipped: no dominant planes fitted " f"validPixels={len(points)} threshold={surface_distance_threshold(points):.4f} " f"normalsReliable={normals_reliable}", flush=True, ) return None phase_started = time.perf_counter() assignment = assign_points_to_surface_planes(points, normals, planes, normals_reliable) assignment_ms = (time.perf_counter() - phase_started) * 1000 phase_started = time.perf_counter() uv_by_mask = np.full((len(surface_indices), 2), np.nan, dtype=np.float32) plane_ids = np.full(len(surface_indices), 255, dtype=np.uint8) ordinal = np.full(surface_mask.size, -1, dtype=np.int32) ordinal[surface_indices] = np.arange(len(surface_indices), dtype=np.int32) positions = ordinal[valid_flat] assignment_distance_limit = max( float(SURFACE_RANSAC_DISTANCE) * 1.5, min(float(SURFACE_PLANE_DISTANCE_METERS), surface_distance_threshold(points) * 1.35), ) rejected_by_distance = 0 for plane_idx, plane in enumerate(planes): assigned = assignment == plane_idx if not assigned.any(): plane["assignedCount"] = 0 continue projected_points, signed_distances = project_points_to_plane( points[assigned], plane["origin"], plane["normal"], ) near_plane = np.abs(signed_distances) <= assignment_distance_limit rejected_by_distance += int((~near_plane).sum()) if not near_plane.any(): plane["assignedCount"] = 0 continue delta = projected_points[near_plane] - plane["origin"] uv = np.column_stack((delta @ plane["uAxis"], delta @ plane["vAxis"])).astype(np.float32) assigned_positions = positions[assigned][near_plane] assigned_keep = assigned_positions >= 0 assigned_positions = assigned_positions[assigned_keep] uv_by_mask[assigned_positions] = uv[assigned_keep] plane_ids[assigned_positions] = plane_idx plane["assignedCount"] = int(assigned_keep.sum()) ray_filled, edge_blended = _plane_uvs_along_edge( surface_mask, surface_indices, maps["intrinsics"], planes, uv_by_mask, plane_ids, ray_fill_mask, ) serializable_planes = [] for plane in planes: assigned_plane_uv = uv_by_mask[plane_ids == int(plane["id"])] assigned_plane_uv = assigned_plane_uv[np.isfinite(assigned_plane_uv).all(axis=1)] if len(assigned_plane_uv): uv_min = np.min(assigned_plane_uv, axis=0) uv_max = np.max(assigned_plane_uv, axis=0) else: uv_min = np.zeros(2, dtype=np.float32) uv_max = np.ones(2, dtype=np.float32) serializable_planes.append({ "id": int(plane["id"]), "normal": plane["normal"].astype(float).tolist(), "origin": plane["origin"].astype(float).tolist(), "offset": float(plane["offset"]), "uAxis": plane["uAxis"].astype(float).tolist(), "vAxis": plane["vAxis"].astype(float).tolist(), "inlierCount": int(plane["inlierCount"]), "assignedCount": int(plane.get("assignedCount", 0)), "isFloor": bool(plane["isFloor"]), "fitMode": str(plane.get("fitMode", PlaneFitMode.NORMAL_AWARE)), "uvMin": uv_min.astype(float).tolist(), "uvMax": uv_max.astype(float).tolist(), "uvWidth": float(max(uv_max[0] - uv_min[0], 0.05)), "uvHeight": float(max(uv_max[1] - uv_min[1], 0.05)), }) projection_ms = (time.perf_counter() - phase_started) * 1000 phase_started = time.perf_counter() finite_uv = np.isfinite(uv_by_mask).all(axis=1) uv_quality = analyze_surface_uv_quality(surface_mask, surface_indices, uv_by_mask, plane_ids) quality_ms = (time.perf_counter() - phase_started) * 1000 uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit) uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance) uv_quality["surfaceUvRayFilledPixels"] = ray_filled uv_quality["surfaceUvEdgeBlendedPixels"] = edge_blended timing_ms = { "geometryMaps": round(geometry_maps_ms, 2), "pixelGather": round(gather_ms, 2), "planeFit": round(plane_fit_ms, 2), "planeAssignment": round(assignment_ms, 2), "projection": round(projection_ms, 2), "qualityAnalysis": round(quality_ms, 2), "total": round((time.perf_counter() - total_started) * 1000, 2), } uv_quality["surfaceUvTimingMs"] = timing_ms print( "[SURFACE_MAPPING] success " f"planes={len(serializable_planes)} assignedPixels={int(finite_uv.sum())}/{len(surface_indices)} " f"fitModes={[plane['fitMode'] for plane in serializable_planes]} " f"mode={uv_quality['textureMappingMode']} reason={uv_quality['textureMappingReason']}", flush=True, ) print( "[SURFACE_MAPPING_TIMING] " + " ".join(f"{name}={duration:.2f}ms" for name, duration in timing_ms.items()), flush=True, ) return { "uv": uv_by_mask, "planeIds": plane_ids, "planes": serializable_planes, "normalMap": normals_map, "validMask": valid_mask, "intrinsics": maps["intrinsics"], "depthScale": maps["depthScale"], "normalsReliable": normals_reliable, "useSurfaceUv": bool(uv_quality["surfaceUvEnabled"]), "metadata": uv_quality, }