File size: 15,083 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 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | #!/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()
|