Saving rendered images and 3D re-projection

Saving rendered images and 3D re-projection#

Save camera images and reproject depth into 3D points with scripts/tutorials/04_sensors/run_usd_camera.py.

Code for run_usd_camera.py
  1# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
  2# All rights reserved.
  3#
  4# SPDX-License-Identifier: BSD-3-Clause
  5
  6"""
  7This script shows how to use the camera sensor from the Isaac Lab framework.
  8
  9Instead of using the simulator or OpenGL convention for the camera, we use the robotics or ROS convention.
 10OVRTX supplies semantic and instance segmentation; it does not expose Isaac Sim's
 11``instance_id_segmentation_fast`` output.
 12
 13.. code-block:: bash
 14
 15    # Usage with GUI
 16    uv run --extra ov python scripts/tutorials/04_sensors/run_usd_camera.py --viz newton_rtx
 17
 18    # Deprecated Isaac Sim path, including instance_id_segmentation_fast outputs
 19    uv run --extra isaacsim python scripts/tutorials/04_sensors/run_usd_camera.py \
 20        --physics isaacsim_physx --viz newton_gl --save
 21
 22    # Usage with no visualizer
 23    uv run --extra ov python scripts/tutorials/04_sensors/run_usd_camera.py
 24
 25"""
 26
 27"""Parse the command-line arguments first."""
 28
 29import argparse
 30from types import SimpleNamespace
 31from typing import TYPE_CHECKING
 32
 33from isaaclab_ov.physics import OvPhysxCfg
 34
 35from isaaclab.app import add_launcher_args, launch_simulation
 36
 37# add argparse arguments
 38parser = argparse.ArgumentParser(description="This script demonstrates how to use the camera sensor.")
 39parser.add_argument(
 40    "--draw",
 41    action="store_true",
 42    default=False,
 43    help="Draw the pointcloud from camera at index specified by ``--camera_id``.",
 44)
 45parser.add_argument(
 46    "--save",
 47    action="store_true",
 48    default=False,
 49    help="Save the data from camera at index specified by ``--camera_id``.",
 50)
 51parser.add_argument(
 52    "--camera_id",
 53    type=int,
 54    choices={0, 1},
 55    default=0,
 56    help=(
 57        "The camera ID to use for displaying points or saving the camera data. Default is 0."
 58        " The viewport will always initialize with the perspective of camera 0."
 59    ),
 60)
 61# append simulation launcher cli args
 62parser.add_argument("--physics", default="ovphysx", choices=["ovphysx", "isaacsim_physx"], help="Physics backend.")
 63add_launcher_args(parser)
 64parser.set_defaults(visualizer=["newton_rtx"])
 65# parse the arguments
 66args_cli = parser.parse_args()
 67# Camera sensors require the rendering extensions in headless and viewport-free launches.
 68args_cli.enable_cameras = True
 69
 70"""Rest everything follows."""
 71
 72import os
 73import random
 74
 75import numpy as np
 76import torch
 77from isaaclab_isaacsim.renderers import IsaacRtxRendererCfg
 78from isaaclab_ov.renderers import OVRTXRendererCfg
 79
 80import isaaclab.sim as sim_utils
 81from isaaclab.assets import AssetBaseCfg, RigidObject, RigidObjectCfg
 82from isaaclab.markers import VisualizationMarkers
 83from isaaclab.markers.config import RAY_CASTER_MARKER_CFG
 84from isaaclab.scene import InteractiveSceneCfg
 85from isaaclab.sensors.camera import CameraCfg
 86from isaaclab.sensors.camera.utils import create_pointcloud_from_depth, save_images_to_file
 87from isaaclab.utils import instantiate, replace
 88
 89if TYPE_CHECKING:
 90    from isaaclab.sensors.camera import Camera
 91
 92
 93def define_sensor() -> "Camera":
 94    """Defines the camera sensor to add to the scene."""
 95    # Setup camera sensor
 96    # In contrast to the ray-cast camera, we spawn the prim at these locations.
 97    # This means the camera sensor will be attached to these prims.
 98    sim_utils.create_prim("/World/Origin_00", "Xform")
 99    sim_utils.create_prim("/World/Origin_01", "Xform")
100    renderer_type = IsaacRtxRendererCfg if args_cli.physics == "isaacsim_physx" else OVRTXRendererCfg
101    camera_cfg = CameraCfg(
102        prim_path="/World/Origin_[^/]+/CameraSensor",
103        update_period=0,
104        height=480,
105        width=640,
106        data_types=[
107            "rgb",
108            "distance_to_image_plane",
109            "normals",
110            "semantic_segmentation",
111            "instance_segmentation",
112            *(["instance_id_segmentation_fast"] if args_cli.physics == "isaacsim_physx" else []),
113        ],
114        renderer_cfg=renderer_type(
115            colorize_semantic_segmentation=True,
116            colorize_instance_segmentation=True,
117        ),
118        spawn=sim_utils.PinholeCameraCfg(
119            focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5)
120        ),
121    )
122    # Create camera
123    camera = instantiate(camera_cfg)
124
125    return camera
126
127
128def design_scene() -> dict:
129    """Design the scene."""
130    # Populate scene
131    # -- Ground-plane
132    cfg = sim_utils.GroundPlaneCfg()
133    cfg.func("/World/defaultGroundPlane", cfg)
134    # -- Lights
135    cfg = sim_utils.DistantLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
136    cfg.func("/World/Light", cfg)
137
138    # Create a dictionary for the scene entities
139    scene_entities = {}
140
141    # Xform to hold objects
142    sim_utils.create_prim("/World/Objects", "Xform")
143    # Random objects
144    for i in range(8):
145        # sample random position
146        position = np.random.rand(3) - np.asarray([0.05, 0.05, -1.0])
147        position *= np.asarray([1.5, 1.5, 0.5])
148        # sample random color
149        color = (random.random(), random.random(), random.random())
150        # choose random prim type
151        prim_type = random.choice(["Cube", "Cone", "Cylinder"])
152        common_properties = {
153            "rigid_props": sim_utils.UsdPhysicsRigidBodyCfg(),
154            "mass_props": sim_utils.MassCfg(mass=5.0),
155            "collision_props": sim_utils.UsdPhysicsCollisionCfg(),
156            "visual_material": sim_utils.PreviewSurfaceCfg(diffuse_color=color, metallic=0.5),
157            "semantic_tags": [("class", prim_type)],
158        }
159        if prim_type == "Cube":
160            shape_cfg = sim_utils.CuboidCfg(size=(0.25, 0.25, 0.25), **common_properties)
161        elif prim_type == "Cone":
162            shape_cfg = sim_utils.ConeCfg(radius=0.1, height=0.25, **common_properties)
163        elif prim_type == "Cylinder":
164            shape_cfg = sim_utils.CylinderCfg(radius=0.25, height=0.25, **common_properties)
165        # Rigid Object
166        obj_cfg = RigidObjectCfg(
167            prim_path=f"/World/Objects/Obj_{i:02d}",
168            spawn=shape_cfg,
169            init_state=RigidObjectCfg.InitialStateCfg(pos=position),
170        )
171        scene_entities[f"rigid_object{i}"] = RigidObject(cfg=obj_cfg)
172
173    # Sensors
174    camera = define_sensor()
175
176    # return the scene information
177    scene_entities["camera"] = camera
178    return scene_entities
179
180
181def run_simulator(sim: sim_utils.SimulationContext, scene_entities: dict):
182    """Run the simulator."""
183    # extract entities for simplified notation
184    camera: Camera = scene_entities["camera"]
185
186    # Create the output directory
187    output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera")
188    os.makedirs(output_dir, exist_ok=True)
189
190    # Camera positions, targets, orientations
191    camera_positions = torch.tensor([[2.5, 2.5, 2.5], [-2.5, -2.5, 2.5]], device=sim.device)
192    camera_targets = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=sim.device)
193    # These orientations are in ROS-convention, and will position the cameras to view the origin
194    camera_orientations = torch.tensor(  # noqa: F841
195        [[-0.1759, 0.3399, 0.8205, -0.4247], [-0.4247, 0.8205, -0.3399, 0.1759]], device=sim.device
196    )
197
198    # Set pose: There are two ways to set the pose of the camera.
199    # -- Option-1: Set pose using view
200    camera.set_world_poses_from_view(camera_positions, camera_targets)
201    # -- Option-2: Set pose using ROS
202    # camera.set_world_poses(camera_positions, camera_orientations, convention="ros")
203
204    # Index of the camera to use for visualization and saving
205    camera_index = args_cli.camera_id
206
207    # Create the markers for the --draw option outside of the simulation loop
208    if sim.get_setting("/isaaclab/has_gui") and args_cli.draw:
209        cfg = replace(RAY_CASTER_MARKER_CFG, prim_path="/Visuals/CameraPointCloud")
210        cfg.markers["hit"].radius = 0.002
211        pc_markers = VisualizationMarkers(cfg)
212
213    # Simulate physics
214    while sim.is_running():
215        # Step simulation
216        sim.step()
217        # Update camera data
218        camera.update(dt=sim.get_physics_dt())
219
220        # Print camera info
221        print(camera)
222        if "rgb" in camera.data.output.keys():
223            print("Received shape of rgb image        : ", camera.data.output["rgb"].shape)
224        if "distance_to_image_plane" in camera.data.output.keys():
225            print("Received shape of depth image      : ", camera.data.output["distance_to_image_plane"].shape)
226        if "normals" in camera.data.output.keys():
227            print("Received shape of normals          : ", camera.data.output["normals"].shape)
228        if "semantic_segmentation" in camera.data.output.keys():
229            print("Received shape of semantic segm.   : ", camera.data.output["semantic_segmentation"].shape)
230        if "instance_segmentation" in camera.data.output.keys():
231            print("Received shape of instance segm.   : ", camera.data.output["instance_segmentation"].shape)
232        if "instance_id_segmentation_fast" in camera.data.output.keys():
233            print("Received shape of instance id segm.: ", camera.data.output["instance_id_segmentation_fast"].shape)
234        print("-------------------------------")
235
236        # Extract camera data
237        if args_cli.save:
238            # Save the camera outputs at camera_index: 8-bit color images as PNG, other data (depth, normals) as NumPy
239            for key, data in camera.data.output.items():
240                file_stem = os.path.join(output_dir, f"{key}_{camera.frame[camera_index]}")
241                if data.torch.dtype == torch.uint8:
242                    save_images_to_file(data.torch[camera_index : camera_index + 1].float() / 255.0, f"{file_stem}.png")
243                else:
244                    np.save(f"{file_stem}.npy", data.torch[camera_index].cpu().numpy())
245
246        # Draw pointcloud if there is a GUI and --draw has been passed
247        if (
248            sim.get_setting("/isaaclab/has_gui")
249            and args_cli.draw
250            and "distance_to_image_plane" in camera.data.output.keys()
251        ):
252            # Derive pointcloud from camera at camera_index
253            pointcloud = create_pointcloud_from_depth(
254                intrinsic_matrix=camera.data.intrinsic_matrices[camera_index],
255                depth=camera.data.output["distance_to_image_plane"][camera_index],
256                position=camera.data.pos_w[camera_index],
257                orientation=camera.data.quat_w_ros[camera_index],
258                device=sim.device,
259            )
260
261            # In the first few steps, things are still being instanced and Camera.data
262            # can be empty. If we attempt to visualize an empty pointcloud it will crash
263            # the sim, so we check that the pointcloud is not empty.
264            if pointcloud.size()[0] > 0:
265                pc_markers.visualize(translations=pointcloud)
266
267
268def main():
269    """Main function."""
270    # Configure the simulation
271    sim_cfg = sim_utils.SimulationCfg(
272        physics=OvPhysxCfg(),
273        device=args_cli.device,
274    )
275    # Launch the simulator runtime that the configuration needs
276    scene_cfg = InteractiveSceneCfg(num_envs=1, env_spacing=0.0)
277    scene_cfg.world = AssetBaseCfg(prim_path="/World")
278    with launch_simulation(SimpleNamespace(sim=sim_cfg, scene=scene_cfg), args_cli):
279        # Initialize the simulation context
280        sim = sim_utils.SimulationContext(sim_cfg)
281        # Set main camera
282        sim.set_camera_view([2.5, 2.5, 2.5], [0.0, 0.0, 0.0])
283        # Design scene
284        scene_entities = design_scene()
285        # Declare the standalone world so scene-data consumers can discover its geometry.
286        scene = instantiate(scene_cfg)
287        # Play simulator
288        sim.reset()
289        # Now we are ready!
290        print("[INFO]: Setup complete...")
291        # Run simulator
292        run_simulator(sim, scene_entities)
293        del scene
294
295
296if __name__ == "__main__":
297    # run the main function
298    main()

Saving the images to file#

To save camera outputs, we use the save_images_to_file() utility. It writes a batch of images as a PNG file and does not depend on the renderer backend. The script creates the output folder once, before the simulation loop:

    # Create the output directory
    output_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output", "camera")
    os.makedirs(output_dir, exist_ok=True)

While stepping the simulator, the outputs of the camera at camera_index are saved once per data type and frame: 8-bit color outputs (the RGB image and the colorized segmentations) as PNG files, and floating-point outputs, such as depth and normals, as NumPy .npy files.

            # Save the camera outputs at camera_index: 8-bit color images as PNG, other data (depth, normals) as NumPy
            for key, data in camera.data.output.items():
                file_stem = os.path.join(output_dir, f"{key}_{camera.frame[camera_index]}")
                if data.torch.dtype == torch.uint8:
                    save_images_to_file(data.torch[camera_index : camera_index + 1].float() / 255.0, f"{file_stem}.png")
                else:
                    np.save(f"{file_stem}.npy", data.torch[camera_index].cpu().numpy())

Projection into 3D Space#

We include utilities to project the depth image into 3D Space. The re-projection operations are done using PyTorch operations which allows faster computation.

from isaaclab.utils.math import transform_points, unproject_depth

# Pointcloud in world frame
points_3d_cam = unproject_depth(
   camera.data.output["distance_to_image_plane"], camera.data.intrinsic_matrices
)

points_3d_world = transform_points(points_3d_cam, camera.data.pos_w, camera.data.quat_w_ros)

Alternately, we can use the isaaclab.sensors.camera.utils.create_pointcloud_from_depth() function to create a point cloud from the depth image and transform it to the world frame.

            # Derive pointcloud from camera at camera_index
            pointcloud = create_pointcloud_from_depth(
                intrinsic_matrix=camera.data.intrinsic_matrices[camera_index],
                depth=camera.data.output["distance_to_image_plane"][camera_index],
                position=camera.data.pos_w[camera_index],
                orientation=camera.data.quat_w_ros[camera_index],
                device=sim.device,
            )

The resulting point cloud can be visualized with Isaac Lab’s VisualizationMarkers. The accompanying tutorial uses RAY_CASTER_MARKER_CFG and calls visualize() to draw the points in the viewport.

            # In the first few steps, things are still being instanced and Camera.data
            # can be empty. If we attempt to visualize an empty pointcloud it will crash
            # the sim, so we check that the pointcloud is not empty.
            if pointcloud.size()[0] > 0:
                pc_markers.visualize(translations=pointcloud)

Executing the script#

To run the accompanying script, execute the following command:

# Usage with saving and drawing
uv run --extra ov python scripts/tutorials/04_sensors/run_usd_camera.py --save --draw --viz newton_rtx

# Usage with saving only (no visualizer)
uv run --extra ov python scripts/tutorials/04_sensors/run_usd_camera.py --save

The simulation should start, and you can observe different objects falling down. An output folder will be created in the IsaacLab/scripts/tutorials/04_sensors directory, where the images will be saved as PNG files. Additionally, you should see the point cloud in the 3D space drawn on the viewport.

To stop the simulation, close the window, or use Ctrl+C in the terminal.