#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ UE4-Stereo -- continuous-velocity acquisition (Scenes 3 and 4). Flies a closed-loop route in Unreal Engine 4.27 / Microsoft AirSim, recording synchronized stereo RGB images, planar metric depth and 6-DoF poses. Motion is driven by continuous velocity commands with the heading interpolated along each segment and limited by a maximum yaw rate, so the vehicle never stops at a waypoint. For the stop-and-rotate variant used in Scenes 1 and 2 see `acquire_stepwise.py`. See README.md for the output format, the camera model and the reference-frame conventions. Example: python acquire_continuous.py --output scene_3/sequence01 \ --route route_a_dir1 --baseline 0.24 --rate 10 Requires airsim, numpy and opencv-python, with the simulator already running. """ from __future__ import annotations import argparse import math import os import queue import threading import time from dataclasses import dataclass 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), (19.5, -1, -2.5, -90), (19.5, -15.5, -2.5, 180), (0, -15, -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), (26, 10, -3, -90), (26, 0, -3, 180), (19, 0, -3, -90), (19, -15.5, -3, 180), (1, -15, -3, 90), (0, 0, -3, 0) ], "route_b_dir2": [ (0, 0, -2.5, -90), (0, -15, -2.5, 0), (19.5, -15.5, -2.5, 90), (19.5, -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, -1.5, -2.5, 180), (0, 0, -2.5, 0) ], "route_b_dir2_offset": [ (0, 0, -3, -90), (1, -15, -3, 0), (19, -15.5, -3, 90), (19, 0, -3, 0), (26, 0, -3, 90), (26, 10, -3, 180), (15, 10, -3, 90), (15, 21.3, -3, 180), (11, 21.3, -3, -90), (10.5, -1.5, -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") QUEUE_MAX = 64 # decouples capture from disk writing WRITE_FLUSH_EVERY = 50 # flush the text files every N frames CONTROL_DT = 0.1 # velocity command period, independent of capture # -------------------------------------------------------------------------- # Small helpers # -------------------------------------------------------------------------- @dataclass class FramePacket: ts: str seq_name: str pose: airsim.Pose left_bgr: np.ndarray right_bgr: np.ndarray depth_m: np.ndarray def wrap_angle_deg(a: float) -> float: return (a + 180.0) % 360.0 - 180.0 def step_yaw(current: float, target: float, max_step_deg: float) -> float: err = wrap_angle_deg(target - current) return current + float(np.clip(err, -max_step_deg, max_step_deg)) 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 pose_to_tum_line(ts: str, pose: airsim.Pose) -> str: p, q = pose.position, pose.orientation return (f"{ts} {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") # -------------------------------------------------------------------------- # Capture thread: grabs frames, timestamps them, enqueues them # -------------------------------------------------------------------------- def capture_thread_fn(stop_event: threading.Event, frame_q: "queue.Queue[FramePacket]", capture_dt: float) -> 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), ] seq_counter = 0 next_t = time.perf_counter() while not stop_event.is_set(): now = time.perf_counter() if now < next_t: time.sleep(min(0.001, next_t - now)) continue responses = client.simGetImages(requests) ts_str = f"{time.time():.9f}" pose = client.simGetVehiclePose() left = decode_rgb(responses[0]) right = decode_rgb(responses[1]) depth = decode_depth(responses[2]) if left is None or right is None or depth is None: next_t += capture_dt continue pkt = FramePacket(ts=ts_str, seq_name=f"{seq_counter:06d}", pose=pose, left_bgr=left, right_bgr=right, depth_m=depth) try: frame_q.put(pkt, timeout=0.01) except queue.Full: try: frame_q.get_nowait() frame_q.put(pkt, timeout=0.01) except (queue.Empty, queue.Full): pass seq_counter += 1 next_t += capture_dt def writer_thread_fn(stop_event: threading.Event, frame_q: "queue.Queue[FramePacket]", output_dir: str, depth_visual: bool) -> None: 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") written = 0 while not stop_event.is_set() or not frame_q.empty(): try: pkt = frame_q.get(timeout=0.05) except queue.Empty: continue rel_left = f"left_rgb/{pkt.seq_name}.png" rel_right = f"right_rgb/{pkt.seq_name}.png" rel_depth = f"depth_npy/{pkt.seq_name}.npy" cv2.imwrite(os.path.join(output_dir, rel_left), pkt.left_bgr) cv2.imwrite(os.path.join(output_dir, rel_right), pkt.right_bgr) np.save(os.path.join(output_dir, rel_depth), pkt.depth_m) if depth_visual: preview = cv2.normalize(pkt.depth_m, None, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8U) cv2.imwrite(os.path.join(output_dir, "depth_visual", f"{pkt.seq_name}.png"), preview) gt_file.write(pose_to_tum_line(pkt.ts, pkt.pose)) assoc_rgb.write(f"{pkt.ts} {rel_left} {pkt.ts} {rel_right}\n") assoc_rgbd.write(f"{pkt.ts} {rel_left} {pkt.ts} {rel_depth}\n") written += 1 if written % WRITE_FLUSH_EVERY == 0: gt_file.flush() assoc_rgb.flush() assoc_rgbd.flush() def fly_segment(client: airsim.MultirotorClient, p_start: np.ndarray, p_end: np.ndarray, yaw_start: float, yaw_end: float, z: float, speed: float, yaw_rate_deg_s: float) -> None: """Fly a straight segment while slewing the heading at a bounded rate. Velocity is constant along the direction of travel; a new heading target is issued every CONTROL_DT seconds, clamped so the turn never exceeds `yaw_rate_deg_s`. """ delta = p_end - p_start distance = float(np.linalg.norm(delta)) if distance < 1e-6: return direction = delta / distance steps = max(1, int(math.ceil((distance / max(speed, 1e-6)) / CONTROL_DT))) dt = (distance / max(speed, 1e-6)) / steps max_step = yaw_rate_deg_s * dt vx, vy = float(direction[0] * speed), float(direction[1] * speed) current_yaw = yaw_start for k in range(steps): alpha = (k + 1) / steps yaw_target = yaw_start + wrap_angle_deg(yaw_end - yaw_start) * alpha current_yaw = step_yaw(current_yaw, yaw_target, max_step) client.moveByVelocityZAsync( vx, vy, z, dt, drivetrain=airsim.DrivetrainType.MaxDegreeOfFreedom, yaw_mode=airsim.YawMode(is_rate=False, yaw_or_rate=current_yaw), ).join() def configure_cameras(client: airsim.MultirotorClient, baseline: float, convergence_deg: float) -> None: """Place the pair `baseline` apart, pitched down, toed in by `convergence_deg`.""" 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("--rate", type=float, default=10.0, help="target capture rate in Hz (default: 10)") ap.add_argument("--speed", type=float, default=1.0, help="commanded cruise speed in m/s (default: 1.0)") ap.add_argument("--yaw-rate", type=float, default=18.0, help="maximum yaw rate in deg/s (default: 18)") 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] z = waypoints[0][2] 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() frame_q: "queue.Queue[FramePacket]" = queue.Queue(maxsize=QUEUE_MAX) threads = [ threading.Thread(target=capture_thread_fn, args=(stop_event, frame_q, 1.0 / args.rate), daemon=True), threading.Thread(target=writer_thread_fn, args=(stop_event, frame_q, args.output, args.depth_visual), daemon=True), ] for t in threads: t.start() print(f"Flying '{args.route}' ({len(waypoints)} waypoints) at {args.rate:g} Hz") try: for i in range(len(waypoints) - 1): x0, y0, _, yaw0 = waypoints[i] x1, y1, _, yaw1 = waypoints[i + 1] fly_segment(client, np.array([x0, y0], dtype=np.float32), np.array([x1, y1], dtype=np.float32), yaw0, yaw1, z, args.speed, args.yaw_rate) finally: stop_event.set() for t in threads: t.join() print("Capture finished. Returning home.") client.goHomeAsync().join() client.armDisarm(False) client.enableApiControl(False) if __name__ == "__main__": main()