greenbot-dataset / tools /calib_camera.py
jlblancoc's picture
Calibration v2, figures, tools and dataset card
2a86f7e verified
Raw History Blame Contribute Delete
8.56 kB
"""Camera part of GREENBOT calibration v2: pose of the left optical frame in os_sensor, and camera time offset.
Usage: calib_camera.py <out_dir> <cache.pkl> [...] (needs <out_dir>/lidars.json and velocities.pkl)
"""
import json
import pickle
import sys
from pathlib import Path
import cv2
import numpy as np
from scipy.optimize import minimize
from scipy.spatial.transform import Rotation
sys.path.insert(0, str(Path(__file__).parent))
from common import D_L, IMG_H, IMG_W, K_L, R_OPT, Stereo, inv, pose_str, se3, xform # noqa: E402
OUT = Path(sys.argv[1])
LID = json.load(open(OUT / "lidars.json"))
VEL = pickle.load(open(OUT / "velocities.pkl", "rb"))
rng = np.random.default_rng(0)
log = []
def say(s=""):
print(s, flush=True)
log.append(s)
st = Stereo()
NPTS = 2500
S = []
for pkl in sys.argv[2:]:
c = pickle.load(open(pkl, "rb"))
bag = c["bag"]
clk = LID["clock"][f"{bag}|ouster_points"]
for i, s in enumerate(c["samples"]):
o = s["ouster"][1]
P = o["P"].astype(float)
m = (P[:, 0] > 0.3) & (np.linalg.norm(P, axis=1) < 15)
idx = np.flatnonzero(m)
idx = rng.choice(idx, min(NPTS, len(idx)), replace=False)
amb = o["amb"].astype(float)
abin = np.clip((np.argsort(np.argsort(amb)) / len(amb) * 32).astype(int), 0, 31)
t_env = o["hdr"] + clk["offset"] + clk["slope"] * (o["hdr"] - clk["h0"])
v, w = VEL[f"{bag}|{i}"]
S.append(dict(bag=bag, still=s["still"], P=P[idx], abin=abin[idx],
t_pts=t_env - LID["ouster_latency_nominal"] + o["t"][idx].astype(float) * 1e-9,
t_cam=s["cam_hdr"], v=np.array(v), w=np.array(w), speed=float(np.linalg.norm(v)),
Z=st.depth_left(s["L"], s["R"]), Lb=cv2.GaussianBlur(s["L"], (5, 5), 1.0), L=s["L"]))
say(f"# {bag}: {len(c['samples'])} samples")
say(f"# stereo: f {st.f:.1f} px, baseline {st.B * 100:.2f} cm; samples {len(S)} ({sum(s['still'] for s in S)} standstill)")
def deskew(s, tau):
"""Ouster points expressed in the sensor frame at the camera time (t_cam + tau); tau: float or {bag: float}."""
tb = tau[s["bag"]] if isinstance(tau, dict) else tau
dt = (s["t_cam"] + tb - s["t_pts"])[:, None]
R = Rotation.from_rotvec(s["w"][None, :] * dt).as_matrix()
return np.einsum("nji,nj->ni", R, s["P"] - s["v"][None, :] * dt)
def cam_pose(p):
return se3(Rotation.from_rotvec(p[:3]).as_matrix() @ R_OPT, p[3:6])
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
BF = 60.0
CAP = 2.0
def residuals(p, tau, subset):
T = cam_pose(p)
r = []
for s in subset:
uv, z, ok = project(T, deskew(s, tau))
ui = uv[ok].astype(int)
zs = s["Z"][ui[:, 1], ui[:, 0]]
v = zs > 0
r.append(BF * (1 / z[ok][v] - 1 / zs[v]))
return np.concatenate(r)
def cost(p, tau, subset):
r = residuals(p, tau, subset)
return float(np.mean(np.minimum(r * r, CAP * CAP))) if len(r) > 1000 else 1e9
def mi(p, tau, subset):
T = cam_pose(p)
a = []
b = []
for s in subset:
uv, z, ok = project(T, deskew(s, tau))
ui = uv[ok].astype(int)
a.append(s["abin"][ok])
b.append(s["Lb"][ui[:, 1], ui[:, 0]] // 8)
a = np.concatenate(a)
b = np.concatenate(b).astype(int)
h = np.bincount(a * 32 + b, minlength=1024).reshape(32, 32).astype(float)
pj = h / h.sum()
px = pj.sum(1, keepdims=True)
py = pj.sum(0, keepdims=True)
nz = pj > 0
return float(np.sum(pj[nz] * np.log(pj[nz] / (px @ py)[nz])))
def optimize(fun, p0, free=range(6)):
free = list(free)
base = np.array(p0, float)
steps = np.array([0.01, 0.01, 0.01, 0.02, 0.02, 0.02])[free]
def full(q):
p = base.copy()
p[free] = q
return p
o = minimize(lambda q: fun(full(q)), base[free], method="Powell",
options=dict(xtol=1e-5, ftol=1e-7, maxfev=4000, direc=np.diag(steps)))
return full(o.x), float(o.fun)
STILL = [s for s in S if s["still"]]
MOVE = [s for s in S if not s["still"]]
T_v_o = np.array(LID["T_velodyne_os_sensor"])
T_v_c_pub = se3(R_OPT, [0.3984, 0.0, -0.3052])
T_v_o_pub = se3(np.eye(3), [0.3007, 0.0, -0.1114 - 0.03618])
T_o_c_v1 = inv(T_v_o_pub) @ T_v_c_pub # camera relative to the Ouster, as a v1 user would compute it
p_v1 = np.r_[Rotation.from_matrix(T_o_c_v1[:3, :3] @ R_OPT.T).as_rotvec(), T_o_c_v1[:3, 3]]
# 1) standstill: 6-DoF, several initial heights
best = None
for z0 in (T_o_c_v1[2, 3], -0.10, -0.04, 0.02):
p, c = optimize(lambda p: cost(p, 0.0, STILL), np.r_[0, 0, 0, T_o_c_v1[0, 3], 0.06, z0])
if best is None or c < best[1]:
best = (p, c)
p_still = best[0]
say(f"\n## standstill only ({len(STILL)} samples): {pose_str(cam_pose(p_still))} cost {best[1]:.3f} "
f"(v1: {cost(p_v1, 0.0, STILL):.3f})")
# 2) time offset scan per sequence on moving samples (pose fixed)
BAGS = sorted({s_["bag"] for s_ in S})
taus = np.arange(-0.15, 0.151, 0.01)
tau = {}
tau_scans = {}
for bag in BAGS:
mv = [s_ for s_ in MOVE if s_["bag"] == bag]
ct = [cost(p_still, t, mv) for t in taus]
k = int(np.argmin(ct))
tb = float(taus[k])
if 0 < k < len(ct) - 1:
q = np.polyfit(taus[k - 1:k + 2], ct[k - 1:k + 2], 2)
tb = float(-q[1] / (2 * q[0]))
tau[bag] = tb
tau_scans[bag] = list(zip(taus.tolist(), ct))
say(f"## {bag}: camera time offset {tb * 1e3:+.1f} ms (cost {min(ct):.3f}; at 0: {cost(p_still, 0.0, mv):.3f}); scan: "
+ ", ".join(f"{t_ * 1e3:+.0f}:{c_:.2f}" for t_, c_ in zip(taus, ct)))
# 3) joint refinement on all samples, alternating pose and per-sequence tau
p_all = p_still
for _ in range(2):
p_all, c_all = optimize(lambda p: cost(p, tau, S), p_all)
for bag in BAGS:
mv = [s_ for s_ in MOVE if s_["bag"] == bag]
o = minimize(lambda x: cost(p_all, x[0], mv), [tau[bag]], method="Powell", options=dict(xtol=1e-4, direc=np.array([[0.01]])))
tau[bag] = float(o.x[0])
T_o_c = cam_pose(p_all)
say(f"\n## v2 left optical in os_sensor: {pose_str(T_o_c)}; tau {dict((b, round(t * 1e3, 1)) for b, t in tau.items())} ms; "
f"cost {cost(p_all, tau, S):.3f}; v1 cost {cost(p_v1, tau, S):.3f}")
say(f" MI: v2 {mi(p_all, tau, S):.4f}, v1 {mi(p_v1, tau, S):.4f}")
p_mi, _ = optimize(lambda p: -mi(p, tau, S), p_all)
say(f" MI-only optimum (cross-check): {pose_str(cam_pose(p_mi))}")
per_bag = {}
for bag in sorted({s["bag"] for s in S}):
sub = [s for s in S if s["bag"] == bag]
pb, cb = optimize(lambda p: cost(p, tau, sub), p_all)
per_bag[bag] = cam_pose(pb).tolist()
say(f" {bag}: {pose_str(cam_pose(pb))} cost {cb:.3f}")
# 4) height profile for the web figure
prof = []
for z in np.arange(-0.24, 0.061, 0.03):
pz, cz = optimize(lambda p: cost(p, tau, S), np.r_[p_all[:5], z], free=range(5))
prof.append((float(z), cz, mi(pz, tau, S)))
say(f" profile z {z * 100:+6.1f} cm: cost {cz:.3f} MI {prof[-1][2]:.4f}")
# 5) row-wise depth ratio, v1 vs v2 (figure data)
rows = {}
for name, p in (("v1", p_v1), ("v2", p_all)):
T = cam_pose(p)
vs = []
rs = []
for s in S:
uv, z, ok = project(T, deskew(s, tau))
ui = uv[ok].astype(int)
zs = s["Z"][ui[:, 1], ui[:, 0]]
v = zs > 0
vs.append(ui[v, 1])
rs.append(z[ok][v] / zs[v])
vs = np.concatenate(vs)
rs = np.concatenate(rs)
edges = np.arange(0, IMG_H + 1, 48)
rows[name] = [(float((a + b) / 2), float(np.median(rs[(vs >= a) & (vs < b)])))
for a, b in zip(edges[:-1], edges[1:]) if np.sum((vs >= a) & (vs < b)) > 200]
T_v_c = T_v_o @ T_o_c
say(f"\n## left optical in base_link(=velodyne): {pose_str(T_v_c)}")
json.dump(dict(T_os_sensor_left_optical=T_o_c.tolist(), T_velodyne_left_optical=T_v_c.tolist(),
T_velodyne_left_optical_v1=T_v_c_pub.tolist(), camera_tau=tau, tau_scan=tau_scans,
mi_T_os_sensor_left_optical=cam_pose(p_mi).tolist(), per_bag=per_bag, height_profile=prof, rows=rows,
p_v1=p_v1.tolist(), p_v2=p_all.tolist()),
open(OUT / "camera.json", "w"), indent=1)
open(OUT / "camera_log.txt", "w").write("\n".join(log) + "\n")