File size: 4,662 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
#!/usr/bin/env python
"""Renders a static gallery: ground truth + selected decalibration stages,
across a few example frames, for the README/webpage.

Usage:
    python scripts/make_gallery.py --metadata-parquet data/train.parquet \\
        --examples 00:120:assets_scratch/shards/data/frames_train-00000-of-00044.parquet \\
                   05:200:assets_scratch/shards/data/frames_train-00021-of-00044.parquet \\
        --stages 1,3,5 --output docs/assets/gallery.png
"""

from __future__ import annotations

import argparse
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import pyarrow.parquet as pq

from kitti_c2l.geometry import project_to_image, transform_points
from kitti_c2l.loader.dataset import decode_image_png, decode_points_bin, row_extrinsic

MIN_DEPTH_CM = 200.0
MAX_DEPTH_CM = 8000.0


def _project_valid(points_cm, rotation, translation, intrinsics, width, height):
    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)
    )
    return pixels[valid], depths[valid]


def _panel(ax, image, pixels, depths, title, title_color="#212121"):
    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.55, linewidths=0, vmin=2, vmax=80)
    ax.set_title(title, fontsize=11, color=title_color, fontweight="bold")
    ax.axis("off")


def make_gallery(metadata_parquet: Path, examples: list[tuple[str, int, Path]], stages: list[int], output_path: Path) -> Path:
    meta_rows = pq.read_table(metadata_parquet).to_pylist()

    n_cols = 1 + len(stages)
    n_rows = len(examples)
    fig, axes = plt.subplots(n_rows, n_cols, figsize=(3.6 * n_cols, 3.0 * n_rows))
    if n_rows == 1:
        axes = axes[None, :]

    for row_idx, (sequence, frame, assets_path) in enumerate(examples):
        asset_rows = pq.read_table(assets_path).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"])

        gt_row = next(r for r in meta_rows if r["sequence"] == sequence and r["frame_index"] == frame and r["stage"] == stages[0])
        width, height = int(gt_row["image_width"]), int(gt_row["image_height"])
        intrinsics = np.array(gt_row["camera_intrinsics"], dtype=np.float64).reshape(3, 3)

        r_gt, t_gt = row_extrinsic(gt_row, use_ground_truth=True)
        pixels, depths = _project_valid(points_cm, r_gt, t_gt, intrinsics, width, height)
        _panel(axes[row_idx, 0], image, pixels, depths, f"seq {sequence} frame {frame}\nground truth", title_color="#2E7D32")

        for col_idx, stage in enumerate(stages, start=1):
            stage_row = next(r for r in meta_rows if r["sequence"] == sequence and r["frame_index"] == frame and r["stage"] == stage)
            r_mis, t_mis = row_extrinsic(stage_row, use_ground_truth=False)
            pixels, depths = _project_valid(points_cm, r_mis, t_mis, intrinsics, width, height)
            title = f"stage {stage}\n±{stage_row['stage_max_rotation_deg']:g}°/±{stage_row['stage_max_translation_cm']:g}cm"
            _panel(axes[row_idx, col_idx], image, pixels, depths, title)

    fig.tight_layout()
    output_path.parent.mkdir(parents=True, exist_ok=True)
    fig.savefig(output_path, dpi=150)
    plt.close(fig)
    return output_path


def _parse_example(spec: str) -> tuple[str, int, Path]:
    sequence, frame, assets_path = spec.split(":", 2)
    return sequence, int(frame), Path(assets_path)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--metadata-parquet", required=True)
    parser.add_argument("--examples", nargs="+", required=True, help="sequence:frame:assets_parquet_path")
    parser.add_argument("--stages", default="1,3,5")
    parser.add_argument("--output", default="docs/assets/gallery.png")
    args = parser.parse_args()

    examples = [_parse_example(s) for s in args.examples]
    stages = [int(s) for s in args.stages.split(",")]
    output_path = make_gallery(Path(args.metadata_parquet), examples, stages, Path(args.output))
    print(f"wrote {output_path}")
    return 0


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