File size: 10,323 Bytes
2a86f7e
 
 
26c3d3a
 
 
2a86f7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26c3d3a
2a86f7e
 
 
 
 
 
 
 
 
 
 
 
 
 
26c3d3a
 
 
2a86f7e
 
 
 
 
 
 
 
 
 
 
26c3d3a
 
 
 
 
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
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
"""Figures for the GREENBOT calibration v2 web page.

Usage: make_figures.py <calib_dir> <release_dir> <cache.pkl> <fig_dir> <timing.npz> [...]

The v1/v2 overlay uses the sample OVERLAY_SAMPLE, read from the cache file of that sequence
next to <cache.pkl> (a corridor view with little sky glare).
"""
import json
import pickle
import sys
from pathlib import Path

import cv2
import numpy as np
import yaml
from scipy.spatial.transform import Rotation

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
from matplotlib.colors import LinearSegmentedColormap  # noqa: E402

sys.path.insert(0, str(Path(__file__).parent))
from common import D_L, IMG_H, IMG_W, K_L, R_OPT, VLP16_ELEV_DEG, Stereo, inv, se3, xform  # noqa: E402

CAL = Path(sys.argv[1])
REL = Path(sys.argv[2])
CACHE = pickle.load(open(sys.argv[3], "rb"))
FIG = Path(sys.argv[4])
TIMINGS = sys.argv[5:]
FIG.mkdir(parents=True, exist_ok=True)
L = json.load(open(CAL / "lidars.json"))
C = json.load(open(CAL / "camera.json"))
VEL = pickle.load(open(CAL / "velocities.pkl", "rb"))
TIM = yaml.safe_load(open(REL / "greenbot_timing_v2.yaml"))

BLUE = "#257de0"    # v2
ORANGE = "#f47230"  # v1
AQUA = "#00b894"
INK = "#191919"
INK2 = "#666666"
GRID = "#e6e6e6"
plt.rcParams.update({
    "font.size": 9, "axes.edgecolor": "#bbbbbb", "axes.labelcolor": INK2, "xtick.color": INK2, "ytick.color": INK2,
    "axes.spines.top": False, "axes.spines.right": False, "axes.titlesize": 10, "axes.titlecolor": INK,
    "axes.titlelocation": "left", "figure.facecolor": "white", "axes.facecolor": "white", "lines.linewidth": 2,
})
DIVERGING = LinearSegmentedColormap.from_list("bo", [BLUE, "#efefef", ORANGE])


def save(fig, name):
    fig.savefig(FIG / name, dpi=160, bbox_inches="tight")
    plt.close(fig)
    print("wrote", name)


T_o_c_v2 = np.array(C["T_os_sensor_left_optical"])
p_v1 = np.array(C["p_v1"])
T_o_c_v1 = se3(Rotation.from_rotvec(p_v1[:3]).as_matrix() @ R_OPT, p_v1[3:6])
OVERLAY_SAMPLE = ("2022-11-02", 44)


def project(T_o_c, P):
    X = xform(inv(T_o_c), P)
    ok = X[:, 2] > 0.3
    n = X[:, :2] / np.maximum(X[:, 2:3], 1e-6)
    ok &= np.hypot(n[:, 0], n[:, 1]) < 1.0
    uv = np.full((len(P), 2), -1.0)
    if ok.any():
        uv[ok] = cv2.projectPoints(X[ok].reshape(-1, 1, 3), np.zeros(3), np.zeros(3), K_L, D_L)[0].reshape(-1, 2)
    ok &= (uv[:, 0] >= 0) & (uv[:, 0] < IMG_W - 1) & (uv[:, 1] >= 0) & (uv[:, 1] < IMG_H - 1)
    return uv, X[:, 2], ok


def deskewed_points(seq, i, s):
    tau = C["camera_tau"][seq]
    clk = L["clock"][f"{seq}|ouster_points"]
    o = s["ouster"][1]
    t_env = o["hdr"] + clk["offset"] + clk["slope"] * (o["hdr"] - clk["h0"])
    t_pts = t_env - L["ouster_latency_nominal"] + o["t"].astype(float) * 1e-9
    v, w = (np.array(a) for a in VEL[f"{seq}|{i}"])
    dt = (s["cam_hdr"] + tau - t_pts)[:, None]
    R = Rotation.from_rotvec(w[None, :] * dt).as_matrix()
    return np.einsum("nji,nj->ni", R, o["P"].astype(float) - v[None, :] * dt)


# ---------------- 1. overlay v1 vs v2 ----------------
st = Stereo()
seq_ex, i_ex = OVERLAY_SAMPLE
ov_cache = CACHE if CACHE["bag"] == seq_ex else pickle.load(open(Path(sys.argv[3]).with_name(f"cache_{seq_ex}.pkl"), "rb"))
s_ex = ov_cache["samples"][i_ex]
del ov_cache
P = deskewed_points(seq_ex, i_ex, s_ex)
P = P[(P[:, 0] > 0.3) & (np.linalg.norm(P, axis=1) < 12)]
Z = st.depth_left(s_ex["L"], s_ex["R"])
fig, axs = plt.subplots(1, 2, figsize=(12, 4.6))
for ax, (name, T) in zip(axs, (("v1 calibration (published 2024)", T_o_c_v1), ("v2 calibration", T_o_c_v2))):
    uv, z, ok = project(T, P)
    ui = uv[ok].astype(int)
    zs = Z[ui[:, 1], ui[:, 0]]
    v = zs > 0
    ax.imshow(s_ex["L"], cmap="gray", vmin=0, vmax=255)
    sc = ax.scatter(ui[v, 0], ui[v, 1], c=np.log(z[ok][v] / zs[v]), cmap=DIVERGING, vmin=-0.4, vmax=0.4, s=3, linewidths=0)
    ax.set_title(name)
    ax.axis("off")
cb = fig.colorbar(sc, ax=axs, fraction=0.025, pad=0.01)
cb.set_label("ln(LiDAR depth / stereo depth)", color=INK2)
cb.outline.set_visible(False)
fig.suptitle("Ouster points projected into the left Bumblebee image (gray = LiDAR and stereo agree)", x=0.02, ha="left", color=INK)
save(fig, "fig_overlay_v1_v2.png")

# ---------------- 2. cost vs camera height ----------------
prof = np.array(C["height_profile"])
z_v2 = T_o_c_v2[2, 3] * 100
z_v1 = T_o_c_v1[2, 3] * 100
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4), sharex=True)
for ax, col, lab in ((axs[0], 1, "LiDAR-stereo depth cost (lower is better)"), (axs[1], 2, "mutual information, Ouster ambient vs image (higher is better)")):
    ax.plot(prof[:, 0] * 100, prof[:, col], color=INK2, marker="o", ms=4, lw=1.5)
    for zz, c, t in ((z_v1, ORANGE, "v1"), (z_v2, BLUE, "v2")):
        ax.axvline(zz, color=c, lw=2)
        ax.text(zz + 0.6, ax.get_ylim()[1], t, color=INK, va="top", fontsize=9, fontweight="bold")
    ax.set_title(lab, fontsize=9)
    ax.grid(color=GRID, lw=0.6)
    ax.set_xlabel("camera height relative to the Ouster os_sensor frame (cm)")
fig.suptitle("Camera height: other five pose parameters re-optimized at every step", x=0.02, ha="left", color=INK)
save(fig, "fig_camera_height_profile.png")

# ---------------- 3. depth ratio by image row ----------------
fig, ax = plt.subplots(figsize=(4.2, 4.2))
for name, c in (("v1", ORANGE), ("v2", BLUE)):
    rr = np.array(C["rows"][name])
    ax.plot(rr[:, 1], rr[:, 0], color=c, marker="o", ms=4)
    ax.text(rr[-1, 1], rr[-1, 0] + 25, name, color=INK, ha="center", fontweight="bold")
ax.axvline(1.0, color="#999999", lw=1)
ax.set_ylim(IMG_H, 0)
ax.set_xlabel("median LiDAR depth / stereo depth")
ax.set_ylabel("image row (px, 0 = top)")
ax.grid(axis="x", color=GRID, lw=0.6)
ax.set_title("Depth agreement by image row, all samples")
save(fig, "fig_depth_ratio_rows.png")

# ---------------- 4. Velodyne elevation histograms ----------------
Pl = np.concatenate([s["velo"][1]["P"].astype(float) for s in CACHE["samples"][::5]])
VO = np.array(L["velodyne_origin_in_legacy_base_link"])
fig, axs = plt.subplots(1, 2, figsize=(10, 3), sharey=True)
for ax, (name, o, c) in zip(axs, (("v1: elevation seen from the base_link origin", np.zeros(3), ORANGE),
                                   ("v2: elevation seen from the velodyne frame origin", VO, BLUE))):
    Q = Pl - o
    Q = Q[np.linalg.norm(Q, axis=1) > 2]
    el = np.degrees(np.arctan2(Q[:, 2], np.hypot(Q[:, 0], Q[:, 1])))
    ax.hist(el, bins=np.arange(-17, 17, 0.1), color=c)
    for e in VLP16_ELEV_DEG:
        ax.axvline(e, color="#cccccc", lw=0.6, zorder=0)
    ax.set_title(name, fontsize=9)
    ax.set_xlabel("beam elevation (deg); gray lines: the 16 VLP-16 beams")
axs[0].set_ylabel("points")
fig.suptitle(f"The v1 Velodyne cloud is not centered on the sensor: its origin is at ({VO[0]:.3f}, {VO[1]:.3f}, {VO[2]:.3f}) m of base_link",
             x=0.02, y=1.06, ha="left", color=INK)
save(fig, "fig_velodyne_origin.png")

# ---------------- 5. Ouster clock drift ----------------
fig, ax = plt.subplots(figsize=(8, 3.4))
cols = [BLUE, ORANGE, AQUA]
for k, npz in enumerate(TIMINGS):
    name = Path(npz).stem.replace("timing_", "")
    t = np.load(npz)
    b, h = t["ouster_points_bag"], t["ouster_points_hdr"]
    d = (b - h)
    d = (d - np.min(d[:200])) * 1e3
    x = (b - b[0]) / 60
    ppm = TIM["sequences"][name]["ouster_clock_drift_ppm"]
    mode = TIM["sequences"][name]["ouster_stamp_mode"].replace("_", " ")
    ax.plot(x[::10], d[::10], ".", ms=1.5, color=cols[k % 3], alpha=0.5,
            label=f"{name}: {mode}" + (f", drift {ppm:+.0f} ppm" if mode == "sensor clock" else ""))
ax.set_xlabel("time since start of the sequence (min)")
ax.set_ylabel("arrival time - Ouster stamp (ms, shifted)")
ax.grid(color=GRID, lw=0.6)
ax.set_title("Ouster stamps vs arrival time: the sensor clock (2022-10-14) drifts; PC-clock sessions do not")
ax.legend(loc="upper left", markerscale=6, frameon=False, fontsize=8, labelcolor=INK)
save(fig, "fig_ouster_clock_drift.png")

# ---------------- 6. sensor layout ----------------
tf = yaml.safe_load(open(REL / "greenbot_tf_static_v2.yaml"))["transforms"]
G = {"base_link": np.eye(4)}
for e in tf:
    T = se3(Rotation.from_quat(e["rotation_xyzw"]).as_matrix(), e["translation"])
    G[e["child"]] = G[e["parent"]] @ T
h_ground = L["velodyne_height_above_ground"]
SHOW = {"velodyne": ("velodyne = base_link", (6, 6)), "os_sensor": ("os_sensor", (8, -12)), "os_lidar": ("os_lidar", (-46, 2)),
        "stereo_left_optical_frame": ("left camera", (8, 4)), "stereo_right_optical_frame": ("right camera", (8, -12))}
V1 = {"Ouster (v1)": (np.array([0.3007, 0, -0.1114]), (8, 4)), "camera, stereo center (v1)": (np.array([0.3984, 0, -0.3052]), (8, -4))}
fig, axs = plt.subplots(2, 1, figsize=(7.5, 6.4), sharex=True, gridspec_kw=dict(height_ratios=[1.25, 1]))
for ax, (i, j, yl, title) in zip(axs, ((0, 2, "z up (m)", "Side view"), (0, 1, "y left (m)", "Top view"))):
    for name, (lab, off) in SHOW.items():
        if (i, j) == (0, 1) and name in ("os_lidar", "stereo_right_optical_frame"):
            lab = {"os_lidar": None, "stereo_right_optical_frame": "right camera"}[name]
        if (i, j) == (0, 2) and name == "stereo_right_optical_frame":
            continue
        T = G[name]
        p = T[:3, 3]
        for a_, c in ((0, "#d62728"), (1, "#2ca02c"), (2, "#1f77b4")):
            d = T[:3, a_] * 0.05
            ax.plot([p[i], p[i] + d[i]], [p[j], p[j] + d[j]], color=c, lw=1.3)
        ax.plot(p[i], p[j], "o", color=BLUE, ms=6, zorder=3)
        if lab:
            ax.annotate(lab, (p[i], p[j]), xytext=off, textcoords="offset points", fontsize=8, color=INK)
    for lab, (p, off) in V1.items():
        ax.plot(p[i], p[j], "o", mfc="white", mec=ORANGE, mew=2, ms=6, zorder=3)
        ax.annotate(lab, (p[i], p[j]), xytext=off, textcoords="offset points", fontsize=8, color=INK2)
    ax.set_ylabel(yl)
    ax.set_aspect("equal")
    ax.grid(color=GRID, lw=0.6)
    ax.set_title(title, fontsize=9)
axs[0].set_ylim(-0.36, 0.09)
axs[0].annotate(f"floor: {h_ground:.2f} m below the Velodyne", xy=(0.02, -0.355), fontsize=8, color=INK2)
axs[1].set_ylim(-0.08, 0.11)
axs[1].set_xlim(-0.05, 0.62)
axs[1].set_xlabel("x forward (m)")
fig.suptitle("Sensor frames in base_link (filled: v2, hollow: v1). Axes: x red, y green, z blue", x=0.02, ha="left", color=INK)
save(fig, "fig_sensor_layout.png")