UE4-Stereo / scripts /acquire_stepwise.py
yanmorona's picture
Add acquisition and example scripts
be5e288 verified
Raw History Blame Contribute Delete
10.5 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
UE4-Stereo -- stop-and-rotate acquisition (Scenes 1 and 2).
Flies a closed-loop route in Unreal Engine 4.27 / Microsoft AirSim, recording
synchronized stereo RGB images, planar metric depth and 6-DoF poses.
The vehicle is commanded through successive position and heading targets: it
flies to a waypoint, stops, rotates in place, and only then proceeds.
For the continuous-motion variant used in Scenes 3 and 4 see
`acquire_continuous.py`. See README.md for the output format, the camera model
and the reference-frame conventions.
Example:
python acquire_stepwise.py --output scene_1/sequence01 \
--route route_a_dir1 --baseline 0.24
Requires airsim, numpy and opencv-python, with the simulator already running.
"""
from __future__ import annotations
import argparse
import math
import os
import threading
import time
import airsim
import cv2
import numpy as np
# ---------------------------------------------------------------------------
# Routes. Waypoints are (x, y, z, yaw) in the AirSim world frame: metres, z
# negative upwards, yaw in degrees. "_offset" marks the laterally displaced
# variants; in route_b these are also 0.5 m higher. "_dir2" runs the loop
# backwards.
# ---------------------------------------------------------------------------
ROUTES: dict[str, list[tuple[float, float, float, float]]] = {
"route_a_dir1": [
(0, 0, -2.5, 0),
(17, 0, -2.5, 90),
(17, 12, -2.5, 0),
(28, 12, -2.5, -90),
(28, -14, -2.5, 180),
(0, -14, -2.5, 90),
(0, 0, -2.5, 0)
],
"route_a_dir1_offset": [
(0, 0, -2.5, 0),
(18, 0, -2.5, 90),
(18, 11, -2.5, 0),
(29, 11, -2.5, -90),
(29, -15, -2.5, 180),
(0, -15, -2.5, 90),
(0, 0, -2.5, 0)
],
"route_a_dir2": [
(0, 0, -2.5, -90),
(0, -14, -2.5, 0),
(28, -14, -2.5, 90),
(28, 12, -2.5, 180),
(17, 12, -2.5, -90),
(17, 0, -2.5, 180),
(0, 0, -2.5, 0)
],
"route_a_dir2_offset": [
(0, 0, -2.5, -90),
(0, -15, -2.5, 0),
(29, -15, -2.5, 90),
(29, 11, -2.5, 180),
(18, 11, -2.5, -90),
(18, 0, -2.5, 180),
(0, 0, -2.5, 0)
],
"route_b_dir1": [
(0, 0, -2.5, 0),
(10.5, 0, -2.5, 90),
(10.5, 21.3, -2.5, 0),
(16, 21.3, -2.5, -90),
(16, 11, -2.5, 0),
(27, 11, -2.5, -90),
(27, -1, -2.5, 180),
(20, -1, -2.5, -90),
(20, -15.5, -2.5, 180),
(0, -15.5, -2.5, 90),
(0, 0, -2.5, 0)
],
"route_b_dir1_offset": [
(0, 0, -3, 0),
(11, 0, -3, 90),
(11, 21.3, -3, 0),
(15, 21.3, -3, -90),
(15, 10, -3, 0),
(28, 10, -3, -90),
(28, 0, -3, 180),
(19, 0, -3, -90),
(19, -15.5, -3, 180),
(1, -15.5, -3, 90),
(0, 0, -3, 0)
],
"route_b_dir2": [
(0, 0, -2.5, -90),
(0, -15.5, -2.5, 0),
(20, -15.5, -2.5, 90),
(20, -1, -2.5, 0),
(27, -1, -2.5, 90),
(27, 11, -2.5, 180),
(16, 11, -2.5, 90),
(16, 21.3, -2.5, 180),
(10.5, 21.3, -2.5, -90),
(10.5, 0, -2.5, 180),
(0, 0, -2.5, 0)
],
"route_b_dir2_offset": [
(0, 0, -3, -90),
(1, -15.5, -3, 0),
(19, -15.5, -3, 90),
(19, 0, -3, 0),
(28, 0, -3, 90),
(28, 10, -3, 180),
(15, 10, -3, 90),
(15, 21.3, -3, 180),
(11, 21.3, -3, -90),
(11, 1, -3, 180),
(0, 0, -3, 0)
],
}
# --------------------------------------------------------------------------
# Rig extrinsics (relative to the vehicle body frame, NED: +z is down)
# --------------------------------------------------------------------------
CAMERA_FORWARD_M = 1.00 # x offset of both cameras
CAMERA_DOWN_M = 0.10 # z offset of both cameras
CAMERA_PITCH_DEG = -23.0 # both cameras tilt downwards by this angle
SUBFOLDERS = ("left_rgb", "right_rgb", "depth_npy", "depth_visual")
MOVE_SPEED_MPS = 1.0 # speed passed to moveToPositionAsync
ROTATE_SPEED_DPS = 2.0 # rotation rate passed to rotateToYawAsync
def decode_rgb(response) -> np.ndarray | None:
if response.width <= 0 or response.height <= 0:
return None
return np.frombuffer(response.image_data_uint8, dtype=np.uint8).reshape(
response.height, response.width, 3)
def decode_depth(response) -> np.ndarray | None:
if response.width <= 0 or response.height <= 0:
return None
depth = np.array(response.image_data_float, dtype=np.float32).reshape(
response.height, response.width)
return np.nan_to_num(depth, nan=0.0, posinf=0.0, neginf=0.0)
def capture_loop(stop_event: threading.Event, output_dir: str,
period_s: float, depth_visual: bool) -> None:
client = airsim.MultirotorClient()
client.confirmConnection()
requests = [
airsim.ImageRequest("front-left", airsim.ImageType.Scene,
pixels_as_float=False, compress=False),
airsim.ImageRequest("front-right", airsim.ImageType.Scene,
pixels_as_float=False, compress=False),
airsim.ImageRequest("front-left", airsim.ImageType.DepthPlanar,
pixels_as_float=True, compress=False),
]
gt_path = os.path.join(output_dir, "groundtruth.txt")
rgb_path = os.path.join(output_dir, "associate_rgb.txt")
rgbd_path = os.path.join(output_dir, "associate_rgbd.txt")
with open(gt_path, "w", encoding="utf-8") as gt_file, \
open(rgb_path, "w", encoding="utf-8") as assoc_rgb, \
open(rgbd_path, "w", encoding="utf-8") as assoc_rgbd:
gt_file.write("# timestamp tx ty tz qx qy qz qw\n")
assoc_rgb.write("# timestamp_left left_image timestamp_right right_image\n")
assoc_rgbd.write("# timestamp_left left_image timestamp_depth depth_image\n")
seq_counter = 0
while not stop_event.is_set():
ts_str = f"{time.time():.9f}"
pose = client.simGetVehiclePose()
p, q = pose.position, pose.orientation
gt_file.write(
f"{ts_str} {p.x_val:.6f} {p.y_val:.6f} {p.z_val:.6f} "
f"{q.x_val:.6f} {q.y_val:.6f} {q.z_val:.6f} {q.w_val:.6f}\n")
responses = client.simGetImages(requests)
seq_name = f"{seq_counter:06d}"
rel_left = f"left_rgb/{seq_name}.png"
rel_right = f"right_rgb/{seq_name}.png"
rel_depth = f"depth_npy/{seq_name}.npy"
left = decode_rgb(responses[0])
if left is not None:
cv2.imwrite(os.path.join(output_dir, rel_left), left)
right = decode_rgb(responses[1])
if right is not None:
cv2.imwrite(os.path.join(output_dir, rel_right), right)
depth = decode_depth(responses[2])
if depth is not None:
np.save(os.path.join(output_dir, rel_depth), depth)
if depth_visual:
preview = cv2.normalize(depth, None, 0, 255,
cv2.NORM_MINMAX, dtype=cv2.CV_8U)
cv2.imwrite(os.path.join(output_dir, "depth_visual",
f"{seq_name}.png"), preview)
assoc_rgb.write(f"{ts_str} {rel_left} {ts_str} {rel_right}\n")
assoc_rgbd.write(f"{ts_str} {rel_left} {ts_str} {rel_depth}\n")
seq_counter += 1
time.sleep(period_s)
def configure_cameras(client: airsim.MultirotorClient,
baseline: float, convergence_deg: float) -> None:
half = baseline / 2.0
pitch = math.radians(CAMERA_PITCH_DEG)
toe = math.radians(convergence_deg)
client.simSetCameraPose("front-left", airsim.Pose(
airsim.Vector3r(CAMERA_FORWARD_M, -half, CAMERA_DOWN_M),
airsim.to_quaternion(pitch, 0.0, toe)))
client.simSetCameraPose("front-right", airsim.Pose(
airsim.Vector3r(CAMERA_FORWARD_M, half, CAMERA_DOWN_M),
airsim.to_quaternion(pitch, 0.0, -toe)))
def parse_args() -> argparse.Namespace:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--output", required=True,
help="directory for this sequence; created if absent")
ap.add_argument("--route", required=True, choices=sorted(ROUTES),
help="route to fly")
ap.add_argument("--baseline", type=float, default=0.24,
help="stereo baseline in metres (default: 0.24)")
ap.add_argument("--convergence", type=float, default=0.0,
help="inward toe-in per camera in degrees (default: 0, parallel)")
ap.add_argument("--period", type=float, default=0.1,
help="sleep between capture iterations in seconds "
"(default: 0.1; the achieved rate is lower)")
ap.add_argument("--depth-visual", action="store_true",
help="also write 8-bit depth previews (not metric)")
return ap.parse_args()
def main() -> None:
args = parse_args()
for sub in SUBFOLDERS:
if sub == "depth_visual" and not args.depth_visual:
continue
os.makedirs(os.path.join(args.output, sub), exist_ok=True)
waypoints = ROUTES[args.route]
client = airsim.MultirotorClient()
client.confirmConnection()
client.enableApiControl(True)
client.armDisarm(True)
client.takeoffAsync().join()
configure_cameras(client, args.baseline, args.convergence)
stop_event = threading.Event()
capture_thread = threading.Thread(
target=capture_loop,
args=(stop_event, args.output, args.period, args.depth_visual),
daemon=True)
capture_thread.start()
print(f"Flying '{args.route}' ({len(waypoints)} waypoints)")
try:
for x, y, z, yaw in waypoints:
client.moveToPositionAsync(x, y, z, MOVE_SPEED_MPS).join()
client.rotateToYawAsync(yaw, ROTATE_SPEED_DPS).join()
finally:
stop_event.set()
capture_thread.join()
print("Capture finished. Returning home.")
client.goHomeAsync().join()
client.armDisarm(False)
client.enableApiControl(False)
if __name__ == "__main__":
main()