from __future__ import annotations import numpy as np from config.surface import SURFACE_MIN_PLANE_PIXELS from services.geometry.plane_fitting import refine_plane _HYPOTHESIS_BATCH_SIZE = 32 def _candidate_hypotheses( candidate_points: np.ndarray, *, iterations: int, rng: np.random.Generator, ) -> tuple[np.ndarray, np.ndarray]: """Generate the same deterministic RANSAC hypotheses without scoring each one separately.""" origins = [] normals = [] for _ in range(iterations): local = rng.choice(len(candidate_points), size=3, replace=False) p0, p1, p2 = candidate_points[local] normal = np.cross(p1 - p0, p2 - p0).astype(np.float32) length = float(np.linalg.norm(normal)) if length < 1e-6: continue origins.append(p0) normals.append(normal / length) if not origins: return np.empty((0, 3), dtype=np.float32), np.empty((0, 3), dtype=np.float32) return np.asarray(origins, dtype=np.float32), np.asarray(normals, dtype=np.float32) def _best_surface_hypothesis( candidate_points: np.ndarray, origins: np.ndarray, normals: np.ndarray, distance_threshold: float, *, candidate_normals: np.ndarray | None = None, normal_cos: float | None = None, ) -> tuple[np.ndarray, np.ndarray] | None: """Score RANSAC hypotheses in bounded batches to avoid hundreds of tiny NumPy calls.""" best_count = 0 best_index = -1 for start in range(0, len(origins), _HYPOTHESIS_BATCH_SIZE): stop = min(start + _HYPOTHESIS_BATCH_SIZE, len(origins)) batch_normals = normals[start:stop] batch_origins = origins[start:stop] offsets = np.sum(batch_origins * batch_normals, axis=1) distances = np.abs(candidate_points @ batch_normals.T - offsets[None, :]) accepted = distances <= distance_threshold if candidate_normals is not None and normal_cos is not None: alignments = np.abs(candidate_normals @ batch_normals.T) accepted &= alignments >= normal_cos counts = accepted.sum(axis=0) local_index = int(np.argmax(counts)) local_count = int(counts[local_index]) if local_count > best_count: best_count = local_count best_index = start + local_index if best_index < 0: return None return origins[best_index], normals[best_index] def ransac_plane_fit(points: np.ndarray): if len(points) < 1000: return None rng = np.random.default_rng(17) span = np.percentile(points, 95, axis=0) - np.percentile(points, 5, axis=0) threshold = max(0.025, float(np.linalg.norm(span)) * 0.012) best_keep = None best_count = 0 best_normal = None best_centroid = None iterations = min(160, max(48, len(points) // 120)) for _ in range(iterations): sample_idx = rng.choice(len(points), size=3, replace=False) p0, p1, p2 = points[sample_idx] normal = np.cross(p1 - p0, p2 - p0).astype(np.float32) length = float(np.linalg.norm(normal)) if length < 1e-6: continue normal /= length distances = np.abs((points - p0) @ normal) keep = distances <= threshold count = int(keep.sum()) if count > best_count: best_keep = keep best_count = count best_normal = normal best_centroid = p0.astype(np.float32) if best_keep is None or best_count < 1000: return None return best_centroid, best_normal, best_keep def ransac_surface_plane( points: np.ndarray, normals: np.ndarray, candidate_indices: np.ndarray, remaining: np.ndarray, distance_threshold: float, normal_cos: float, ): if len(candidate_indices) < 3: return None rng = np.random.default_rng(41) candidate_points = points[candidate_indices] candidate_normals = normals[candidate_indices] relaxed_cos = max(0.0, normal_cos - 0.15) origins, hypothesis_normals = _candidate_hypotheses( candidate_points, iterations=220, rng=rng, ) best = _best_surface_hypothesis( candidate_points, origins, hypothesis_normals, distance_threshold, candidate_normals=candidate_normals, normal_cos=relaxed_cos, ) if best is None: return None best_origin, best_normal = best distances = np.abs((points - best_origin) @ best_normal) align = np.abs(normals @ best_normal) inliers = remaining & (distances <= distance_threshold) & (align >= relaxed_cos) if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: return None refine_idx = np.flatnonzero(inliers) if len(refine_idx) > 50000: refine_idx = refine_idx[:: max(1, len(refine_idx) // 50000)] origin, normal = refine_plane(points[refine_idx], normals[refine_idx]) distances = np.abs((points - origin) @ normal) align = np.abs(normals @ normal) inliers = remaining & (distances <= distance_threshold) & (align >= normal_cos) if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: return None final_idx = np.flatnonzero(inliers) if len(final_idx) > 50000: final_idx = final_idx[:: max(1, len(final_idx) // 50000)] origin, normal = refine_plane(points[final_idx], normals[final_idx]) return origin, normal, inliers def ransac_surface_plane_by_distance( points: np.ndarray, candidate_indices: np.ndarray, remaining: np.ndarray, distance_threshold: float, ): if len(candidate_indices) < 3: return None rng = np.random.default_rng(53) candidate_points = points[candidate_indices] origins, hypothesis_normals = _candidate_hypotheses( candidate_points, iterations=260, rng=rng, ) best = _best_surface_hypothesis( candidate_points, origins, hypothesis_normals, distance_threshold, ) if best is None: return None best_origin, best_normal = best distances = np.abs((points - best_origin) @ best_normal) inliers = remaining & (distances <= distance_threshold) if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: return None refine_idx = np.flatnonzero(inliers) if len(refine_idx) > 50000: refine_idx = refine_idx[:: max(1, len(refine_idx) // 50000)] origin, normal = refine_plane(points[refine_idx], None) distances = np.abs((points - origin) @ normal) inliers = remaining & (distances <= distance_threshold * 1.25) if int(inliers.sum()) < SURFACE_MIN_PLANE_PIXELS: return None final_idx = np.flatnonzero(inliers) if len(final_idx) > 50000: final_idx = final_idx[:: max(1, len(final_idx) // 50000)] origin, normal = refine_plane(points[final_idx], None) return origin, normal, inliers