Download services/geometry/uv_mapping.py from modventures/room-visualizer-v2: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/geometry/uv_mapping.py
- Command line
-
hf download hf://spaces/modventures/room-visualizer-v2/services/geometry/uv_mapping.py
-
curl -L -o uv_mapping.py https://huggingface.co/spaces/modventures/room-visualizer-v2/resolve/main/services/geometry/uv_mapping.py
16.6 kB
| from __future__ import annotations | |
| import time | |
| 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_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, | |
| merge_coplanar_planes, | |
| ) | |
| from services.geometry.plane_fitting import project_points_to_plane, surface_distance_threshold | |
| def analyze_surface_uv_quality( | |
| surface_mask: np.ndarray, | |
| surface_indices: np.ndarray, | |
| uv_by_mask: np.ndarray, | |
| plane_ids: np.ndarray, | |
| min_coverage: float = SURFACE_UV_MIN_COVERAGE, | |
| ) -> 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 < 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 build_surface_uv_mapping( | |
| surface_mask: np.ndarray, | |
| surface_indices: np.ndarray, | |
| geometry: dict | None, | |
| *, | |
| geometry_maps: dict | None = None, | |
| mark_floor: bool = True, | |
| min_coverage: float | None = None, | |
| fill_missing_from_plane: bool = False, | |
| vertical_ref: np.ndarray | None = None, | |
| ): | |
| 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, mark_floor=mark_floor, | |
| vertical_ref=vertical_ref) | |
| if not mark_floor: | |
| # One flat wall attracts several near-identical RANSAC planes when | |
| # normals are noisy. Distinct plane ids mean distinct UV origins, so | |
| # the tile grid would restart mid-wall. Floors keep the original | |
| # behaviour untouched. | |
| planes = merge_coplanar_planes(planes, surface_distance_threshold(points), | |
| vertical_ref=vertical_ref) | |
| 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()) | |
| if fill_missing_from_plane and planes: | |
| # Pixels with no usable depth still belong to the surface: on a wall they | |
| # are the TV, the mirror, the cabinet standing in front of it. Their 3D | |
| # points describe the *object*, not the wall, so plane assignment leaves | |
| # them without UV and coverage collapses (0.78 on one living-room wall). | |
| # | |
| # We know the plane and the camera, so a UV exists regardless of depth: | |
| # intersect each pixel's camera ray with the plane. That both restores | |
| # coverage and makes the tile grid continue correctly behind the object, | |
| # which is what tiling *behind* an occluder is supposed to look like. | |
| missing = ~np.isfinite(uv_by_mask).all(axis=1) | |
| if missing.any(): | |
| dominant_idx = int(np.argmax([ | |
| int(plane.get("assignedCount", 0)) or int(plane["inlierCount"]) | |
| for plane in planes | |
| ])) | |
| dominant = planes[dominant_idx] | |
| width = surface_mask.shape[1] | |
| flat = surface_indices[missing].astype(np.int64) | |
| pixel_y = (flat // width).astype(np.float32) | |
| pixel_x = (flat % width).astype(np.float32) | |
| intrinsics = np.asarray(maps["intrinsics"], dtype=np.float32) | |
| fx = float(intrinsics[0, 0]) or 1.0 | |
| fy = float(intrinsics[1, 1]) or 1.0 | |
| cx, cy = float(intrinsics[0, 2]), float(intrinsics[1, 2]) | |
| rays = np.column_stack(( | |
| (pixel_x - cx) / fx, | |
| (pixel_y - cy) / fy, | |
| np.ones(len(pixel_x), dtype=np.float32), | |
| )).astype(np.float32) | |
| normal = np.asarray(dominant["normal"], dtype=np.float32) | |
| origin = np.asarray(dominant["origin"], dtype=np.float32) | |
| denominator = rays @ normal | |
| usable = np.abs(denominator) > 1e-6 | |
| distances = np.zeros(len(rays), dtype=np.float32) | |
| distances[usable] = float(origin @ normal) / denominator[usable] | |
| usable &= distances > 0 # plane behind the camera is not a hit | |
| if usable.any(): | |
| hit = rays[usable] * distances[usable, None] | |
| delta = hit - origin | |
| filled_uv = np.column_stack(( | |
| delta @ np.asarray(dominant["uAxis"], dtype=np.float32), | |
| delta @ np.asarray(dominant["vAxis"], dtype=np.float32), | |
| )).astype(np.float32) | |
| target = np.where(missing)[0][usable] | |
| uv_by_mask[target] = filled_uv | |
| plane_ids[target] = dominant_idx | |
| print( | |
| f"[SURFACE_MAPPING] ray-plane filled {int(usable.sum())} " | |
| f"occluded pixels from plane {dominant_idx}", | |
| flush=True, | |
| ) | |
| 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, | |
| min_coverage=SURFACE_UV_MIN_COVERAGE if min_coverage is None else min_coverage, | |
| ) | |
| quality_ms = (time.perf_counter() - phase_started) * 1000 | |
| uv_quality["surfaceUvPlaneDistanceLimitMeters"] = float(assignment_distance_limit) | |
| uv_quality["surfaceUvRejectedByPlaneDistance"] = int(rejected_by_distance) | |
| 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, | |
| } | |