File size: 6,865 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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