File size: 7,003 Bytes
2a86f7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared helpers for the GREENBOT calibration v2 tools."""
import cv2
import numpy as np
from scipy.spatial import cKDTree
from scipy.spatial.transform import Rotation

# ---------------- published intrinsics (calib.ini, Feb 2024) ----------------
IMG_W = 1024
IMG_H = 768
K_L = np.array([[552.209216, 0, 535.193976], [0, 553.665955, 383.237170], [0, 0, 1]])
D_L = np.array([-3.786586e-01, 2.120561e-01, 1.170313e-04, -1.623899e-03, -7.851788e-02])
K_R = np.array([[545.423587, 0, 543.856891], [0, 546.055991, 389.533267], [0, 0, 1]])
D_R = np.array([-3.628856e-01, 1.472389e-01, -1.584509e-03, -6.308057e-04, -2.830265e-02])
# Pose of the right camera in the left camera frame: X_left = R_LR X_right + T_LR
R_LR = np.array(
    [
        [9.9979404139789e-01, -1.8417999557335e-03, -2.0210951441971e-02],
        [1.9119117124848e-03, 9.9999222024352e-01, 3.4502240551596e-03],
        [2.0204439583179e-02, -3.4881550066186e-03, 9.9978978460263e-01],
    ]
)
T_LR = np.array([1.184059e-01, -5.219039e-04, 2.763806e-03])

# Legacy Velodyne cloud: published in "base_link" with the beam origin here (estimated from the data).
VELO_ORIGIN_IN_LEGACY_BASE_LINK = np.array([0.10, 0.50, 0.0])
VLP16_ELEV_DEG = np.arange(-15, 16, 2)
# Ouster /tf_static
OS_SENSOR_TO_LIDAR_Z = 0.03618
# Nominal optical axes (x right, y down, z forward) in a LiDAR-like frame (x fwd, y left, z up)
R_OPT = np.array([[0, 0, 1.0], [-1, 0, 0], [0, -1, 0]])

TOP_LEFT = "/stereo_camera/left/image_raw"
TOP_RIGHT = "/stereo_camera/right/image_raw"
TOP_OUSTER = "/ouster/points"
TOP_VELO = "/Velodyne1_SCAN"


def stamp(m):
    return m.header.stamp.sec + m.header.stamp.nanosec * 1e-9


def cloud_xyz(m, extra=()):
    off = {f.name: f.offset for f in m.fields}
    tmap = {1: "i1", 2: "u1", 3: "<i2", 4: "<u2", 5: "<i4", 6: "<u4", 7: "<f4", 8: "<f8"}
    dtp = {f.name: f.datatype for f in m.fields}
    names = ["x", "y", "z"] + [e for e in extra if e in off]
    dt = np.dtype(
        {
            "names": names,
            "formats": ["<f4"] * 3 + [tmap[dtp[e]] for e in names[3:]],
            "offsets": [off[n] for n in names],
            "itemsize": m.point_step,
        }
    )
    p = np.frombuffer(m.data, dtype=dt, count=m.width * m.height)
    P = np.stack([p["x"], p["y"], p["z"]], 1).astype(np.float64)
    ok = np.isfinite(P).all(1) & (np.linalg.norm(P, axis=1) > 0.05)
    return (P[ok],) + tuple(p[e][ok] for e in names[3:])


def bayer_to_gray(m):
    a = np.frombuffer(m.data, np.uint8).reshape(m.height, m.width)
    return cv2.cvtColor(cv2.cvtColor(a, cv2.COLOR_BayerGR2BGR), cv2.COLOR_BGR2GRAY)


def se3(R, t):
    T = np.eye(4)
    T[:3, :3] = R
    T[:3, 3] = t
    return T


def inv(T):
    R = T[:3, :3]
    return se3(R.T, -R.T @ T[:3, 3])


def xform(T, P):
    return P @ T[:3, :3].T + T[:3, 3]


def pose_str(T):
    rpy = Rotation.from_matrix(T[:3, :3]).as_euler("xyz", degrees=True)
    return f"t=({T[0, 3]:+.4f}, {T[1, 3]:+.4f}, {T[2, 3]:+.4f}) m  rpy(xyz)=({rpy[0]:+.2f}, {rpy[1]:+.2f}, {rpy[2]:+.2f}) deg"


def normals(P, k=12):
    tree = cKDTree(P)
    _, nn = tree.query(P, k=k)
    C = P[nn] - P[nn].mean(1, keepdims=True)
    w, v = np.linalg.eigh(np.einsum("nki,nkj->nij", C, C))
    planarity = (w[:, 1] - w[:, 0]) / np.maximum(w[:, 2], 1e-12)
    return tree, v[:, :, 0], planarity


def icp_multi(pairs, T0, schedule=((0.5, 15), (0.2, 15), (0.08, 20), (0.05, 20))):
    """Point-to-plane ICP of several (source, target) pairs sharing one rigid transform.

    pairs: list of (src Nx3, (tree, normals, planarity, tgt Mx3)); returns T (src -> tgt) and stats.
    """
    T = T0.copy()
    for dmax, iters in schedule:
        for _ in range(iters):
            A_all = []
            b_all = []
            for src, (tree, nrm, pl, tgt) in pairs:
                S = xform(T, src)
                d, j = tree.query(S)
                m = (d < dmax) & (pl[j] > 0.3)
                p = S[m]
                n = nrm[j[m]]
                A_all.append(np.hstack([np.cross(p, n), n]))
                b_all.append(np.sum((tgt[j[m]] - p) * n, 1))
            A = np.concatenate(A_all)
            b = np.concatenate(b_all)
            w = 1.0 / np.maximum(1.0, np.abs(b) / 0.02)  # Huber-like weights
            x = np.linalg.lstsq(A * w[:, None], b * w, rcond=None)[0]
            T = se3(Rotation.from_rotvec(x[:3]).as_matrix(), x[3:]) @ T
    res = []
    for src, (tree, nrm, pl, tgt) in pairs:
        S = xform(T, src)
        d, j = tree.query(S)
        m = (d < 0.05) & (pl[j] > 0.3)
        res.append(np.abs(np.sum((tgt[j[m]] - S[m]) * nrm[j[m]], 1)))
    res = np.concatenate(res)
    return T, float(np.median(res)), int(len(res))


class Stereo:
    def __init__(self):
        Rcv = R_LR.T
        Tcv = (-R_LR.T @ T_LR).reshape(3, 1)
        self.R1, self.R2, self.P1, self.P2, self.Q, _, _ = cv2.stereoRectify(
            K_L, D_L, K_R, D_R, (IMG_W, IMG_H), Rcv, Tcv, flags=cv2.CALIB_ZERO_DISPARITY, alpha=0
        )
        self.m1 = cv2.initUndistortRectifyMap(K_L, D_L, self.R1, self.P1, (IMG_W, IMG_H), cv2.CV_32FC1)
        self.m2 = cv2.initUndistortRectifyMap(K_R, D_R, self.R2, self.P2, (IMG_W, IMG_H), cv2.CV_32FC1)
        self.f = self.P1[0, 0]
        self.B = -self.P2[0, 3] / self.P2[0, 0]
        # for every original left pixel, its location in the rectified image
        uu, vv = np.meshgrid(np.arange(IMG_W, dtype=np.float32), np.arange(IMG_H, dtype=np.float32))
        rp = cv2.undistortPoints(np.stack([uu.ravel(), vv.ravel()], 1).reshape(-1, 1, 2), K_L, D_L, R=self.R1, P=self.P1)
        rp = rp.reshape(IMG_H, IMG_W, 2)
        self.rx = rp[..., 0].astype(np.float32)
        self.ry = rp[..., 1].astype(np.float32)

    def depth_left(self, L, R):
        """Depth (z along the original left optical axis, meters) on the original left pixel grid; 0 = invalid."""
        Lr = cv2.remap(L, *self.m1, cv2.INTER_LINEAR)
        Rr = cv2.remap(R, *self.m2, cv2.INTER_LINEAR)

        def sg():
            return cv2.StereoSGBM_create(0, 128, 5, P1=200, P2=800, disp12MaxDiff=1, uniquenessRatio=10,
                                         speckleWindowSize=100, speckleRange=2, mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY)

        dL = sg().compute(Lr, Rr).astype(np.float32) / 16
        dR = (sg().compute(Rr[:, ::-1].copy(), Lr[:, ::-1].copy()).astype(np.float32) / 16)[:, ::-1]
        uu = np.arange(IMG_W, dtype=np.float32)[None, :].repeat(IMG_H, 0)
        vv = np.arange(IMG_H, dtype=np.float32)[:, None].repeat(IMG_W, 1)
        xr = uu - dL
        ok = (dL > 1.0) & (xr >= 0)
        ok &= np.abs(dL - cv2.remap(dR, xr, vv, cv2.INTER_NEAREST)) < 1.0
        X = cv2.reprojectImageTo3D(np.where(ok, dL, 0).astype(np.float32), self.Q)
        X[~ok] = 0
        Xo = X.reshape(-1, 3) @ self.R1  # rectified -> original left frame
        Zrect = Xo[:, 2].reshape(IMG_H, IMG_W).astype(np.float32)
        Zrect[~ok] = 0
        Z = cv2.remap(Zrect, self.rx, self.ry, cv2.INTER_NEAREST)
        Z[(Z < 0.3) | (Z > 15)] = 0
        return Z