File size: 9,844 Bytes
790d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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, vertical_ref: np.ndarray | None = None):
    """Build (u, v) axes for a plane.

    For a non-floor surface v is world-up projected onto the plane, so tiles run
    up the wall. `vertical_ref` is which direction "up" actually is.

    It defaults to +Y, but geometry providers return points in *camera*
    coordinates, so +Y is camera-up rather than gravity-up. Any camera tilt then
    rotates every wall's tile grid by that same angle. Callers that know the
    floor plane should pass its normal: a floor is horizontal by definition, so
    its normal is true vertical in whatever frame the points are expressed in.
    """
    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:
        camera_up = np.array([0.0, 1.0, 0.0], dtype=np.float32)
        if vertical_ref is None:
            up = camera_up
        else:
            up = np.asarray(vertical_ref, dtype=np.float32).copy()
            length = float(np.linalg.norm(up))
            up = camera_up if length < 1e-6 else up / length
            # A plane normal has arbitrary sign; keep the axis pointing the same
            # way as before so tile orientation does not flip.
            if float(up @ camera_up) < 0:
                up = -up
        v_axis = up - normal * float(up @ normal)
        if float(np.linalg.norm(v_axis)) < 1e-5:
            up = np.array([0.0, 0.0, 1.0], dtype=np.float32)
            v_axis = up - normal * float(up @ 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