File size: 6,352 Bytes
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""Renders an animated GIF of a LiDAR projection smoothly correcting from a
miscalibrated stage back to ground truth (SE(3) interpolation between the two
extrinsics), for a README/webpage hero visual.

Usage:
    python scripts/make_correction_animation.py \\
        --metadata-parquet data/train.parquet --assets-parquet assets_scratch/shards/data/frames_train-00000-of-00044.parquet \\
        --sequence 00 --frame 120 --stage 1 --output docs/assets/correction_animation.gif
"""

from __future__ import annotations

import argparse
import io
import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pyarrow.parquet as pq
from PIL import Image
from scipy.spatial.transform import Rotation, Slerp

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))

from kitti_c2l.geometry import project_to_image, transform_points  # noqa: E402
from kitti_c2l.loader.dataset import (  # noqa: E402
    decode_image_png,
    decode_points_bin,
    row_extrinsic,
)

MIN_DEPTH_CM = 200.0
MAX_DEPTH_CM = 8000.0


def _interpolate_transforms(r_start: np.ndarray, t_start: np.ndarray, r_end: np.ndarray, t_end: np.ndarray, num_steps: int):
    key_rots = Rotation.from_matrix(np.stack([r_start, r_end]))
    slerp = Slerp([0.0, 1.0], key_rots)
    fractions = np.linspace(0.0, 1.0, num_steps)
    rotations = slerp(fractions).as_matrix()
    translations = t_start[None, :] + fractions[:, None] * (t_end - t_start)[None, :]
    return rotations, translations, fractions


def _render_frame(
    image: np.ndarray, points_cm: np.ndarray, rotation: np.ndarray, translation: np.ndarray, intrinsics: np.ndarray,
    title: str, max_points: int = 18000, rng: np.random.Generator | None = None,
) -> np.ndarray:
    height, width = image.shape[:2]
    points_cam = transform_points(points_cm, rotation, translation)
    pixels = project_to_image(points_cam, intrinsics)
    depths = points_cam[:, 2]

    valid = (
        (depths > MIN_DEPTH_CM) & (depths < MAX_DEPTH_CM)
        & (pixels[:, 0] >= 0) & (pixels[:, 0] < width)
        & (pixels[:, 1] >= 0) & (pixels[:, 1] < height)
    )
    pixels, depths = pixels[valid], depths[valid]
    if pixels.shape[0] > max_points:
        rng = rng or np.random.default_rng(0)
        keep = rng.choice(pixels.shape[0], size=max_points, replace=False)
        pixels, depths = pixels[keep], depths[keep]

    # Render at half native resolution: smaller file, and softens the raw
    # 64-beam scan-line banding that's distractingly sharp at full res.
    scale = 0.5
    fig, ax = plt.subplots(figsize=(width * scale / 100, height * scale / 100 + 0.45), dpi=100)
    fig.subplots_adjust(top=0.88, bottom=0.0, left=0.0, right=1.0)
    ax.imshow(image)
    if pixels.shape[0] > 0:
        order = np.argsort(-depths)
        ax.scatter(pixels[order, 0], pixels[order, 1], c=depths[order] / 100.0, cmap="turbo", s=10, alpha=0.5, linewidths=0, vmin=2, vmax=80)
    ax.set_title(title, fontsize=10, fontweight="bold", color="#212121")
    ax.axis("off")
    ax.set_xlim(0, width)
    ax.set_ylim(height, 0)

    buf = io.BytesIO()
    fig.savefig(buf, format="png")
    plt.close(fig)
    buf.seek(0)
    return np.array(Image.open(buf).convert("RGB"))


def make_animation(
    metadata_parquet: Path,
    assets_parquet: Path,
    sequence: str,
    frame: int,
    stage: int,
    output_path: Path,
    num_steps: int = 36,
    hold_frames: int = 8,
    fps: int = 20,
) -> Path:
    meta_rows = pq.read_table(metadata_parquet).to_pylist()
    row = next(r for r in meta_rows if r["sequence"] == sequence and r["frame_index"] == frame and r["stage"] == stage)

    asset_rows = pq.read_table(assets_parquet).to_pylist()
    frame_id = f"{sequence}_{frame:06d}"
    asset_row = next(r for r in asset_rows if r["frame_id"] == frame_id)

    image = decode_image_png(asset_row["image_png"])
    points_cm = decode_points_bin(asset_row["points_bin"])
    intrinsics = np.array(row["camera_intrinsics"], dtype=np.float64).reshape(3, 3)

    r_gt, t_gt = row_extrinsic(row, use_ground_truth=True)
    r_miscal, t_miscal = row_extrinsic(row, use_ground_truth=False)

    rotations, translations, fractions = _interpolate_transforms(r_miscal, t_miscal, r_gt, t_gt, num_steps)

    frames = []
    for i, (rotation, translation, frac) in enumerate(zip(rotations, translations, fractions, strict=True)):
        progress_pct = int(round(frac * 100))
        title = f"seq {sequence} frame {frame}  |  correcting stage {stage} miscalibration  ({progress_pct}%)"
        frames.append(_render_frame(image, points_cm, rotation, translation, intrinsics, title))
        print(f"  rendered {i + 1}/{num_steps}")

    pil_frames = [Image.fromarray(f) for f in frames]
    pil_frames = [pil_frames[0]] * hold_frames + pil_frames + [pil_frames[-1]] * hold_frames

    # Shared adaptive palette across all frames: much smaller file than per-frame
    # palettes, and avoids color flicker between frames.
    palette_source = pil_frames[len(pil_frames) // 2].quantize(colors=192, method=Image.MEDIANCUT)
    pil_frames = [f.quantize(palette=palette_source, dither=Image.FLOYDSTEINBERG) for f in pil_frames]

    output_path.parent.mkdir(parents=True, exist_ok=True)
    pil_frames[0].save(
        output_path, save_all=True, append_images=pil_frames[1:], duration=int(1000 / fps), loop=0, optimize=True
    )
    return output_path


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--metadata-parquet", required=True)
    parser.add_argument("--assets-parquet", required=True)
    parser.add_argument("--sequence", required=True)
    parser.add_argument("--frame", type=int, required=True)
    parser.add_argument("--stage", type=int, default=1)
    parser.add_argument("--output", default="docs/assets/correction_animation.gif")
    parser.add_argument("--num-steps", type=int, default=36)
    parser.add_argument("--fps", type=int, default=20)
    args = parser.parse_args()

    output_path = make_animation(
        Path(args.metadata_parquet), Path(args.assets_parquet), args.sequence, args.frame, args.stage,
        Path(args.output), num_steps=args.num_steps, fps=args.fps,
    )
    print(f"wrote {output_path}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())