File size: 4,308 Bytes
18196ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Analytic UV mapping for a fitted plane.

Functions
---------
upright_plane_basis        - in-plane (u, v) axes with v aligned to a given "up" direction
ray_plane_uv               - UV of pixels by intersecting camera rays with a plane
plane_to_image_transform   - exact 3x3 pixel -> plane-UV homography for a plane
"""

from __future__ import annotations

import numpy as np

# Hits farther than this (metres) are near-horizon rays and are rejected.
MAX_RAY_DISTANCE_METERS = 100.0


def upright_plane_basis(normal: np.ndarray, up: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Return unit (u, v) axes spanning the plane, with v following `up`.

    For walls `up` is the floor normal, so textures stay upright even when the
    camera is tilted. Falls back to the camera's +Y axis when `up` is (nearly)
    parallel to the plane normal.
    """
    normal = np.asarray(normal, dtype=np.float32)
    normal = normal / max(float(np.linalg.norm(normal)), 1e-6)
    for reference in (np.asarray(up, dtype=np.float32), np.array([0.0, 1.0, 0.0], dtype=np.float32)):
        v_axis = reference - normal * float(reference @ normal)
        length = float(np.linalg.norm(v_axis))
        if length > 1e-4:
            v_axis = v_axis / length
            u_axis = np.cross(v_axis, normal)
            u_axis = u_axis / max(float(np.linalg.norm(u_axis)), 1e-6)
            return u_axis.astype(np.float32), v_axis.astype(np.float32)
    raise ValueError("Cannot build a plane basis: normal is degenerate.")


def ray_plane_uv(
    flat_indices: np.ndarray,
    image_width: int,
    intrinsics: np.ndarray,
    origin: np.ndarray,
    normal: np.ndarray,
    u_axis: np.ndarray,
    v_axis: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
    """UV (metres, relative to `origin`) where each pixel's camera ray meets the plane.

    Uses the pinhole convention of services.geometry.camera.backproject_depth,
    so results agree with depth-derived 3D points. Returns (uv, hit): uv is
    float32 (N, 2) with NaN where the ray misses the plane in front of the
    camera, and hit is the matching boolean mask.
    """
    flat = np.asarray(flat_indices, dtype=np.int64)
    xs = (flat % image_width).astype(np.float32)
    ys = (flat // image_width).astype(np.float32)
    fx = max(float(intrinsics[0, 0]), 1e-6)
    fy = max(float(intrinsics[1, 1]), 1e-6)
    rays = np.column_stack((
        (xs - float(intrinsics[0, 2])) / fx,
        (ys - float(intrinsics[1, 2])) / fy,
        np.ones_like(xs),
    ))

    normal = np.asarray(normal, dtype=np.float32)
    origin = np.asarray(origin, dtype=np.float32)
    denom = rays @ normal
    with np.errstate(divide="ignore", invalid="ignore"):
        distance = np.where(np.abs(denom) > 1e-6, float(origin @ normal) / denom, np.nan)
    hit = np.isfinite(distance) & (distance > 0) & (distance < MAX_RAY_DISTANCE_METERS)

    uv = np.full((len(flat), 2), np.nan, dtype=np.float32)
    if hit.any():
        delta = rays[hit] * distance[hit, None] - origin
        uv[hit, 0] = delta @ np.asarray(u_axis, dtype=np.float32)
        uv[hit, 1] = delta @ np.asarray(v_axis, dtype=np.float32)
    return uv, hit


def plane_to_image_transform(
    intrinsics: np.ndarray,
    origin: np.ndarray,
    normal: np.ndarray,
    u_axis: np.ndarray,
    v_axis: np.ndarray,
) -> np.ndarray:
    """3x3 homography H with (u, v, w) = H @ (x, y, 1) giving the same UV as ray_plane_uv.

    Intersecting ray r with the plane gives u = [(n.o)(u.r) - (o.u)(n.r)] / (n.r),
    and likewise for v, which is projective in r and so in the pixel. A flat
    wall therefore needs 9 numbers instead of a per-pixel UV array. Same
    row-major, integer-pixel convention as fit_metric_floor_transform.
    """
    normal = np.asarray(normal, dtype=np.float64)
    origin = np.asarray(origin, dtype=np.float64)
    u_axis = np.asarray(u_axis, dtype=np.float64)
    v_axis = np.asarray(v_axis, dtype=np.float64)
    offset = float(normal @ origin)
    ray_to_uv = np.vstack((
        offset * u_axis - float(origin @ u_axis) * normal,
        offset * v_axis - float(origin @ v_axis) * normal,
        normal,
    ))
    transform = ray_to_uv @ np.linalg.inv(np.asarray(intrinsics, dtype=np.float64))
    return transform / transform[2, 2] if abs(transform[2, 2]) > 1e-12 else transform