UE4-Stereo / scripts /load_sequence.py
yanmorona's picture
Add acquisition and example scripts
be5e288 verified
Raw History Blame Contribute Delete
5.55 kB
#!/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()