File size: 10,533 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 | #!/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()
|