#!/usr/bin/env python3 """Render a real KITTI-C2L pair, without synthesizing or retouching sensor data. Requirements: numpy, pillow, pyarrow, matplotlib. Use the frozen legacy metadata and v1.1 calibration_reference.json. The exact published seed regenerates the independent sensor deltas, which are checked against the legacy row before composing the v1.1 full-projection extrinsic. The same central crop, raw LiDAR scan, range colours and marker style are used in both panels. This is a geometry illustration, not a model prediction. """ from __future__ import annotations import argparse import base64 import hashlib import io import json from pathlib import Path import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pyarrow.parquet as pq from matplotlib.colors import Normalize from PIL import Image def euler_matrix(degrees): r, p, y = np.deg2rad(degrees) rx = np.array([[1, 0, 0], [0, np.cos(r), -np.sin(r)], [0, np.sin(r), np.cos(r)]]) ry = np.array([[np.cos(p), 0, np.sin(p)], [0, 1, 0], [-np.sin(p), 0, np.cos(p)]]) rz = np.array([[np.cos(y), -np.sin(y), 0], [np.sin(y), np.cos(y), 0], [0, 0, 1]]) return rz @ ry @ rx def sensor_delta(rng, max_rotation, max_translation): angles = rng.uniform(-max_rotation, max_rotation, 3) translation = rng.uniform(-max_translation, max_translation, 3) transform = np.eye(4) transform[:3, :3] = euler_matrix(angles) transform[:3, 3] = translation return transform, angles, translation def file_sha256(path): digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def prepare(args): matches = pq.read_table( args.metadata, filters=[("sequence", "=", args.sequence), ("frame_index", "=", args.frame), ("stage", "=", args.stage)], ).to_pylist() if len(matches) != 1: raise ValueError(f"Expected one metadata row, got {len(matches)}") row = matches[0] refs = json.loads(args.reference.read_text()) calibration = refs["calibrations"][row["raw_date"]] reference = np.array(calibration["T_rectified_camera2_from_velodyne_cm"]) intrinsics = np.array(calibration["K_rectified_camera2"]) rng = np.random.default_rng(row["sample_seed"]) lidar, lidar_angles, lidar_t = sensor_delta(rng, row["stage_max_rotation_deg"], row["stage_max_translation_cm"]) camera, camera_angles, camera_t = sensor_delta(rng, row["stage_max_rotation_deg"], row["stage_max_translation_cm"]) for name, angles, translation in [("lidar", lidar_angles, lidar_t), ("cam", camera_angles, camera_t)]: stored = [row[f"delta_{name}_{axis}_deg"] for axis in ("roll", "pitch", "yaw")] np.testing.assert_allclose(angles, stored, rtol=1e-6, atol=1e-6) stored_t = [row[f"delta_{name}_t{axis}_cm"] for axis in "xyz"] np.testing.assert_allclose(translation, stored_t, rtol=1e-6, atol=1e-5) legacy = reference.copy() legacy[:3, 3] -= np.array(calibration["translation_delta_from_legacy_cm"]) legacy_miscal = camera @ legacy @ np.linalg.inv(lidar) np.testing.assert_allclose(legacy[:3, :3], np.array(row["gt_R_cam_from_velo"]).reshape(3, 3), atol=5e-8) np.testing.assert_allclose(legacy[:3, 3], row["gt_t_cam_from_velo_cm"], atol=3e-6) np.testing.assert_allclose(legacy_miscal[:3, :3], np.array(row["miscal_R_cam_from_velo"]).reshape(3, 3), atol=5e-8) np.testing.assert_allclose(legacy_miscal[:3, 3], row["miscal_t_cam_from_velo_cm"], atol=1e-5) miscal = camera @ reference @ np.linalg.inv(lidar) wanted = f"{args.sequence}_{args.frame:06d}" asset = None for batch in pq.ParquetFile(args.assets).iter_batches(batch_size=16): for candidate in batch.to_pylist(): if candidate["frame_id"] == wanted: asset = candidate break if asset is not None: break if asset is None: raise ValueError(f"No asset {wanted} in {args.assets}") assert asset["sequence"] == row["sequence"] assert asset["raw_frame_index"] == row["raw_frame_index"] image = np.array(Image.open(io.BytesIO(asset["image_png"])).convert("RGB")) scan = np.frombuffer(asset["points_bin"], dtype=" 200 uv = np.full((len(camera), 2), np.nan) homogeneous = camera[positive] @ intrinsics.T uv[positive] = homogeneous[:, :2] / homogeneous[:, 2:3] valid = positive & (ranges >= 2) & (ranges <= 60) valid &= (uv[:, 0] >= 0) & (uv[:, 0] < width) & (uv[:, 1] >= 0) & (uv[:, 1] < height) return uv[valid], ranges[valid] def render(args): row, image, points, ranges, reference, miscal, intrinsics, provenance = prepare(args) plt.rcParams.update({"font.family": "DejaVu Sans", "svg.fonttype": "none"}) width, height = 2400, 1320 fig = plt.figure(figsize=(width / 150, height / 150), dpi=150, facecolor="#F6F7F9") ink, muted = "#142438", "#556477" def text(x, y, value, size, **kw): return fig.text(x / width, 1 - y / height, value, fontsize=size * 72 / 150, color=kw.pop("color", ink), va="top", **kw) text(104, 64, "KITTI-C2L", 104, weight="bold") text(108, 192, "Reproducible camera–LiDAR calibration", 49, color=muted) text(2294, 91, "REAL KITTI DATA", 26, ha="right", weight="bold", color=muted) text(2294, 133, "Controlled synthetic miscalibration", 25, ha="right", color=muted) panel_y, panel_h, panel_w = 382, 509.48, 1084 crop = provenance["crop_xyxy"] for index, (x, transform, title, colour, subtitle) in enumerate([ (104, miscal, "Synthetic miscalibration", "#B85120", f"Published stage {args.stage} perturbation"), (1212, reference, "KITTI reference calibration", "#087F79", "Full-projection reference · v1.1"), ]): text(x, 293, title, 48, weight="bold", color=colour) text(x, 354, subtitle, 29, color=muted) ax = fig.add_axes([x / width, 1 - (panel_y + panel_h + 30) / height, panel_w / width, panel_h / height]) ax.imshow(image, interpolation="nearest") uv, depth = project(points, transform, intrinsics, image.shape[1], image.shape[0], ranges) order = np.argsort(depth)[::-1] ax.scatter(uv[order, 0], uv[order, 1], c=depth[order], cmap="turbo", norm=Normalize(2, 60), s=1.0, alpha=0.9, linewidths=0, rasterized=True) ax.set_xlim(crop[0] - .5, crop[2] - .5) ax.set_ylim(crop[3] - .5, crop[1] - .5) ax.set_aspect("equal", adjustable="box") ax.set_axis_off() provenance[f"panel_{index}_visible_points"] = int(((uv[:, 0] >= crop[0]) & (uv[:, 0] < crop[2]) & (uv[:, 1] >= crop[1]) & (uv[:, 1] < crop[3])).sum()) text(104, 973, "Same image. Same LiDAR scan. Different extrinsics.", 48, weight="bold") text(108, 1045, "LiDAR points are coloured by distance; only the projection geometry changes.", 33, color=muted) gradient = fig.add_axes([108 / width, 1 - 1140 / height, 440 / width, 18 / height]) gradient.imshow(np.linspace(2, 60, 440)[None, :], cmap="turbo", aspect="auto", extent=[2, 60, 0, 1]) gradient.set_axis_off() text(108, 1155, "2 m", 25, color=muted) text(548, 1155, "60 m", 25, color=muted, ha="right") text(595, 1117, "LiDAR range", 28, color=muted) text(2296, 1117, f"Sequence {args.sequence} · Frame {args.frame:06d} · Stage {args.stage}", 28, color=muted, ha="right") text(2296, 1155, "Geometry illustration · no model prediction", 26, color=muted, ha="right") fig.add_artist(plt.Line2D([104 / width, 2296 / width], [1 - 1220 / height] * 2, color="#D9DFE7", linewidth=.8, transform=fig.transFigure)) text(108, 1249, "Source: KITTI / Geiger et al. (2013) · CC BY-NC-SA 3.0", 25, color=muted) text(2296, 1249, "huggingface.co/datasets/mcocheteux/KITTI-C2L-Dataset", 24, color=muted, ha="right") args.output.parent.mkdir(parents=True, exist_ok=True) fig.savefig(args.output, dpi=150, facecolor=fig.get_facecolor(), metadata={"Title": "KITTI-C2L calibration comparison", "Description": "Real sensor projections; synthetic miscalibration versus KITTI reference; no model prediction."}) plt.close(fig) # Embed the finished raster in a simple SVG so Hub sanitization cannot # change the fonts or separate the raw-image and projected-point layers. encoded = base64.b64encode(args.output.read_bytes()).decode("ascii") svg = ( '\n' 'KITTI-C2L: synthetic miscalibration and KITTI reference calibration\n' 'Real sequence 00 frame 120, stage 3; identical sensor data, crop, and range colours; ' 'v1.1 full-projection geometry. Source: KITTI / Geiger et al. (2013), CC BY-NC-SA 3.0. ' 'Geometry illustration, no model prediction.\n' f'\n' '\n' ) args.output.with_suffix(".svg").write_text(svg) Image.open(args.output).save(args.output.with_suffix(".webp"), quality=92, method=6) args.output.with_suffix(".json").write_text(json.dumps(provenance, indent=2) + "\n") print(json.dumps({"output": str(args.output), "sample": row["sample_id"], "checks": provenance["checks"]})) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--metadata", type=Path, required=True, help="Frozen legacy data/train.parquet") parser.add_argument("--reference", type=Path, required=True, help="release/v1.1.0/calibration_reference.json") parser.add_argument("--assets", type=Path, required=True, help="Asset shard containing the chosen frame") parser.add_argument("--sequence", default="00") parser.add_argument("--frame", type=int, default=120) parser.add_argument("--stage", type=int, default=3) parser.add_argument("--output", type=Path, required=True) render(parser.parse_args())