File size: 11,359 Bytes
1150050 | 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | """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()
|