Spaces:
Paused
Paused
Download apps/renderer/services/geometry/multi_plane.py from modventures/prevision: direct link, hf CLI and curl.
- Browser
- Download file 7.55 kB
-
https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/geometry/multi_plane.py
- Command line
-
hf download hf://spaces/modventures/prevision/apps/renderer/services/geometry/multi_plane.py
-
curl -L -o multi_plane.py https://huggingface.co/spaces/modventures/prevision/resolve/main/apps/renderer/services/geometry/multi_plane.py
7.55 kB
| from __future__ import annotations | |
| import numpy as np | |
| from enums import PlaneFitMode | |
| from config.models import DEPTH_MODEL_NAME | |
| from config.runtime import ENABLE_MULTI_PLANE_SURFACES | |
| from config.surface import ( | |
| SURFACE_MAX_PLANES, | |
| SURFACE_MIN_PLANE_PIXELS, | |
| SURFACE_NORMAL_ANGLE_DEGREES, | |
| SURFACE_NORMAL_SMOOTHING_KERNEL, | |
| SURFACE_RANSAC_DISTANCE, | |
| ) | |
| from services.geometry.camera import ( | |
| backproject_depth, | |
| pixel_intrinsics_from_model, | |
| prepare_depth_for_backprojection, | |
| ) | |
| from services.geometry.normals import compute_normals_from_points, smooth_normal_map | |
| from services.geometry.plane_fitting import plane_basis, surface_distance_threshold | |
| from services.geometry.ransac import ransac_surface_plane, ransac_surface_plane_by_distance | |
| MIN_SECONDARY_PLANE_RATIO = 0.05 | |
| def _prune_weak_secondary_planes(planes: list[dict]) -> list[dict]: | |
| if not planes: | |
| return [] | |
| primary_inliers = max(plane["inlierCount"] for plane in planes) | |
| retained_planes = [ | |
| plane | |
| for plane in planes | |
| if plane["inlierCount"] >= primary_inliers * MIN_SECONDARY_PLANE_RATIO | |
| ] | |
| for plane_id, plane in enumerate(retained_planes): | |
| plane["id"] = plane_id | |
| return retained_planes | |
| def geometry_point_maps(mask: np.ndarray, geometry: dict | None): | |
| if not ENABLE_MULTI_PLANE_SURFACES or geometry is None: | |
| return None | |
| h, w = mask.shape[:2] | |
| points = geometry.get("points") | |
| point_source = "raw-point-map" | |
| valid_mask = geometry.get("validMask") | |
| intrinsics = geometry.get("intrinsics") | |
| depth_scale = None | |
| if points is None: | |
| depth = geometry.get("depth") | |
| if depth is None: | |
| return None | |
| provider = geometry.get("provider", "") | |
| is_metric_depth = "metric" in DEPTH_MODEL_NAME.lower() or "metric" in provider.lower() | |
| depth_for_points, depth_scale = prepare_depth_for_backprojection(depth, mask, is_metric_depth) | |
| pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) | |
| points = backproject_depth(depth_for_points, pixel_intrinsics) | |
| valid_mask = np.isfinite(depth_for_points) & (depth_for_points > 0.05) | |
| point_source = f"{provider or 'depth'}-backprojection" | |
| else: | |
| points = points.astype(np.float32, copy=False) | |
| pixel_intrinsics = pixel_intrinsics_from_model(intrinsics, w, h) | |
| if valid_mask is None: | |
| valid_mask = np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) | |
| valid_mask = valid_mask.astype(bool, copy=False) & np.isfinite(points).all(axis=2) & (points[:, :, 2] > 0.05) | |
| print( | |
| "[FLOOR_3D_POINTS] point map ready for floor mapping " | |
| f"source={point_source} provider={geometry.get('provider')} shape={points.shape} " | |
| f"validPixels={int(valid_mask.sum())} floorMaskPixels={int(mask.sum())}", | |
| flush=True, | |
| ) | |
| normals = geometry.get("normals") | |
| if normals is None or normals.shape[:2] != mask.shape: | |
| normals = compute_normals_from_points(points, valid_mask, SURFACE_NORMAL_SMOOTHING_KERNEL) | |
| else: | |
| normals = smooth_normal_map(normals.astype(np.float32, copy=False), SURFACE_NORMAL_SMOOTHING_KERNEL) | |
| normal_valid_mask = np.isfinite(normals).all(axis=2) & (np.linalg.norm(normals, axis=2) > 1e-4) | |
| return { | |
| "points": points.astype(np.float32, copy=False), | |
| "normals": normals.astype(np.float32, copy=False), | |
| "normalValidMask": normal_valid_mask, | |
| "validMask": valid_mask, | |
| "intrinsics": pixel_intrinsics.astype(np.float32), | |
| "depthScale": depth_scale, | |
| } | |
| def fit_multi_surface_planes( | |
| points: np.ndarray, | |
| normals: np.ndarray, | |
| normals_reliable: bool = True, | |
| max_planes: int | None = None, | |
| ): | |
| """Sequential RANSAC plane fitting. | |
| max_planes defaults to SURFACE_MAX_PLANES (the floor's budget); walls pass | |
| WALL_MAX_PLANES so they can split into several planes without changing | |
| how the floor is fitted. | |
| """ | |
| plane_budget = SURFACE_MAX_PLANES if max_planes is None else max(1, int(max_planes)) | |
| if len(points) < SURFACE_MIN_PLANE_PIXELS: | |
| return [] | |
| distance_threshold = surface_distance_threshold(points) | |
| normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) | |
| rng = np.random.default_rng(29) | |
| sample_count = min(len(points), 26000) | |
| sample_indices = rng.choice(len(points), size=sample_count, replace=False) | |
| remaining = np.ones(len(points), dtype=bool) | |
| planes = [] | |
| for plane_id in range(plane_budget): | |
| candidates = sample_indices[remaining[sample_indices]] | |
| if len(candidates) < max(300, SURFACE_MIN_PLANE_PIXELS // 6): | |
| break | |
| fit_mode = PlaneFitMode.NORMAL_AWARE | |
| result = None | |
| if normals_reliable: | |
| result = ransac_surface_plane( | |
| points, | |
| normals, | |
| candidates, | |
| remaining, | |
| distance_threshold, | |
| normal_cos, | |
| ) | |
| if result is None: | |
| fit_mode = "distance-only" | |
| result = ransac_surface_plane_by_distance( | |
| points, | |
| candidates, | |
| remaining, | |
| distance_threshold, | |
| ) | |
| if result is None: | |
| break | |
| origin, normal, inliers = result | |
| inlier_count = int(inliers.sum()) | |
| if inlier_count < SURFACE_MIN_PLANE_PIXELS: | |
| break | |
| planes.append({ | |
| "id": plane_id, | |
| "origin": origin.astype(np.float32), | |
| "normal": normal.astype(np.float32), | |
| "offset": float(-origin @ normal), | |
| "inlierCount": inlier_count, | |
| "fitMode": fit_mode, | |
| }) | |
| remaining[inliers] = False | |
| if int(remaining.sum()) < SURFACE_MIN_PLANE_PIXELS: | |
| break | |
| if not planes: | |
| return [] | |
| planes = _prune_weak_secondary_planes(planes) | |
| floor_id = int(np.argmax([ | |
| plane["inlierCount"] * max(0.1, abs(float(plane["normal"][1]))) | |
| for plane in planes | |
| ])) | |
| for idx, plane in enumerate(planes): | |
| plane["isFloor"] = idx == floor_id | |
| u_axis, v_axis = plane_basis(plane["normal"], plane["isFloor"]) | |
| plane["uAxis"] = u_axis | |
| plane["vAxis"] = v_axis | |
| return planes | |
| def assign_points_to_surface_planes( | |
| points: np.ndarray, | |
| normals: np.ndarray, | |
| planes: list[dict], | |
| normals_reliable: bool = True, | |
| ): | |
| plane_normals = np.asarray([plane["normal"] for plane in planes], dtype=np.float32) | |
| plane_origins = np.asarray([plane["origin"] for plane in planes], dtype=np.float32) | |
| offsets = -np.sum(plane_normals * plane_origins, axis=1) | |
| distances = np.abs(points @ plane_normals.T + offsets[None, :]) | |
| if not normals_reliable: | |
| return np.argmin(distances, axis=1).astype(np.int32) | |
| alignments = np.abs(normals @ plane_normals.T) | |
| normal_cos = float(np.cos(np.deg2rad(SURFACE_NORMAL_ANGLE_DEGREES))) | |
| distance_threshold = float(SURFACE_RANSAC_DISTANCE) * 1.5 | |
| denom = max(1.0 - normal_cos, 1e-3) | |
| score = distances / max(distance_threshold, 1e-6) + (1.0 - alignments) / denom | |
| ok = (distances <= distance_threshold) & (alignments >= normal_cos) | |
| score[~ok] = np.inf | |
| assignment = np.argmin(score, axis=1).astype(np.int32) | |
| has_match = np.isfinite(score[np.arange(len(points)), assignment]) | |
| if not has_match.all(): | |
| assignment[~has_match] = np.argmin(distances[~has_match], axis=1).astype(np.int32) | |
| return assignment | |