File size: 5,545 Bytes
be5e288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UE4-Stereo -- example loader.

Reads one sequence and shows how to work with each of its components: the
stereo pair, the metric depth map, the ground-truth trajectory and the camera
parameters. Run it from anywhere, passing the path to a sequence directory:

    python load_sequence.py --sequence path/to/scene_1/sequence01
    python load_sequence.py --sequence . --show 0        # from inside one

Pass --baseline 0.32 for sequences 05 and 06, which use the wider rig.
See README.md for the camera model and the reference-frame conventions.

Requires numpy and opencv-python; matplotlib only for --show.
"""

from __future__ import annotations

import argparse
import os

import cv2
import numpy as np

# Ideal pinhole cameras: intrinsics are exact by construction, not calibrated.
IMAGE_WIDTH = 640
IMAGE_HEIGHT = 480
HFOV_DEG = 90.0

FX = FY = (IMAGE_WIDTH / 2.0) / np.tan(np.radians(HFOV_DEG) / 2.0)
CX, CY = IMAGE_WIDTH / 2.0, IMAGE_HEIGHT / 2.0

# Rig extrinsics relative to the vehicle body frame (NED: +z is down).
CAMERA_FORWARD_M = 1.00
CAMERA_DOWN_M = 0.10
CAMERA_PITCH_DEG = -23.0


def intrinsic_matrix() -> np.ndarray:
    return np.array([[FX, 0.0, CX],
                     [0.0, FY, CY],
                     [0.0, 0.0, 1.0]], dtype=np.float64)


def read_associations(path: str) -> list[tuple[str, str, str, str]]:
    """Parse an associate_*.txt file, skipping the comment header."""
    rows = []
    with open(path, encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            parts = line.split()
            if len(parts) == 4:
                rows.append(tuple(parts))
    return rows


def read_trajectory(path: str) -> np.ndarray:
    return np.loadtxt(path)


def load_frame(sequence: str, index: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:

    stereo = read_associations(os.path.join(sequence, "associate_rgb.txt"))
    rgbd = read_associations(os.path.join(sequence, "associate_rgbd.txt"))

    _, rel_left, _, rel_right = stereo[index]
    _, _, _, rel_depth = rgbd[index]

    left = cv2.imread(os.path.join(sequence, rel_left), cv2.IMREAD_COLOR)
    right = cv2.imread(os.path.join(sequence, rel_right), cv2.IMREAD_COLOR)
    depth = np.load(os.path.join(sequence, rel_depth))
    return left, right, depth


def depth_to_disparity(depth_m: np.ndarray, baseline_m: float) -> np.ndarray:
    disparity = np.zeros_like(depth_m, dtype=np.float32)
    valid = depth_m > 0.0
    disparity[valid] = (FX * baseline_m) / depth_m[valid]
    return disparity


def summarize(sequence: str, baseline_m: float) -> None:
    stereo = read_associations(os.path.join(sequence, "associate_rgb.txt"))
    traj = read_trajectory(os.path.join(sequence, "groundtruth.txt"))
    _, _, depth = load_frame(sequence, 0)
    valid = depth > 0.0

    duration = traj[-1, 0] - traj[0, 0]
    distance = np.linalg.norm(np.diff(traj[:, 1:4], axis=0), axis=1).sum()

    print(f"Sequence:        {sequence}")
    print(f"Stereo pairs:    {len(stereo)}")
    print(f"Poses:           {len(traj)}")
    print(f"Duration:        {duration:.1f} s  ({len(traj) / duration:.2f} Hz)")
    print(f"Path length:     {distance:.1f} m")
    print(f"Altitude:        {-traj[:, 3].mean():.2f} m above spawn (mean)")
    print(f"Image size:      {IMAGE_WIDTH} x {IMAGE_HEIGHT}")
    print(f"fx = fy:         {FX:.1f} px     cx, cy = {CX:.1f}, {CY:.1f} px")
    print(f"Baseline:        {baseline_m:.2f} m     fx*B = {FX * baseline_m:.1f} m.px")
    print(f"Depth (frame 0): {depth[valid].min():.2f} to {depth[valid].max():.2f} m, "
          f"{100 * valid.mean():.1f}% valid")


def show_frame(sequence: str, index: int, baseline_m: float) -> None:
    import matplotlib.pyplot as plt

    left, right, depth = load_frame(sequence, index)
    disparity = depth_to_disparity(depth, baseline_m)

    fig, axes = plt.subplots(2, 2, figsize=(11, 7))
    for ax, img, title in (
        (axes[0, 0], cv2.cvtColor(left, cv2.COLOR_BGR2RGB), "left"),
        (axes[0, 1], cv2.cvtColor(right, cv2.COLOR_BGR2RGB), "right"),
    ):
        ax.imshow(img)
        ax.set_title(title)
        ax.axis("off")

    im = axes[1, 0].imshow(np.where(depth > 0, depth, np.nan), cmap="viridis")
    axes[1, 0].set_title("depth [m]")
    axes[1, 0].axis("off")
    fig.colorbar(im, ax=axes[1, 0], fraction=0.046)

    im = axes[1, 1].imshow(np.where(disparity > 0, disparity, np.nan), cmap="magma")
    axes[1, 1].set_title(f"disparity [px], B = {baseline_m:.2f} m")
    axes[1, 1].axis("off")
    fig.colorbar(im, ax=axes[1, 1], fraction=0.046)

    fig.suptitle(f"{sequence} -- frame {index}")
    fig.tight_layout()
    plt.show()


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--sequence", required=True,
                    help="path to a sequence directory, e.g. scene_1/sequence01")
    ap.add_argument("--baseline", type=float, default=0.24,
                    help="stereo baseline of this sequence in metres (default: 0.24)")
    ap.add_argument("--show", type=int, metavar="N",
                    help="display frame N instead of only printing a summary")
    args = ap.parse_args()

    summarize(args.sequence, args.baseline)
    if args.show is not None:
        show_frame(args.sequence, args.show, args.baseline)


if __name__ == "__main__":
    main()