From 5e17def23349e4a68aed7392149b8d1e7b27abd4 Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:46:39 +0530 Subject: [PATCH 1/6] Add files via upload --- PyFlyt/core/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/PyFlyt/core/__init__.py b/PyFlyt/core/__init__.py index 76346815..0c6d5a1a 100644 --- a/PyFlyt/core/__init__.py +++ b/PyFlyt/core/__init__.py @@ -1,4 +1,5 @@ """Class implementations for creating custom UAVs in the PyBullet simulation environment.""" from .aviary import Aviary +from .utils.camera_recorder import CameraRecorder from .utils.load_objs import loadOBJ, obj_collision, obj_visual From 9083d33d1a47e9ff812f5464ba3233141bb9754f Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:47:03 +0530 Subject: [PATCH 2/6] Add files via upload --- PyFlyt/core/utils/camera_recorder.py | 337 +++++++++++++++++++++++++++ 1 file changed, 337 insertions(+) create mode 100644 PyFlyt/core/utils/camera_recorder.py diff --git a/PyFlyt/core/utils/camera_recorder.py b/PyFlyt/core/utils/camera_recorder.py new file mode 100644 index 00000000..32b43b3b --- /dev/null +++ b/PyFlyt/core/utils/camera_recorder.py @@ -0,0 +1,337 @@ +"""Record a drone's onboard camera together with the exact camera pose. + +`CameraRecorder` writes a posed image sequence from the `Camera` component of a drone: + + / + images/000000.png, 000001.png, ... + depth/000000.npy, ... (optional, metric z-depth in metres, float32) + poses.csv timestamp,tx,ty,tz,qx,qy,qz,qw + intrinsics.txt fx fy cx cy + +Each row of `poses.csv` is the camera-to-world transform of the matching image, +with camera axes in the OpenCV convention (x right, y down, z forward) and the +PyBullet world frame (z up). Timestamps are simulation time in seconds. + +The pose is obtained by inverting the same view matrix that is used to render +the image, so it follows every `Camera` option (gimbal, tilt angle, position +offset, tracking camera) and pose and pixels are consistent by construction. +Images are always rendered with `ER_TINY_RENDERER`, so the intrinsics are the +same with and without `render=True`. + +This layout can be read by most visual odometry, SLAM, NeRF / Gaussian-splatting +and world-model training pipelines. +""" + +from __future__ import annotations + +import csv +import os +import struct +import zlib + +import numpy as np +import pybullet as p + +# OpenGL eye axes (x right, y up, z backward) from OpenCV camera axes +_GL_FROM_CV = np.diag([1.0, -1.0, -1.0, 1.0]) + + +def view_matrix_to_camera_pose(view_matrix) -> np.ndarray: + """Converts a PyBullet view matrix into an OpenCV camera-to-world pose. + + Args: + view_matrix: 16 floats, column-major, e.g. from `computeViewMatrix`. + + Returns: + np.ndarray: (4, 4) camera-to-world transform with OpenCV camera axes. + + """ + view = np.asarray(view_matrix, dtype=np.float64).reshape(4, 4, order="F") + return np.linalg.inv(view) @ _GL_FROM_CV + + +def camera_pose_to_view_matrix(T_wc: np.ndarray) -> list[float]: + """Converts an OpenCV camera-to-world pose into a PyBullet view matrix. + + Args: + T_wc (np.ndarray): (4, 4) camera-to-world transform with OpenCV camera axes. + + Returns: + list[float]: 16 floats, column-major. + + """ + view = np.linalg.inv(np.asarray(T_wc, dtype=np.float64) @ _GL_FROM_CV) + return view.flatten(order="F").tolist() + + +def projection_matrix_to_intrinsics( + projection_matrix, width: int, height: int, tiny_renderer: bool = True +) -> tuple[np.ndarray, float, float]: + """Extracts pinhole intrinsics and clipping planes from a PyBullet projection matrix. + + PyBullet's TinyRenderer samples pixels half a pixel away from the ideal OpenGL + convention: its principal point is at (W/2, H/2 - 1) instead of ((W-1)/2, (H-1)/2). + + Args: + projection_matrix: 16 floats, column-major, e.g. from `computeProjectionMatrixFOV`. + width (int): image width in pixels. + height (int): image height in pixels. + tiny_renderer (bool): whether images are rendered with `ER_TINY_RENDERER`. + + Returns: + tuple[np.ndarray, float, float]: (3, 3) intrinsics matrix K (pixel centres at integer coordinates), near plane, far plane. + + """ + P = np.asarray(projection_matrix, dtype=np.float64).reshape(4, 4, order="F") + fx = P[0, 0] * width / 2.0 + fy = P[1, 1] * height / 2.0 + cx = (1.0 - P[0, 2]) * width / 2.0 - 0.5 + cy = (1.0 + P[1, 2]) * height / 2.0 - 0.5 + if tiny_renderer: + cx, cy = cx + 0.5, cy - 0.5 + near = P[2, 3] / (P[2, 2] - 1.0) + far = P[2, 3] / (P[2, 2] + 1.0) + K = np.array([[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]]) + return K, float(near), float(far) + + +def depth_buffer_to_metric( + depth_buffer: np.ndarray, near: float, far: float +) -> np.ndarray: + """Converts a PyBullet depth buffer (values in [0, 1]) into metric z-depth. + + Args: + depth_buffer (np.ndarray): depth buffer returned by `getCameraImage`. + near (float): near clipping plane. + far (float): far clipping plane. + + Returns: + np.ndarray: distance along the camera's optical axis in metres. + + """ + depth_buffer = np.asarray(depth_buffer, dtype=np.float64) + return far * near / (far - (far - near) * depth_buffer) + + +def rotation_matrix_to_quat_xyzw(R: np.ndarray) -> np.ndarray: + """Converts a rotation matrix into a unit quaternion [x, y, z, w] with w >= 0. + + Args: + R (np.ndarray): (3, 3) rotation matrix. + + Returns: + np.ndarray: (4,) quaternion. + + """ + m = np.asarray(R, dtype=np.float64) + tr = np.trace(m) + if tr > 0.0: + s = 2.0 * np.sqrt(tr + 1.0) + q = [ + (m[2, 1] - m[1, 2]) / s, + (m[0, 2] - m[2, 0]) / s, + (m[1, 0] - m[0, 1]) / s, + 0.25 * s, + ] + elif m[0, 0] > m[1, 1] and m[0, 0] > m[2, 2]: + s = 2.0 * np.sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]) + q = [ + 0.25 * s, + (m[0, 1] + m[1, 0]) / s, + (m[0, 2] + m[2, 0]) / s, + (m[2, 1] - m[1, 2]) / s, + ] + elif m[1, 1] > m[2, 2]: + s = 2.0 * np.sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]) + q = [ + (m[0, 1] + m[1, 0]) / s, + 0.25 * s, + (m[1, 2] + m[2, 1]) / s, + (m[0, 2] - m[2, 0]) / s, + ] + else: + s = 2.0 * np.sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]) + q = [ + (m[0, 2] + m[2, 0]) / s, + (m[1, 2] + m[2, 1]) / s, + 0.25 * s, + (m[1, 0] - m[0, 1]) / s, + ] + q = np.array(q) + q /= np.linalg.norm(q) + return q if q[3] >= 0.0 else -q + + +def write_png(path: str, image: np.ndarray) -> None: + """Writes an 8-bit RGB or grayscale image as PNG without extra dependencies. + + Args: + path (str): output file path. + image (np.ndarray): (H, W, 3) or (H, W) uint8 array. + + """ + image = np.ascontiguousarray(image, dtype=np.uint8) + height, width = image.shape[:2] + color_type = 2 if image.ndim == 3 else 0 + rows = image.reshape(height, -1) + raw = np.hstack([np.zeros((height, 1), dtype=np.uint8), rows]).tobytes() + + def chunk(tag: bytes, data: bytes) -> bytes: + return ( + struct.pack(">I", len(data)) + + tag + + data + + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + ) + + with open(path, "wb") as f: + f.write(b"\x89PNG\r\n\x1a\n") + f.write( + chunk( + b"IHDR", struct.pack(">IIBBBBB", width, height, 8, color_type, 0, 0, 0) + ) + ) + f.write(chunk(b"IDAT", zlib.compress(raw, 6))) + f.write(chunk(b"IEND", b"")) + + +class CameraRecorder: + """Saves posed images from the onboard `Camera` of a drone in an `Aviary`. + + The drone must be created with `use_camera=True`. Call `capture()` whenever a + frame should be saved, typically every few `env.step()` calls. + + Example: + ```python + env = Aviary(..., drone_options=dict(use_camera=True)) + with CameraRecorder(env, "flight_0") as rec: + for i in range(1000): + env.step() + if i % 12 == 0: + rec.capture() + ``` + + Args: + aviary: the `Aviary` instance. + output_dir (str): directory where the sequence is written (created if missing). + drone_index (int): index of the drone in `aviary.drones`. + save_depth (bool): whether to also save metric depth maps as `.npy` files. + + """ + + def __init__( + self, + aviary, + output_dir: str, + drone_index: int = 0, + save_depth: bool = False, + ): + """Initializes the recorder and writes `intrinsics.txt`. + + Args: + aviary: the `Aviary` instance. + output_dir (str): directory where the sequence is written (created if missing). + drone_index (int): index of the drone in `aviary.drones`. + save_depth (bool): whether to also save metric depth maps as `.npy` files. + + """ + self.aviary = aviary + self.drone_index = drone_index + drone = aviary.drones[drone_index] + if not getattr(drone, "use_camera", False): + raise ValueError( + "CameraRecorder needs a drone created with `use_camera=True` in `drone_options`." + ) + self.camera = drone.camera + self.height, self.width = (int(v) for v in self.camera.camera_resolution) + self.K, self.near, self.far = projection_matrix_to_intrinsics( + self.camera.proj_mat, self.width, self.height + ) + self.save_depth = save_depth + + self.output_dir = output_dir + os.makedirs(os.path.join(output_dir, "images"), exist_ok=True) + if save_depth: + os.makedirs(os.path.join(output_dir, "depth"), exist_ok=True) + np.savetxt( + os.path.join(output_dir, "intrinsics.txt"), + self.K[[0, 1, 0, 1], [0, 1, 2, 2]][None], + fmt="%.6f", + header="fx fy cx cy", + ) + self._csv_file = open(os.path.join(output_dir, "poses.csv"), "w", newline="") + self._csv = csv.writer(self._csv_file) + self._csv.writerow(["timestamp", "tx", "ty", "tz", "qx", "qy", "qz", "qw"]) + self.frame_count = 0 + + def camera_pose(self) -> np.ndarray: + """Returns the current camera-to-world transform with OpenCV camera axes. + + Returns: + np.ndarray: (4, 4) transform. + + """ + return view_matrix_to_camera_pose(self.camera.view_mat) + + def capture(self, timestamp: float | None = None) -> tuple[np.ndarray, np.ndarray]: + """Renders one frame, writes it to disk and appends its pose. + + Args: + timestamp (float | None): time stamp in seconds, defaults to `aviary.elapsed_time`. + + Returns: + tuple[np.ndarray, np.ndarray]: (H, W, 3) uint8 RGB image, (4, 4) camera-to-world transform. + + """ + view = self.camera.view_mat + T_wc = view_matrix_to_camera_pose(view) + if timestamp is None: + timestamp = float(self.aviary.elapsed_time) + + _, _, rgba, depth_buffer, _ = self.aviary.getCameraImage( + width=self.width, + height=self.height, + viewMatrix=view, + projectionMatrix=self.camera.proj_mat, + flags=p.ER_NO_SEGMENTATION_MASK, + renderer=p.ER_TINY_RENDERER, + ) + rgb = np.asarray(rgba, dtype=np.uint8).reshape(self.height, self.width, 4)[ + ..., :3 + ] + + name = f"{self.frame_count:06d}" + write_png(os.path.join(self.output_dir, "images", name + ".png"), rgb) + if self.save_depth: + depth = depth_buffer_to_metric( + np.reshape(depth_buffer, (self.height, self.width)), + self.near, + self.far, + ) + np.save( + os.path.join(self.output_dir, "depth", name + ".npy"), + depth.astype(np.float32), + ) + + quat = rotation_matrix_to_quat_xyzw(T_wc[:3, :3]) + self._csv.writerow( + [f"{timestamp:.6f}"] + + [f"{v:.9f}" for v in T_wc[:3, 3]] + + [f"{v:.9f}" for v in quat] + ) + self._csv_file.flush() + self.frame_count += 1 + return rgb, T_wc + + def close(self) -> None: + """Closes the pose file.""" + if not self._csv_file.closed: + self._csv_file.close() + + def __enter__(self) -> CameraRecorder: + """Enters a context that closes the recorder on exit.""" + return self + + def __exit__(self, *exc) -> None: + """Closes the recorder.""" + self.close() From 04386df72a41ed4a037606384da8de08a45582b0 Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:48:06 +0530 Subject: [PATCH 3/6] Add files via upload --- examples/core/11_camera_recording.py | 62 ++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 examples/core/11_camera_recording.py diff --git a/examples/core/11_camera_recording.py b/examples/core/11_camera_recording.py new file mode 100644 index 00000000..996dc157 --- /dev/null +++ b/examples/core/11_camera_recording.py @@ -0,0 +1,62 @@ +"""Fly a drone around a circle and record its camera with exact camera poses. + +The output folder holds `images/`, `depth/`, `poses.csv` (camera-to-world, +OpenCV camera axes) and `intrinsics.txt`, which can be used for visual odometry, +SLAM, novel-view synthesis or world-model training. +""" + +import numpy as np + +from PyFlyt.core import Aviary, CameraRecorder + +# the starting position and orientations +start_pos = np.array([[1.0, 0.0, 1.0]]) +start_orn = np.array([[0.0, 0.0, np.pi / 2]]) + +# environment setup, a forward-facing camera tilted 20 degrees towards the ground +env = Aviary( + start_pos=start_pos, + start_orn=start_orn, + render=False, + drone_type="quadx", + drone_options=dict( + use_camera=True, + camera_angle_degrees=20, + camera_FOV_degrees=90, + camera_resolution=(240, 320), + camera_fps=10, + ), +) + +# add some things to look at +for x, y in [(2.5, 0.0), (0.0, 2.5), (-2.5, 0.0), (0.0, -2.5)]: + env.loadURDF("duck_vhacd.urdf", basePosition=[x, y, 0.0], globalScaling=10.0) + +# call this to register all new bodies for collision +env.register_all_new_bodies() + +# set to position control +env.set_mode(7) + +# fly one climbing circle in 20 seconds while facing the direction of travel, +# saving a frame at 10 Hz (the default control rate is 120 Hz) +num_steps = 20 * 120 +with CameraRecorder(env, "camera_recording", save_depth=True) as recorder: + for i in range(num_steps): + theta = 2 * np.pi * i / num_steps + height = 1.0 + 0.5 * np.sin(theta) + + # the yaw setpoint is not wrapped by the controller, + # so command the heading relative to the current yaw + yaw = env.state(0)[1, 2] + yaw_error = (theta + np.pi / 2 - yaw + np.pi) % (2 * np.pi) - np.pi + env.set_setpoint( + 0, np.array([np.cos(theta), np.sin(theta), yaw + yaw_error, height]) + ) + env.step() + + if i % 12 == 0: + recorder.capture() + +print(f"Saved {recorder.frame_count} posed frames to camera_recording/") +env.disconnect() From a490e70b772b0a05b1b01a862ece8bd381aeb0f0 Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:48:28 +0530 Subject: [PATCH 4/6] Add files via upload --- tests/test_camera_recorder.py | 162 ++++++++++++++++++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 tests/test_camera_recorder.py diff --git a/tests/test_camera_recorder.py b/tests/test_camera_recorder.py new file mode 100644 index 00000000..df803627 --- /dev/null +++ b/tests/test_camera_recorder.py @@ -0,0 +1,162 @@ +"""Tests the posed camera recorder.""" + +from __future__ import annotations + +import os + +import numpy as np +import pybullet as p +import pytest + +from PyFlyt.core import Aviary +from PyFlyt.core.utils.camera_recorder import ( + CameraRecorder, + camera_pose_to_view_matrix, + rotation_matrix_to_quat_xyzw, + view_matrix_to_camera_pose, +) + + +def _quat_to_R(q) -> np.ndarray: + return np.array(p.getMatrixFromQuaternion(q)).reshape(3, 3) + + +def _make_env(**camera_options) -> Aviary: + options = dict(use_camera=True, camera_resolution=(240, 320)) + options.update(camera_options) + return Aviary( + start_pos=np.array([[0.0, 0.0, 1.0]]), + start_orn=np.zeros((1, 3)), + render=False, + drone_type="quadx", + drone_options=options, + ) + + +def test_view_matrix_round_trip(): + """Pose -> view matrix -> pose is the identity.""" + rng = np.random.default_rng(0) + for _ in range(10): + T = np.eye(4) + T[:3, :3] = _quat_to_R( + p.getQuaternionFromEuler(rng.uniform(-np.pi, np.pi, 3).tolist()) + ) + T[:3, 3] = rng.uniform(-5, 5, 3) + np.testing.assert_allclose( + view_matrix_to_camera_pose(camera_pose_to_view_matrix(T)), T, atol=1e-9 + ) + q = rotation_matrix_to_quat_xyzw(T[:3, :3]) + np.testing.assert_allclose(_quat_to_R(q.tolist()), T[:3, :3], atol=1e-9) + + +@pytest.mark.parametrize( + "camera_options,rpy_deg", + [ + (dict(), (0.0, 0.0, 0.0)), + (dict(camera_angle_degrees=20), (25.0, -15.0, 70.0)), + ( + dict(camera_position_offset=np.array([0.1, 0.0, 0.05])), + (-30.0, 10.0, -120.0), + ), + (dict(use_gimbal=True, camera_angle_degrees=30), (20.0, 15.0, 40.0)), + ], +) +def test_logged_pose_matches_rendered_pixels(tmp_path, camera_options, rpy_deg): + """Projecting a known sphere with the logged pose and intrinsics lands on its rendered pixels.""" + env = _make_env(**camera_options) + radius = 0.1 + rec = CameraRecorder(env, str(tmp_path), save_depth=True) + H, W = rec.height, rec.width + + env.resetBasePositionAndOrientation( + env.drones[0].Id, + [0.3, -0.2, 1.0], + p.getQuaternionFromEuler(np.deg2rad(rpy_deg).tolist()), + ) + env.stepSimulation() # refresh link states used by the camera + T_wc = rec.camera_pose() + + # place a sphere 1.5 m ahead of the camera, off the optical axis + target = T_wc[:3, :3] @ np.array([0.2, -0.1, 1.5]) + T_wc[:3, 3] + sphere = env.createMultiBody( + 0, + env.createCollisionShape(p.GEOM_SPHERE, radius=radius), + env.createVisualShape(p.GEOM_SPHERE, radius=radius), + target.tolist(), + ) + + _, T_logged = rec.capture() + rec.close() + np.testing.assert_allclose(T_logged, T_wc) + + # segmentation rendered with the same matrices + _, _, _, _, seg = env.getCameraImage( + width=W, + height=H, + viewMatrix=camera_pose_to_view_matrix(T_wc), + projectionMatrix=rec.camera.proj_mat, + renderer=p.ER_TINY_RENDERER, + ) + v, u = np.nonzero(np.reshape(seg, (H, W)) == sphere) + assert len(u) > 10 + observed = np.array([u.mean(), v.mean()]) + + # re-read everything from disk, as a downstream user would + fx, fy, cx, cy = np.loadtxt(tmp_path / "intrinsics.txt") + row = np.genfromtxt(tmp_path / "poses.csv", delimiter=",", names=True) + R = _quat_to_R([row["qx"], row["qy"], row["qz"], row["qw"]]) + t = np.array([row["tx"], row["ty"], row["tz"]]) + x_c = R.T @ (target - t) + predicted = np.array([fx * x_c[0] / x_c[2] + cx, fy * x_c[1] / x_c[2] + cy]) + np.testing.assert_allclose(observed, predicted, atol=0.3) + + # metric depth at the sphere's centre is its near surface + depth = np.load(tmp_path / "depth" / "000000.npy") + d = depth[int(round(predicted[1])), int(round(predicted[0]))] + assert abs(d - (x_c[2] - radius * x_c[2] / np.linalg.norm(x_c))) < 0.01 + + # a gimballed camera keeps a level horizon: its x axis stays horizontal + if camera_options.get("use_gimbal"): + assert abs(T_wc[2, 0]) < 1e-6 + + env.disconnect() + + +def test_requires_camera(tmp_path): + """A drone without a camera is rejected.""" + env = Aviary( + start_pos=np.array([[0.0, 0.0, 1.0]]), + start_orn=np.zeros((1, 3)), + render=False, + drone_type="quadx", + ) + with pytest.raises(ValueError): + CameraRecorder(env, str(tmp_path)) + env.disconnect() + + +def test_recorded_flight(tmp_path): + """A short flight produces one image per pose, with increasing timestamps.""" + env = _make_env(camera_fps=24) + env.set_mode(7) + env.set_setpoint(0, np.array([1.0, 0.5, 0.5, 1.5])) + with CameraRecorder(env, str(tmp_path)) as rec: + for i in range(240): + env.step() + if i % 10 == 0: + rec.capture() + env.disconnect() + + images = sorted(os.listdir(tmp_path / "images")) + poses = np.genfromtxt(tmp_path / "poses.csv", delimiter=",", names=True) + assert len(images) == len(poses) == 24 + assert np.all(np.diff(poses["timestamp"]) > 0) + q = np.stack([poses[k] for k in ("qx", "qy", "qz", "qw")], 1) + np.testing.assert_allclose(np.linalg.norm(q, axis=1), 1.0, atol=1e-6) + assert poses["tx"][-1] - poses["tx"][0] > 0.3 + + # images are valid PNGs of the right size + with open(tmp_path / "images" / images[0], "rb") as f: + header = f.read(24) + assert header[:8] == b"\x89PNG\r\n\x1a\n" + assert np.frombuffer(header[16:24], dtype=">u4").tolist() == [320, 240] From 5cb3881941d0810a04b6dcbd3a3ac118518c3e7c Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:49:29 +0530 Subject: [PATCH 5/6] Add files via upload --- .../documentation/core/camera_recorder.md | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs_source/documentation/core/camera_recorder.md diff --git a/docs_source/documentation/core/camera_recorder.md b/docs_source/documentation/core/camera_recorder.md new file mode 100644 index 00000000..372cd4b9 --- /dev/null +++ b/docs_source/documentation/core/camera_recorder.md @@ -0,0 +1,51 @@ +# Camera Recorder + +## Description + +`CameraRecorder` saves the onboard camera of a drone as a posed image sequence: every image comes with the exact camera-to-world pose it was rendered from, plus the pinhole intrinsics and, optionally, metric depth. +This is the data layout expected by most visual odometry, SLAM, novel-view synthesis (NeRF, Gaussian splatting) and world-model training pipelines. + +``` +/ + images/000000.png, 000001.png, ... + depth/000000.npy, ... (optional, metric z-depth in metres, float32) + poses.csv timestamp,tx,ty,tz,qx,qy,qz,qw + intrinsics.txt fx fy cx cy +``` + +- Poses are camera-to-world transforms with OpenCV camera axes (x right, y down, z forward) in the PyBullet world frame (z up); timestamps are simulation time in seconds. +- The pose is recovered by inverting the view matrix used to render the frame, so it respects every `Camera` option (gimbal, tilt angle, position offset, tracking camera). +- Frames are always rendered with PyBullet's TinyRenderer, so the intrinsics do not change between `render=True` and `render=False`. + +## Usage + +The drone must be spawned with `use_camera=True`. + +```python +import numpy as np +from PyFlyt.core import Aviary, CameraRecorder + +env = Aviary( + start_pos=np.array([[0.0, 0.0, 1.0]]), + start_orn=np.zeros((1, 3)), + render=False, + drone_type="quadx", + drone_options=dict(use_camera=True, camera_resolution=(240, 320), camera_fps=10), +) +env.set_mode(7) +env.set_setpoint(0, np.array([2.0, 1.0, 0.0, 1.5])) + +with CameraRecorder(env, "flight_0", save_depth=True) as recorder: + for i in range(1200): + env.step() + if i % 12 == 0: # 10 Hz at the default 120 Hz control rate + recorder.capture() +``` + +A complete example is in `examples/core/11_camera_recording.py`. + +## Class Description +```{eval-rst} +.. autoclass:: PyFlyt.core.utils.camera_recorder.CameraRecorder + :members: +``` From a9510a5e5713b0889f60ca4d8a5c523d94b8ec15 Mon Sep 17 00:00:00 2001 From: Vishwa GW <136871744+vishwagw@users.noreply.github.com> Date: Thu, 19 Nov 2026 16:51:22 +0530 Subject: [PATCH 6/6] Add files via upload --- docs_source/documentation/core.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs_source/documentation/core.md b/docs_source/documentation/core.md index 9df28310..84826fea 100644 --- a/docs_source/documentation/core.md +++ b/docs_source/documentation/core.md @@ -6,6 +6,7 @@ core/aviary core/wind core/drones core/abstractions +core/camera_recorder ``` ## Core API