KITTI-C2L-Dataset / code /scripts /audit_calibration.py
mcocheteux's picture
Release v1.1.0: add source-consistent full-projection calibration protocol
1150050 verified
Raw History Blame Contribute Delete
11.4 kB
"""Regenerate source-consistent v1.1 labels and audit against KITTI's full P.
This is an algebraic conversion audit, not a new physical calibration estimate.
No image-based objective, test-set fitting, or raw sensor modification is used.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
from kitti_c2l.generate import generate_sequence_rows
from kitti_c2l.geometry import euler_deg_to_matrix
from kitti_c2l.kitti_calib import load_rig_chain, parse_calib_file
from kitti_c2l.sequence_mapping import load_sequence_mapping
from kitti_c2l.windows import generate_sequence_windows
from kitti_c2l.writer import write_split, write_windows
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--raw-root", required=True, type=Path)
parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
parser.add_argument("--data-output", required=True, type=Path)
parser.add_argument("--report-output", required=True, type=Path)
args = parser.parse_args()
if args.data_output.exists() or args.report_output.exists():
raise FileExistsError("Refusing to overwrite generated calibration artifacts")
mapping = {key: value for key, value in load_sequence_mapping().items() if value.available}
dates = sorted({info.date for info in mapping.values()})
inputs = {
f"{date}/{name}": sha256(args.raw_root / date / name)
for date in dates
for name in ("calib_imu_to_velo.txt", "calib_velo_to_cam.txt", "calib_cam_to_cam.txt")
}
per_date = {}
for date in dates:
old = load_rig_chain(args.raw_root / date)
exact = load_rig_chain(args.raw_root / date, camera_model="full_projection_v1_1")
per_date[date] = {
"legacy_translation_cm": old.translation_cam_from_lidar_cm.tolist(),
"full_projection_translation_cm": exact.translation_cam_from_lidar_cm.tolist(),
"translation_delta_cm": (
exact.translation_cam_from_lidar_cm - old.translation_cam_from_lidar_cm
).tolist(),
"translation_delta_l2_cm": float(
np.linalg.norm(
exact.translation_cam_from_lidar_cm - old.translation_cam_from_lidar_cm
)
),
"rotation_unchanged": bool(
np.array_equal(old.rotation_cam_from_lidar, exact.rotation_cam_from_lidar)
),
"full_projection_rotation": exact.rotation_cam_from_lidar.tolist(),
"intrinsics": exact.intrinsics.tolist(),
}
frames, windows = {"train": [], "test": []}, {"train": [], "test": []}
for seq, info in mapping.items():
frames[info.split].extend(
generate_sequence_rows(info, args.raw_root, camera_model="full_projection_v1_1")
)
windows[info.split].extend(
generate_sequence_windows(info, args.raw_root, camera_model="full_projection_v1_1")
)
print(f"Regenerated sequence {seq}", flush=True)
files = []
allowed_changes = {"gt_t_cam_from_velo_cm", "miscal_t_cam_from_velo_cm"}
for split in frames:
for name, rows, writer in (
(f"{split}.parquet", frames[split], write_split),
(f"windows_{split}.parquet", windows[split], write_windows),
):
path = args.data_output / name
writer(rows, path)
table, legacy = pq.read_table(path), pq.read_table(args.root / "data" / name)
assert table.schema == legacy.schema
assert table.num_rows == legacy.num_rows
unchanged = [key for key in table.column_names if key not in allowed_changes]
assert table.select(unchanged).equals(legacy.select(unchanged)), (
f"Unexpected non-translation change: {name}"
)
# Independent vectorized composition, using the stored float32 deltas.
def array(key, shape, current=table):
return np.asarray(current[key].to_pylist(), dtype=np.float64).reshape(-1, *shape)
rg, tg = array("gt_R_cam_from_velo", (3, 3)), array("gt_t_cam_from_velo_cm", (3,))
rc = euler_deg_to_matrix(
np.column_stack(
[table[f"delta_cam_{axis}_deg"].to_numpy() for axis in ("roll", "pitch", "yaw")]
)
)
rl = euler_deg_to_matrix(
np.column_stack(
[
table[f"delta_lidar_{axis}_deg"].to_numpy()
for axis in ("roll", "pitch", "yaw")
]
)
)
tc = np.column_stack([table[f"delta_cam_t{axis}_cm"].to_numpy() for axis in "xyz"])
tl = np.column_stack([table[f"delta_lidar_t{axis}_cm"].to_numpy() for axis in "xyz"])
rm = rc @ rg @ rl.transpose(0, 2, 1)
tm = np.einsum("nij,nj->ni", rc, tg) + tc - np.einsum("nij,nj->ni", rm, tl)
residual = float(np.max(np.abs(tm - array("miscal_t_cam_from_velo_cm", (3,)))))
assert residual < 3e-4
for date in dates:
mask = np.asarray(table["raw_date"].to_pylist()) == date
if mask.any():
np.testing.assert_allclose(
tg[mask],
np.broadcast_to(
per_date[date]["full_projection_translation_cm"], tg[mask].shape
),
atol=2e-5,
rtol=0,
)
files.append(
{
"path": f"data_v1_1/{name}",
"rows": table.num_rows,
"bytes": path.stat().st_size,
"sha256": sha256(path),
"legacy_sha256": sha256(args.root / "data" / name),
"unchanged_columns": unchanged,
"max_composition_residual_cm": residual,
}
)
projection = []
availability = []
for seq, info in mapping.items():
date_root = args.raw_root / info.date
drive = date_root / f"{info.date}_drive_{info.drive}_sync"
availability.append(
{
"sequence": seq,
"image_02": (drive / "image_02/data").is_dir(),
"image_03": (drive / "image_03/data").is_dir(),
"oxts": (drive / "oxts/data").is_dir(),
"lidar_timestamps": (drive / "velodyne_points/timestamps.txt").is_file(),
}
)
cam = parse_calib_file(date_root / "calib_cam_to_cam.txt")
velo = parse_calib_file(date_root / "calib_velo_to_cam.txt")
p = cam["P_rect_02"].reshape(3, 4)
exact = load_rig_chain(date_root, camera_model="full_projection_v1_1")
old = load_rig_chain(date_root)
old_errors, exact_errors, stored_errors = [], [], []
stored_row = next(row for row in frames[info.split] if row.sequence == seq)
selected_frames = sorted(
{int((info.frame_count - 1) * fraction) for fraction in (0.1, 0.5, 0.9)}
)
for frame in selected_frames:
raw_frame = info.raw_frame_index(frame)
path = drive / "velodyne_points/data" / f"{raw_frame:010d}.bin"
points = np.fromfile(path, dtype=np.float32).reshape(-1, 4)[:, :3].astype(np.float64)
rect = (points @ velo["R"].reshape(3, 3).T + velo["T"]) @ cam["R_rect_00"].reshape(
3, 3
).T
projected = np.column_stack((rect, np.ones(len(rect)))) @ p.T
uv = projected[:, :2] / np.where(projected[:, 2:] != 0, projected[:, 2:], np.nan)
valid = (
(projected[:, 2] > 3)
& (uv[:, 0] >= 0)
& (uv[:, 0] < exact.image_width)
& (uv[:, 1] >= 0)
& (uv[:, 1] < exact.image_height)
)
assert valid.sum() > 100
for rig, errors in ((old, old_errors), (exact, exact_errors)):
xyz = (
points[valid] @ rig.rotation_cam_from_lidar.T
+ rig.translation_cam_from_lidar_cm / 100
)
homogeneous = xyz @ rig.intrinsics.T
predicted = homogeneous[:, :2] / homogeneous[:, 2:]
errors.extend(np.linalg.norm(predicted - uv[valid], axis=1).tolist())
stored_xyz = (
points[valid] @ np.asarray(stored_row.gt_R_cam_from_velo).reshape(3, 3).T
+ np.asarray(stored_row.gt_t_cam_from_velo_cm) / 100
)
stored_homogeneous = (
stored_xyz @ np.asarray(stored_row.camera_intrinsics).reshape(3, 3).T
)
stored_uv = stored_homogeneous[:, :2] / stored_homogeneous[:, 2:]
stored_errors.extend(np.linalg.norm(stored_uv - uv[valid], axis=1).tolist())
projection.append(
{
"sequence": seq,
"frame_indices": selected_frames,
"points": len(exact_errors),
"legacy_vs_source_mean_px": float(np.mean(old_errors)),
"legacy_vs_source_p95_px": float(np.percentile(old_errors, 95)),
"full_vs_source_max_px": float(np.max(exact_errors)),
"stored_float32_vs_source_max_px": float(np.max(stored_errors)),
}
)
assert projection[-1]["full_vs_source_max_px"] < 1e-9
assert projection[-1]["stored_float32_vs_source_max_px"] < 1e-3
assert all(sha256(args.raw_root / key) == digest for key, digest in inputs.items())
report = {
"version": "1.1.0",
"camera_model": "full_projection_v1_1",
"status": "pass",
"claim": "Exact factorization of the supplied KITTI projection; no new physical ground truth or absolute-accuracy claim.",
"date": "2026-10-17",
"source_reference": "https://www.cvlibs.net/publications/Geiger2013IJRR.pdf, equation 7",
"formula": "b = solve(P[:,:3], P[:,3]); R = R_rect_00 @ R_velo_to_cam; t = R_rect_00 @ t_velo_to_cam + b",
"translation_unit": "centimetres",
"source_calibration_sha256": inputs,
"per_date": per_date,
"files": files,
"projection_checks": projection,
"available_refinement_inputs": availability,
"parameters_estimated_from_recordings": False,
"fit_on_test_data": False,
"v1_0_files_modified": False,
"sensor_payloads_modified": False,
}
args.report_output.parent.mkdir(parents=True, exist_ok=True)
args.report_output.write_text(json.dumps(report, indent=2) + "\n")
print(
json.dumps(
{
"status": "pass",
"metadata_rows": sum(f["rows"] for f in files),
"projection_points": sum(p["points"] for p in projection),
"max_full_projection_residual_px": max(
p["full_vs_source_max_px"] for p in projection
),
},
indent=2,
)
)
if __name__ == "__main__":
main()