File size: 12,625 Bytes
a8bcfc0
 
 
 
 
 
 
 
 
 
 
 
 
 
02c4b51
a8bcfc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
02c4b51
 
 
 
 
 
 
 
 
 
 
 
 
 
a8bcfc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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="<f4").reshape(-1, 4)
    points_cm = scan[:, :3].astype(np.float64) * 100
    ranges = np.linalg.norm(scan[:, :3], axis=1)
    asset_sha256 = file_sha256(args.assets)
    published_shard = "841dfff386059908515c05376cd6226d0dce84402798341dce2b138d32f228d6"
    if args.sequence == "00" and args.frame == 120:
        assert asset_sha256 == published_shard, "Asset shard differs from published inventory"
    provenance = {
        "dataset": "mcocheteux/KITTI-C2L-Dataset",
        "source_revision": "115005094f96a9cca4a1ea8c64a387c0cbb4de72",
        "geometry_protocol": "full_projection_v1_1",
        "sample_id": row["sample_id"],
        "sample_seed": row["sample_seed"],
        "camera_id": row["camera_id"],
        "raw_date": row["raw_date"],
        "raw_drive": row["raw_drive"],
        "raw_frame_index": row["raw_frame_index"],
        "image_png_sha256": hashlib.sha256(asset["image_png"]).hexdigest(),
        "points_bin_sha256": hashlib.sha256(asset["points_bin"]).hexdigest(),
        "asset_shard_sha256": asset_sha256,
        "legacy_metadata_sha256": hashlib.sha256(args.metadata.read_bytes()).hexdigest(),
        "calibration_reference_sha256": hashlib.sha256(args.reference.read_bytes()).hexdigest(),
        "reference_transform_cm": reference.tolist(),
        "miscalibrated_transform_cm": miscal.tolist(),
        "intrinsics": intrinsics.tolist(),
        "source_shape": list(image.shape),
        "crop_xyxy": [220, 0, 1020, 376],
        "point_colours": "Unchanged raw LiDAR Euclidean range, turbo, 2 to 60 metres",
        "projection_filter": "Positive camera Z above 2 metres; native image field of view; raw range 2 to 60 metres",
        "sensor_data_modified": False,
        "model_prediction": False,
        "license": "CC BY-NC-SA 3.0; KITTI: A. Geiger, P. Lenz, C. Stiller, R. Urtasun (2013)",
        "checks": {
            "seed_deltas_match_published_metadata": True,
            "legacy_recomposition_matches_published_extrinsic": True,
            "same_image_scan_crop_and_colour_scale_both_panels": True,
            "asset_shard_matches_published_sha256": asset_sha256 == published_shard,
        },
    }
    return row, image, points_cm, ranges, reference, miscal, intrinsics, provenance


def project(points_cm, transform, intrinsics, width, height, ranges):
    camera = points_cm @ transform[:3, :3].T + transform[:3, 3]
    positive = camera[:, 2] > 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 = (
        '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
        f'width="{width}" height="{height}" viewBox="0 0 {width} {height}">\n'
        '<title>KITTI-C2L: synthetic miscalibration and KITTI reference calibration</title>\n'
        '<desc>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.</desc>\n'
        f'<image width="{width}" height="{height}" xlink:href="data:image/png;base64,{encoded}"/>\n'
        '</svg>\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())