File size: 7,046 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
163
164
165
166
167
168
169
170
171
172
173
174
#!/usr/bin/env python
"""Visualizes LiDAR->camera projection under ground-truth vs. decalibrated extrinsics.

For a chosen (sequence, frame), plots the LiDAR point cloud projected onto the
camera image side by side: ground truth on the left, one panel per selected
decalibration stage on the right, points colored by depth. Useful both as a
sanity check while generating the dataset and as a quick way to see how
severe each difficulty stage actually looks.

Requires the `viz` extra: pip install kitti-c2l[viz]

Usage:
    # Every stage found for one frame
    python scripts/visualize_projection.py --parquet data/train.parquet \\
        --kitti-raw-root /path/to/KITTI --sequence 01 --frame 0 --output overlay.png

    # A single specific row
    python scripts/visualize_projection.py --parquet data/train.parquet \\
        --kitti-raw-root /path/to/KITTI --sample-id 01_000000_stage1 --output overlay.png

    # Only stages 1 and 5, for a quick easy-vs-hard comparison
    python scripts/visualize_projection.py --parquet data/train.parquet \\
        --kitti-raw-root /path/to/KITTI --sequence 04 --frame 3 --stages 1,5 --output overlay.png
"""

from __future__ import annotations

import argparse
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

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 load_image, load_points_cm, row_extrinsic  # noqa: E402

MIN_DEPTH_CM = 200.0
MAX_DEPTH_CM = 8000.0


def _select_rows(
    table_rows: list[dict],
    sample_id: str | None,
    sequence: str | None,
    frame: int | None,
    stages: set[int] | None,
) -> list[dict]:
    if sample_id is not None:
        matches = [r for r in table_rows if r["sample_id"] == sample_id]
        if not matches:
            raise ValueError(f"No row with sample_id={sample_id!r}")
        return matches

    if sequence is not None and frame is not None:
        matches = [r for r in table_rows if r["sequence"] == sequence and r["frame_index"] == frame]
        if not matches:
            raise ValueError(f"No rows for sequence={sequence!r}, frame={frame}")
        if stages is not None:
            matches = [r for r in matches if r["stage"] in stages]
            if not matches:
                raise ValueError(f"No rows for sequence={sequence!r}, frame={frame}, stages={sorted(stages)}")
        return sorted(matches, key=lambda r: r["stage"])

    print("No --sample-id or --sequence/--frame given; using the first row in the file.", file=sys.stderr)
    return table_rows[:1]


def _project_valid(
    points_cm: np.ndarray, rotation: np.ndarray, translation_cm: np.ndarray, intrinsics: np.ndarray, width: int, height: int
) -> tuple[np.ndarray, np.ndarray]:
    """Returns (pixels (M, 2), depths_cm (M,)) for points that land in-frame within the valid depth range."""
    points_cam = transform_points(points_cm, rotation, translation_cm)
    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 _plot_panel(ax, image: np.ndarray, pixels: np.ndarray, depths: np.ndarray, title: str) -> None:
    ax.imshow(image)
    if pixels.shape[0] > 0:
        order = np.argsort(-depths)  # far first, so near points draw on top
        scatter = ax.scatter(
            pixels[order, 0], pixels[order, 1], c=depths[order] / 100.0, cmap="turbo", s=3, alpha=0.85
        )
        plt.colorbar(scatter, ax=ax, fraction=0.03, pad=0.01, label="depth (m)")
    ax.set_title(title, fontsize=9)
    ax.axis("off")


def visualize(
    parquet_path: str | Path,
    kitti_raw_root: str | Path,
    output_path: str | Path,
    sample_id: str | None = None,
    sequence: str | None = None,
    frame: int | None = None,
    stages: set[int] | None = None,
) -> Path:
    table_rows = pq.read_table(parquet_path).to_pylist()
    rows = _select_rows(table_rows, sample_id, sequence, frame, stages)

    n_cols = 1 + len(rows)  # ground truth + one panel per selected (sequence, frame, stage) row
    fig, axes = plt.subplots(1, n_cols, figsize=(5 * n_cols, 5))
    if n_cols == 1:
        axes = [axes]

    first_row = rows[0]
    image = load_image(kitti_raw_root, first_row)
    points_cm = load_points_cm(kitti_raw_root, first_row)
    width, height = int(first_row["image_width"]), int(first_row["image_height"])

    gt_rotation, gt_translation = row_extrinsic(first_row, use_ground_truth=True)
    gt_pixels, gt_depths = _project_valid(points_cm, gt_rotation, gt_translation, np.array(first_row["camera_intrinsics"]).reshape(3, 3), width, height)
    _plot_panel(axes[0], image, gt_pixels, gt_depths, f"Ground truth\nseq {first_row['sequence']} frame {first_row['frame_index']}")

    for ax, row in zip(axes[1:], rows, strict=True):
        rotation, translation = row_extrinsic(row, use_ground_truth=False)
        intrinsics = np.array(row["camera_intrinsics"]).reshape(3, 3)
        pixels, depths = _project_valid(points_cm, rotation, translation, intrinsics, width, height)
        title = f"Stage {row['stage']} (±{row['stage_max_rotation_deg']:g}°/±{row['stage_max_translation_cm']:g}cm)"
        _plot_panel(ax, image, pixels, depths, title)

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


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--parquet", required=True, help="Path to a published {split}.parquet file.")
    parser.add_argument("--kitti-raw-root", required=True, help="Local KITTI raw root, see README.md.")
    parser.add_argument("--output", default="projection.png")
    parser.add_argument("--sample-id", default=None, help="Exact sample_id, e.g. 01_000000_stage1.")
    parser.add_argument("--sequence", default=None, help="Sequence id, e.g. 01. Use with --frame.")
    parser.add_argument("--frame", type=int, default=None, help="0-based frame index within the sequence.")
    parser.add_argument("--stages", default=None, help="Comma-separated stage ids to show, e.g. 1,5 (default: all found).")
    args = parser.parse_args()

    stages = {int(s) for s in args.stages.split(",")} if args.stages else None
    output_path = visualize(
        args.parquet,
        args.kitti_raw_root,
        args.output,
        sample_id=args.sample_id,
        sequence=args.sequence,
        frame=args.frame,
        stages=stages,
    )
    print(f"wrote {output_path}")
    return 0


if __name__ == "__main__":
    sys.exit(main())