Download services/geometry/plane_fitting.py from modventures/floor-visualizer-gpu: direct link, hf CLI and curl.
- Browser
- Download file 8.81 kB
-
https://huggingface.co/spaces/modventures/floor-visualizer-gpu/resolve/main/services/geometry/plane_fitting.py
- Command line
-
hf download hf://spaces/modventures/floor-visualizer-gpu/services/geometry/plane_fitting.py
-
curl -L -o plane_fitting.py https://huggingface.co/spaces/modventures/floor-visualizer-gpu/resolve/main/services/geometry/plane_fitting.py
8.81 kB
| from __future__ import annotations | |
| import cv2 | |
| import numpy as np | |
| from enums import GeometryProvider, PlaneFitMode | |
| from config.surface import SURFACE_RANSAC_DISTANCE | |
| from services.geometry.camera import ( | |
| backproject_depth, | |
| pixel_intrinsics_from_model, | |
| prepare_depth_for_backprojection, | |
| ) | |
| def project_points_to_plane(points: np.ndarray, origin: np.ndarray, normal: np.ndarray): | |
| normal = normal.astype(np.float32) | |
| normal /= max(float(np.linalg.norm(normal)), 1e-6) | |
| signed_distance = (points - origin) @ normal | |
| projected = points - signed_distance[:, None] * normal | |
| return projected.astype(np.float32), signed_distance.astype(np.float32) | |
| def refine_plane(points: np.ndarray, normals: np.ndarray | None = None): | |
| centroid = np.median(points, axis=0).astype(np.float32) | |
| _, _, vh = np.linalg.svd(points - centroid, full_matrices=False) | |
| normal = vh[-1].astype(np.float32) | |
| normal /= max(float(np.linalg.norm(normal)), 1e-6) | |
| if normals is not None and len(normals): | |
| reference = np.median(normals, axis=0).astype(np.float32) | |
| if float(np.linalg.norm(reference)) > 1e-6 and float(normal @ reference) < 0: | |
| normal = -normal | |
| elif normal[1] < 0: | |
| normal = -normal | |
| return centroid, normal | |
| def plane_basis(normal: np.ndarray, is_floor: bool): | |
| normal = normal.astype(np.float32) | |
| normal /= max(float(np.linalg.norm(normal)), 1e-6) | |
| if is_floor: | |
| ref = np.array([1.0, 0.0, 0.0], dtype=np.float32) | |
| u_axis = ref - normal * float(ref @ normal) | |
| if float(np.linalg.norm(u_axis)) < 1e-5: | |
| ref = np.array([0.0, 0.0, 1.0], dtype=np.float32) | |
| u_axis = ref - normal * float(ref @ normal) | |
| u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6) | |
| v_axis = np.cross(normal, u_axis) | |
| else: | |
| vertical_ref = np.array([0.0, 1.0, 0.0], dtype=np.float32) | |
| v_axis = vertical_ref - normal * float(vertical_ref @ normal) | |
| if float(np.linalg.norm(v_axis)) < 1e-5: | |
| vertical_ref = np.array([0.0, 0.0, 1.0], dtype=np.float32) | |
| v_axis = vertical_ref - normal * float(vertical_ref @ normal) | |
| v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6) | |
| u_axis = np.cross(v_axis, normal) | |
| u_axis /= max(float(np.linalg.norm(u_axis)), 1e-6) | |
| v_axis /= max(float(np.linalg.norm(v_axis)), 1e-6) | |
| return u_axis.astype(np.float32), v_axis.astype(np.float32) | |
| def surface_distance_threshold(points: np.ndarray) -> float: | |
| span = np.percentile(points, 95, axis=0) - np.percentile(points, 5, axis=0) | |
| adaptive = max(0.025, float(np.linalg.norm(span)) * 0.012) | |
| return float(np.clip(max(float(SURFACE_RANSAC_DISTANCE), adaptive), 0.025, 0.20)) | |
| def fit_metric_floor_transform( | |
| mask: np.ndarray, | |
| points_map: np.ndarray, | |
| valid_mask: np.ndarray | None = None, | |
| normals_map: np.ndarray | None = None, | |
| intrinsics: np.ndarray | None = None, | |
| provider: str = GeometryProvider.METRIC_DEPTH, | |
| surface_kind: str = "floor", | |
| ): | |
| # Import here to avoid circular dependency with ransac module | |
| from services.geometry.ransac import ransac_plane_fit | |
| h, w = mask.shape[:2] | |
| valid = (mask > 0) & np.isfinite(points_map).all(axis=2) & (points_map[:, :, 2] > 0.05) | |
| if valid_mask is not None: | |
| valid &= valid_mask.astype(bool) | |
| ys, xs = np.where(valid) | |
| if len(xs) < 2000: | |
| return None | |
| stride = max(1, len(xs) // 18000) | |
| xs = xs[::stride] | |
| ys = ys[::stride] | |
| points = points_map[ys, xs].astype(np.float32) | |
| normal_consistency = 1.0 | |
| if normals_map is not None and normals_map.shape[:2] == mask.shape: | |
| sample_normals = normals_map[ys, xs].astype(np.float32) | |
| lengths = np.linalg.norm(sample_normals, axis=1) | |
| good_normals = np.isfinite(sample_normals).all(axis=1) & (lengths > 1e-4) | |
| sample_normals[good_normals] /= lengths[good_normals, None] | |
| if good_normals.sum() >= 1000: | |
| reference = np.median(sample_normals[good_normals], axis=0) | |
| reference /= max(float(np.linalg.norm(reference)), 1e-6) | |
| aligned = np.abs(sample_normals @ reference) | |
| normal_keep = good_normals & (aligned >= np.cos(np.deg2rad(30))) | |
| normal_consistency = float(normal_keep.mean()) | |
| if normal_keep.sum() >= 1000: | |
| points = points[normal_keep] | |
| xs = xs[normal_keep] | |
| ys = ys[normal_keep] | |
| ransac_fit = ransac_plane_fit(points) | |
| if ransac_fit is not None: | |
| centroid, normal, keep = ransac_fit | |
| else: | |
| keep = np.ones(len(points), dtype=bool) | |
| normal = np.array([0.0, 1.0, 0.0], dtype=np.float32) | |
| centroid = np.median(points, axis=0) | |
| for _ in range(4): | |
| fit_points = points[keep] | |
| if len(fit_points) < 1000: | |
| return None | |
| centroid = np.median(fit_points, axis=0) | |
| _, _, vh = np.linalg.svd(fit_points - centroid, full_matrices=False) | |
| normal = vh[-1].astype(np.float32) | |
| distances = np.abs((points - centroid) @ normal) | |
| threshold = max(0.025, float(np.percentile(distances[keep], 70)) * 1.8) | |
| keep = distances <= threshold | |
| if normal[1] < 0: | |
| normal = -normal | |
| inlier_ratio = float(keep.mean()) | |
| residual = float(np.median(np.abs((points[keep] - centroid) @ normal))) | |
| if inlier_ratio < 0.45 or residual > 0.18: | |
| return None | |
| # Use local horizontal/vertical axes for walls and horizontal/depth axes | |
| # for floors. This keeps physical tile dimensions stable across surfaces. | |
| u_axis, v_axis = plane_basis(normal, is_floor=surface_kind != "wall") | |
| projected_points, _ = project_points_to_plane(points[keep], centroid, normal) | |
| floor_points = projected_points - centroid | |
| uv = np.column_stack((floor_points @ u_axis, floor_points @ v_axis)).astype(np.float32) | |
| uv_min = np.min(uv, axis=0) | |
| uv_max = np.max(uv, axis=0) | |
| image_points = np.column_stack((xs[keep], ys[keep])).astype(np.float32) | |
| transform, ransac_mask = cv2.findHomography( | |
| image_points, | |
| uv, | |
| method=cv2.RANSAC, | |
| ransacReprojThreshold=0.08, | |
| maxIters=3000, | |
| confidence=0.995, | |
| ) | |
| if transform is None: | |
| return None | |
| homography_inliers = float(ransac_mask.mean()) if ransac_mask is not None else 0.0 | |
| confidence = float(np.clip( | |
| 0.55 * inlier_ratio | |
| + 0.30 * homography_inliers | |
| + 0.15 * normal_consistency | |
| - min(residual / 0.18, 1.0) * 0.25, | |
| 0.0, | |
| 1.0, | |
| )) | |
| pixel_intrinsics = ( | |
| pixel_intrinsics_from_model(intrinsics, w, h) | |
| if intrinsics is not None | |
| else None | |
| ) | |
| return { | |
| "floorTransform": transform.flatten().tolist(), | |
| "surfaceTransform": transform.flatten().tolist(), | |
| "surfaceType": surface_kind, | |
| "surfaceUAxis": u_axis.tolist(), | |
| "surfaceVAxis": v_axis.tolist(), | |
| "surfaceWidthMeters": float(max(uv_max[0] - uv_min[0], 0.05)), | |
| "surfaceHeightMeters": float(max(uv_max[1] - uv_min[1], 0.05)), | |
| "metersPerUnit": 1.0, | |
| "geometryConfidence": confidence, | |
| "geometryProvider": provider, | |
| "cameraIntrinsics": pixel_intrinsics.flatten().tolist() if pixel_intrinsics is not None else None, | |
| "camera": { | |
| "focalLength": ( | |
| float(pixel_intrinsics[0, 0]) | |
| if pixel_intrinsics is not None | |
| else float(max(h, w) * 0.95) | |
| ), | |
| "confidence": confidence, | |
| }, | |
| "planeNormal": normal.tolist(), | |
| "planeOrigin": centroid.tolist(), | |
| "fitResidualMeters": residual, | |
| "fitInlierRatio": inlier_ratio, | |
| "normalConsistency": normal_consistency, | |
| "planeFit": PlaneFitMode.RANSAC, | |
| } | |
| def estimate_metric_floor_transform( | |
| mask: np.ndarray, | |
| depth: np.ndarray | None, | |
| provider: str = GeometryProvider.DEPTH_ANYTHING, | |
| intrinsics: np.ndarray | None = None, | |
| surface_kind: str = "floor", | |
| ): | |
| from config.models import DEPTH_MODEL_NAME | |
| from config.runtime import ENABLE_PLANE_FIT | |
| if depth is None or not ENABLE_PLANE_FIT: | |
| return None | |
| h, w = mask.shape[:2] | |
| 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) | |
| result = fit_metric_floor_transform( | |
| mask, | |
| points, | |
| intrinsics=pixel_intrinsics, | |
| provider=provider, | |
| surface_kind=surface_kind, | |
| ) | |
| if result is not None: | |
| result["depthScale"] = depth_scale | |
| return result | |