File size: 7,549 Bytes
532466c
 
 
 
 
 
3e1a674
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
532466c
 
 
 
8e53f1d
532466c
 
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
 
8e53f1d
 
 
532466c
 
 
 
 
 
18196ae
 
 
 
 
 
 
 
 
 
 
 
 
532466c
 
 
 
 
 
 
 
 
 
 
18196ae
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e53f1d
 
532466c
 
 
3e1a674
532466c
3e1a674
 
532466c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
202
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