greenbot-dataset / tools /make_release.py
jlblancoc's picture
Calibration v2, figures, tools and dataset card
2a86f7e verified
Raw History Blame Contribute Delete
7.19 kB
"""Write the GREENBOT calibration v2 release files from the estimation results.
Usage: make_release.py <calib_out_dir> <release_dir> <timing_dir>
calib_out_dir: lidars.json, camera.json
timing_dir : timing_<seq>.npz for every sequence to convert
"""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
import yaml
from scipy.spatial.transform import Rotation
sys.path.insert(0, str(Path(__file__).parent))
from common import D_L, D_R, IMG_H, IMG_W, K_L, K_R, R_LR, T_LR, inv, se3 # noqa: E402
CAL = Path(sys.argv[1])
REL = Path(sys.argv[2])
TIM = Path(sys.argv[3])
REL.mkdir(parents=True, exist_ok=True)
L = json.load(open(CAL / "lidars.json"))
C = json.load(open(CAL / "camera.json"))
T_v_o = np.array(L["T_velodyne_os_sensor"])
T_o_c = np.array(C["T_os_sensor_left_optical"])
T_v_c = T_v_o @ T_o_c
T_l_r = se3(R_LR, T_LR) # right optical frame in the left optical frame
T_o_lidar = se3(Rotation.from_euler("z", 180, degrees=True).as_matrix(), [0, 0, 0.03618])
T_o_imu = se3(np.eye(3), [0.00625, -0.01178, 0.00764])
def entry(parent, child, T, note):
q = Rotation.from_matrix(T[:3, :3]).as_quat() # x, y, z, w
rpy = Rotation.from_matrix(T[:3, :3]).as_euler("xyz", degrees=True)
return dict(parent=parent, child=child, translation=[round(float(x), 5) for x in T[:3, 3]],
rotation_xyzw=[round(float(x), 7) for x in q], rpy_xyz_deg=[round(float(x), 3) for x in rpy], note=note)
TF = [
entry("base_link", "velodyne", np.eye(4), "base_link is the Velodyne VLP-16 beam origin (x forward, y left, z up)"),
entry("base_link", "os_sensor", T_v_o, "Ouster OS0 sensor frame (ouster-ros convention, bottom of the housing); estimated by ICP"),
entry("os_sensor", "os_lidar", T_o_lidar, "from the Ouster /tf_static recorded in the bags"),
entry("os_sensor", "os_imu", T_o_imu, "from the Ouster /tf_static recorded in the bags"),
entry("base_link", "stereo_left_optical_frame", T_v_c, "Bumblebee BB2 left camera, optical frame (x right, y down, z forward); estimated from LiDAR-stereo alignment"),
entry("stereo_left_optical_frame", "stereo_right_optical_frame", T_l_r, "stereo extrinsics from calib.ini (Feb 2024)"),
]
hdr = ("# GREENBOT dataset: static transforms, calibration v2\n"
"# All poses are 'child frame expressed in parent frame'. Translations in meters.\n"
"# rotation_xyzw is authoritative; rpy_xyz_deg (extrinsic X-Y-Z, i.e. roll-pitch-yaw) is given for reading only.\n")
with open(REL / "greenbot_tf_static_v2.yaml", "w") as f:
f.write(hdr)
yaml.safe_dump(dict(version="2.0", frames_convention="REP-103", transforms=TF), f, sort_keys=False, default_flow_style=None)
# ---------------- launch file ----------------
nodes = []
for e in TF:
x, y, z = e["translation"]
qx, qy, qz, qw = e["rotation_xyzw"]
name = f"tf_{e['parent']}_to_{e['child']}"
nodes.append(f''' Node(
package="tf2_ros",
executable="static_transform_publisher",
name="{name}",
arguments=[
"--x", "{x}", "--y", "{y}", "--z", "{z}",
"--qx", "{qx}", "--qy", "{qy}", "--qz", "{qz}", "--qw", "{qw}",
"--frame-id", "{e['parent']}", "--child-frame-id", "{e['child']}",
],
),''')
launch = f'''"""GREENBOT dataset: static transforms (calibration v2).
Not needed when playing the v2 MCAP bags (they already contain /tf_static);
use it with the legacy v1 bags or for your own processing:
ros2 launch greenbot_tf_static_v2.launch.py
"""
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
{chr(10).join(nodes)}
])
'''
open(REL / "greenbot_tf_static_v2.launch.py", "w").write(launch)
# ---------------- camera_info YAMLs (camera_calibration / camera_info_manager format) ----------------
Rcv = R_LR.T
Tcv = (-R_LR.T @ T_LR).reshape(3, 1)
R1, R2, P1, P2, _, _, _ = cv2.stereoRectify(K_L, D_L, K_R, D_R, (IMG_W, IMG_H), Rcv, Tcv, flags=cv2.CALIB_ZERO_DISPARITY, alpha=0)
def cam_yaml(name, K, D, R, P):
def mat(a, r, c):
return dict(rows=r, cols=c, data=[float(x) for x in np.asarray(a).ravel()])
return dict(image_width=IMG_W, image_height=IMG_H, camera_name=name, camera_matrix=mat(K, 3, 3),
distortion_model="plumb_bob", distortion_coefficients=mat(D, 1, 5),
rectification_matrix=mat(R, 3, 3), projection_matrix=mat(P, 3, 4))
for side, K, D, R, P in (("left", K_L, D_L, R1, P1), ("right", K_R, D_R, R2, P2)):
with open(REL / f"stereo_{side}.yaml", "w") as f:
f.write(f"# GREENBOT Bumblebee BB2 {side} camera, from calib.ini (MRPT kinect-stereo-calib, Feb 2024).\n"
f"# Images are 1024x768 bayer_grbg8. Frame: stereo_{side}_optical_frame\n")
yaml.safe_dump(cam_yaml(f"bumblebee_{side}", K, D, R, P), f, sort_keys=False, default_flow_style=None)
# ---------------- timing models ----------------
# Policy: stamps already on the PC clock are kept. Ouster stamps taken from the sensor's internal clock are mapped to
# the PC clock with the arrival envelope of the Ouster IMU (sub-millisecond transport latency); points share that clock.
def mode_of(t):
if "ouster_points_bag" not in t:
return "no_ouster"
return "sensor_clock" if np.median(t["ouster_points_bag"] - t["ouster_points_hdr"]) > 1e3 else "pc_clock"
def envelope_fit(b, h):
d = b - h
w = ((h - h[0]) // 20).astype(int)
env = np.array([[h[w == i][np.argmin(d[w == i])], np.min(d[w == i])] for i in np.unique(w)])
h0 = float(h[0])
p = np.polyfit(env[:, 0] - h0, env[:, 1], 1)
r = env[:, 1] - np.polyval(p, env[:, 0] - h0)
k = np.abs(r) < 3 * np.median(np.abs(r)) + 1e-5
p = np.polyfit(env[k, 0] - h0, env[k, 1], 1)
return h0, float(p[0]), float(p[1]), float(np.std(env[k, 1] - np.polyval(p, env[k, 0] - h0)))
seqs = {}
for npz in sorted(TIM.glob("timing_*.npz")):
seq = npz.stem.replace("timing_", "")
t = np.load(npz)
mode = mode_of(t)
if mode == "sensor_clock":
h0, slope, offset, res = envelope_fit(t["ouster_imu_bag"], t["ouster_imu_hdr"])
else:
h0, slope, offset, res = 0.0, 0.0, 0.0, 0.0
seqs[seq] = dict(ouster_stamp_mode=mode, ouster_h0=h0, ouster_slope=slope, ouster_offset=offset,
ouster_clock_drift_ppm=round(slope * 1e6, 2), clock_fit_residual_ms=round(res * 1e3, 3),
velodyne_dt=0.0, camera_dt=0.0)
with open(REL / "greenbot_timing_v2.yaml", "w") as f:
f.write("# GREENBOT v2 time base: the PC clock of the recording computer.\n"
"# Camera and Velodyne stamps are kept. Ouster stamps (points, imu, reflec_image) are mapped as\n"
"# t = h + ouster_offset + ouster_slope * (h - ouster_h0) (identity for pc_clock sequences)\n"
"# where h is the original stamp; for sensor_clock sequences the map is fitted to the Ouster IMU arrival times.\n")
yaml.safe_dump(dict(velodyne_origin_in_legacy_base_link=L["velodyne_origin_in_legacy_base_link"], sequences=seqs), f, sort_keys=False)
print("written:", sorted(p.name for p in REL.iterdir()))