Skip to content
ImagineWorld

Working with ROS 2 and Perception Stack

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-10-working-with-ros-2-and-perception-stack
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleWorking with ROS 2 and Perception Stack
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Working with ROS 2 and Perception Stack

Section titled “Chapter 10 — Working with ROS 2 and Perception Stack”

Robots interact with the environment thanks to their sensors. Without sensors, robots are blind machines unable to react to the world’s stimuli and can only perform cyclic motions. However, adding sensors to a robot also means the necessity to implement proper algorithms to process the sensor data. One of the most common sensor types used in robotics is visual sensors, like cameras. In this chapter, we will discuss how to interface standard cameras with our laptops and elaborate images using Open Computer Vision (OpenCV), a popular open-source library to process video streams. In addition, we will see the main limitations of cameras, that is, the missing information about the depth. For this reason, we will discuss another type of sensor: depth sensors and the processing of their data (point cloud data). Apart from these libraries that offer functionalities to elaborate raw image and spatial data, we will discuss artificial intelligence approaches to solve typical robotics problems associated with computer vision and the usage of the Graphics Processing Unit (GPU).

As such, we will cover the following main topics in the chapter:

  • Integrating robotics and computer vision
  • Getting started with depth sensors
  • Using NVIDIA ISAAC ROS to speed up image processing

To follow this chapter, it is best to have a computer with Ubuntu 24.04 LTS installed or any other Ubuntu version. Additionally, to fully execute all the examples of this chapter, a standard USB camera and an Intel depth sensor are required. Finally, in the last part of the book, we will use the NVIDIA ISAAC ROS framework, which requires an NVIDIA CUDA-enabled graphical card to be installed.

The reference materials for this chapter can be found in the Chapter10 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter10.

Robotics and computer vision are closely connected fields, as robots rely on computer vision to complete a variety of tasks. The data from computer vision algorithms helps robots with tasks such as:

  • Object recognition: Identifying and classifying objects, either through semantic classification or 3D shape matching.
  • Obstacle avoidance: Enabling robots to detect and navigate around obstacles safely.

In simple terms, computer vision allows robots to interpret visual information, recognize objects, and understand their surroundings. Depending on the specific application, different processing techniques or vision sensors may be required. One of the most widely used software libraries for image processing on standard computers is OpenCV. OpenCV is an open-source library that offers a wide range of tools and algorithms for computer vision, machine learning, and image processing. It is highly versatile and can be used for tasks such as real-time image processing, object detection, face recognition, and 3D vision. OpenCV has evolved over the years to include many powerful features, including:

  • Image processing: OpenCV offers various image transformations, such as filtering, resizing, blurring, edge detection, and thresholding.
  • Object detection and recognition: It provides tools for detecting objects like faces, pedestrians, and patterns using methods like Haar cascades, Histogram of Oriented Gradients (HOG), and deep-learning-based models.
  • Video processing: OpenCV can handle video frame processing in real time, making it suitable for applications like surveillance, video editing, and motion analysis.
  • Feature detection: It includes algorithms like SIFT, SURF, ORB, and FAST for detecting keypoints and features in images, which are useful for tasks like object recognition and image stitching.

One reason standard cameras are popular in many applications is that robots can easily use any USB camera connected to their main computer. These cameras are widely available, affordable, and easy to set up. In contrast, industrial cameras offer more advanced features, such as the ability to adjust settings like frame rate and brightness, but they are more expensive and harder to integrate with ROS 2.

In this chapter, we’ll start by integrating a standard USB camera with ROS 2. If you’re using a laptop with a built-in camera, you can use that. Otherwise, any USB camera will work for the following example. Notice that, even if you don’t have the sensors used in this chapter, you can simulate them using Gazebo and test the examples discussed in this chapter.

There are different ways to integrate camera sensors with ROS 2. One is to implement the low-level functions to grab data from a specific sensor using OpenCV libraries. Another way is to use the usb_cam package already present in the ROS 2 package repositories. Let’s start with this latter approach:

  1. In any case, whatever the chosen approach, the first thing to do is to retrieve the address of the camera device from the operating system. The list of video devices present in the system can be seen with the following command:
    $ ls /dev | grep video

For example, if you have one or more cameras connected to your laptop, the output will be like this:

Video0 video1 video2 video3
  1. Among this list, to check which is the correct device, video streaming programs like VLC or cheese can be used. Let’s install the usb_cam package:
    sudo apt-get install ros-jazzy-usb-cam
  2. To start the camera, we must create a proper launch file. Let’s create a package containing the launch file:
    ros2 pkg create usb_cam_launcher
    mkdir usb_cam_launcher/launch
    touch usb_cam_launcher/launch/my_usb_cam.launch.py

The content of the launch file is described in the following:

  1. At the start, the modules are imported:
    from launch import LaunchDescription
    from launch_ros.actions import Node
  2. We need to start only one node, usb_cam_node_exe initialized with the proper parameters:
    def generate_launch_description():
    return LaunchDescription([
    Node(
    package='usb_cam',
    executable='usb_cam_node_exe',
    name='usb_cam',
    output='screen',
  3. As you can see, here we must insert the address of the video device associated with our camera. If we want to start the video device associated with the ID video2, the complete address is /dev/video2:
    parameters=[
    {'video_device': '/dev/video2'},
    {'image_width': 1280},
    {'image_height': 720},
    {'pixel_format': 'yuyv'},
    {'camera_frame_id': 'usb_camera'}
    ],)])
  4. To start this launch file, you must modify CMakeLists.txt to install the launch directory. After you have compiled and sourced the workspace, you can start the node with the following command:
    ros2 launch usb_cam_launcher my_usb_cam.launch.py
  5. Now you can check the list of topics active in your system with the $ ros2 topic list command. Mainly we are interested in two topics:
    • /camera_info: This topic contains information about the intrinsic camera calibration, used to transform image pixels into 2D coordinates. We will learn how to calibrate and use this information later in this chapter.
      • /image_raw: The topic containing the image. Figure 10.1: rqt_image_view showing the images taken from the USB camera Figure 10.1: rqt_image_view showing the images taken from the USB camera
  6. You can use the rqt_image_view program to display the image. If this program is not already installed, you can install it with the following command:
    sudo apt-get install ros-jazzy-rqt-image-view
  7. You can now use rqt_image_view with the following command. Later, you can see the image by selecting the desired topic on which the image is streamed (see Figure 10.1). To start rqt, you can use the following command:
    ros2 run rqt_image_view rqt_image_view

Now that we have a webcam, we can start to elaborate the images using OpenCV libraries, as discussed in the next section.

Getting started with OpenCV – ROS 2 integration

Section titled “Getting started with OpenCV – ROS 2 integration”

We are now ready to start elaborating images using ROS 2 and OpenCV. On its own, ROS 2 doesn’t offer a proper way to perform image processing. As already stated, the main library worldwide used to perform this task is OpenCV. For this reason, ROS 2 offers an interface towards OpenCV that allows ROS 2 topics to be directly converted into the image data structure supported by OpenCV and vice versa. In this way, the main programming pipeline will be:

  1. Receiving the image data to elaborate via ROS 2 topics (ROS uses the sensor_msgs/msg/Image data type)
  2. Convert this to an OpenCV image (the data used is a cv::Mat)
  3. Process the image
  4. Convert the OpenCV image into a ROS 2 message, publishing the eventual result

But what is a cv::Mat? In OpenCV, an image is represented as a matrix, where each element corresponds to a pixel in the image. For grayscale images, the matrix has one channel, and each element stores the intensity of the pixel (0-255). For color images, the matrix has three channels (e.g., RGB), with each element containing a vector of three values representing the intensity of red, green, and blue at that pixel. The matrix’s dimensions correspond to the image’s width and height.

The interface to transform ROS 2 data in OpenCV images and vice versa is implemented in the cv_bridge package. Let’s use it on a ROS 2 node to perform some basic operations typical of computer vision. For code readability, we report here only part of the whole source code. You can check the full code in the book repository: https://github.com/PacktPublishing/Mastering-ROS-2.git.

First, create the ROS 2 package with the correct dependencies:

$ ros2 pkg create my_opencv_package --dependencies rclcpp sensor_msgs cv_bridge

Create a source called image_processing.cpp. In this code, we will perform the following operations:

  • Conversion from RGB to grayscale: Reduces a color image to shades of gray by averaging the color channels.
  • Image blur: Smooths the image to reduce noise using filters like Gaussian blur.
  • Image thresholding: Converts an image to binary by setting pixel values above a threshold to white and below to black.
  • Contour detection: Identifies the outlines of objects or shapes within an image.
  • Feature extraction: Identifies important patterns or points in an image for recognition or matching.
  • ORB: Detects and describes keypoints in an image for fast feature matching.
  • Corners: Points where two edges meet, often detected for identifying unique features.

These operations serve different purposes. Techniques like blurring, converting to grayscale, or thresholding are part of image enhancement, which prepares images for further analysis. For instance, blurring helps reduce noise or unnecessary details, making the image easier to process. Similarly, feature extraction methods like ORB or corner detection are used to analyze the camera’s environment. These features can outline object shapes, enable object tracking, or support advanced tasks like visual odometry, which calculates the camera’s position as it moves.

The content of the image_processing.cpp source is reported here:

  1. In the header, we need to add both the cv_bridge and opencv headers:
    #include <cv_bridge/cv_bridge.hpp>
    #include <opencv2/opencv.hpp>
    #include "rclcpp/rclcpp.hpp"
    #include "sensor_msgs/msg/image.hpp"
  2. In the constructor, the input and output of the node are initialized. We subscribe to the topic streamed by the camera sensor, publishing the processed images. In this case, we report only two publishers, but they will be the same for all the other images:
    class ImageProcessor : public rclcpp::Node {
    public:
    ImageProcessor() : Node("image_processor") {
    image_subscription_ = this->create_subscription<sensor_msgs::msg::Image>("/image_raw", 10, std::bind(&ImageProcessor::image_callback, this, std::placeholders::_1));
    contours_imag_pub_ = this->create_publisher<sensor_msgs::msg::Image>( "contours/image_raw", 1);
    gray_img_pub_ = this->create_publisher<sensor_msgs::msg::Image>( "gray/image_raw", 1);
    }
    private:
  3. In the image callback, the function toCvCopy is used to store the data received from the callback in the cv_bridge object. This object already contains the cv::Mat element that represents the input image:
    void image_callback(const sensor_msgs::msg::Image::SharedPtr msg) {
    cv_bridge::CvImagePtr cv_ptr;
    try {
    cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
    }
    catch (cv_bridge::Exception& e) {
    RCLCPP_ERROR(this->get_logger(), "cv_bridge exception: %s", e.what());
    return;
    }
    cv::Mat processed_image = cv_ptr->image.clone();
    cv::Mat contours_image = cv_ptr->image.clone();
    cv::Mat gray_image;
  4. Let’s start by translating the image into a grayscale image and generating its blur version. A mask is used to define the strength of the blur:
    cv::cvtColor(processed_image, gray_image, cv::COLOR_BGR2GRAY);
    cv::blur(processed_image, blur_image, cv::Size(15, 15));
  5. This line applies binary thresholding to gray_image, setting pixels above 128 to 255 (white) and below to 0 (black), storing the result in thresholded_image. The result will be an image with total white or total black:
    cv::threshold(gray_image, thresholded_image, 128, 255, cv::THRESH_BINARY);
  6. Then, we extract image contours. Contours are used in computer vision to identify object shapes and boundaries for tasks like detection, segmentation, and measurement:
    std::vector<std::vector<cv::Point>> contours;
    cv::findContours(thresholded_image, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
    cv::drawContours(contours_image, contours, -1, cv::Scalar(0, 255, 0), 2);
  7. Here, we extract ORB features. ORB is used in computer vision to detect and describe keypoints efficiently, making it ideal for fast image matching and object recognition:
    cv::Ptr<cv::ORB> orb = cv::ORB::create();
    std::vector<cv::KeyPoint> keypoints;
    cv::Mat descriptors;
    orb->detectAndCompute(gray_image, cv::noArray(), keypoints, descriptors);
    cv::drawKeypoints(processed_image, keypoints, keypoints_img, cv::Scalar(0, 0, 255), cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
  8. Corners are an image feature used in many computer vision applications because they are distinctive, stable under transformations, and ideal for tasks like image matching and object recognition:
    cv::Mat dst, dst_norm, dst_norm_scaled;
    dst = cv::Mat::zeros(gray_image.size(), CV_32FC1);
    const int blockSize = 2;
    const int apertureSize = 3;
    double k = 0.04;
    cv::cornerHarris(gray_image, dst, blockSize, apertureSize, k);
    cv::normalize(dst, dst_norm, 0, 255, cv::NORM_MINMAX, CV_32FC1, cv::Mat());
    cv::convertScaleAbs(dst_norm, dst_norm_scaled);
  9. To visualize the corners, we can print them over the image:
    corner_image = processed_image.clone();
    for (int i = 0; i < dst_norm.rows; i++) {
    for (int j = 0; j < dst_norm.cols; j++) {
    if ((int)dst_norm.at<float>(i, j) > 200) {
    cv::circle(corner_image, cv::Point(j, i), 5, cv::Scalar(0, 0, 255), 2, 8, 0);
    }
    }
    }
  10. We are now ready to generate the output by publishing the images reporting the output of all the operations done so far. Also, in this case, the cv_bridge object is used to translate the image from OpenCV to ROS 2. Here, we must consider the image format. For example, a colored image must be converted considering the bgr8, while the grayscale image should be converted with a mono8 format:
    msg_ = cv_bridge::CvImage(std_msgs::msg::Header(), "bgr8", contours_image).toImageMsg();
    _contours_imag_pub->publish(*msg_.get());
    msg_ = cv_bridge::CvImage(std_msgs::msg::Header(), "mono8", gray_image).toImageMsg();
    }
  11. As class members, we define the image publishers:
    rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr image_subscription_;
    rclcpp::Publisher<sensor_msgs::msg::Image>::SharedPtr _contours_imag_pub;

You can now add the source to the CMakeLists.txt compile and source the ROS 2 workspace. Test the OpenCV elaboration node by launching the USB cam and the node described above:

$ ros2 launch usb_cam_launcher my_usb_cam.launch.py
$ ros2 run my_opencv_package image_processing

A sample output of the node is reported in Figure 10.2, where the contours, the ORB features, the blur image, and the threshold ones are depicted:

Figure 10.2: Image elaboration result: contours, ORB features, blur, and threshold images

Figure 10.2: Image elaboration result: contours, ORB features, blur, and threshold images

In the previous section, we perform basic image elaboration routines that work considering the value of the pixel of the image. In robotics, this is not enough. In fact, we must find a mapping between the pixel of the image and the physical space around the camera sensor. How can we obtain this? Using the intrinsic parameters of the camera. For this reason, we will introduce the differences between the pixel and image spaces:

  • Pixel space: This refers to the coordinate system defined by the individual pixels of an image. Each pixel has discrete coordinates (x, y) corresponding to its position in the grid of pixels. Pixel space is primarily concerned with the raw pixel values and their arrangement, without considering any geometric relationships to the real world.
  • Image space: Image space extends beyond pixel coordinates to include a mathematical representation of the image that can relate pixel positions to real-world coordinates. It often considers factors like perspective, camera parameters, and transformations that allow for interpreting the image data in a meaningful way.

To pass between pixel space and image space, we must use the camera calibration. Camera calibration in robotics involves determining the intrinsic and extrinsic parameters of a camera to accurately relate image space to real-world coordinates. This is essential for tasks like navigation, object detection, and mapping, where precise measurements are required. Mainly we have two kinds of calibration. The intrinsic and extrinsic:

  • Intrinsic calibration: This focuses on the internal parameters of the camera, such as focal length, optical center (principal point), and lens distortion coefficients. Intrinsic calibration corrects for distortions and enables accurate mapping of pixel coordinates to real-world measurements.
  • Extrinsic calibration: This involves determining the camera’s position and orientation in relation to a reference frame or the environment. Extrinsic parameters describe the transformation between the camera coordinate system and the world coordinate system, allowing for the accurate placement of objects detected in the image in their real-world locations.

To perform the calibration of a camera, we need a calibration pattern. Typically, it is a chessboard, like the one shown in Figure 10.3. Also, in this case, OpenCV has a procedure to perform the calibration, while ROS 2 has a wrapper for it. Before starting the calibration, we must install the following package:

$ sudo apt-get install ros-jazzy-camera-calibration

Now, we can start the calibration:

$ ros2 run camera_calibration cameracalibrator --size 10x7 --square 0.02 --ros-args -r image:=/image_raw -p camera:=/camera

This command contains some parameters depending on the chessboard and the USB camera connected.

  • --size 10x7: Specifies the checkerboard pattern has 10 internal corners horizontally and 7 vertically.
  • --square 0.02: Sets the size of each square on the checkerboard to 0.02 meters (2 cm).
  • --ros-args: Indicates that the following parameters are ROS 2-specific.
  • -r image:=/image_raw: Remaps the input topic to subscribe to /image_raw for camera images.
  • -p camera:=/camera: Sets a parameter for the camera namespace or topic to use during calibration.

Figure 10.3: Camera calibration procedure

Figure 10.3: Camera calibration procedure

After that, the calibration starts, and the window shown in Figure 10.3 is opened. To perform the calibration, you must move the camera, or the chessboard, in different directions and orientations, zooming in and out to improve the quality of the calibration. You can check the quality of the calibration in the top-right panel, which informs you about the single components of the calibration. When the overall quality is acceptable, the calibration button is enabled (CALIBRATE in Figure 10.3), and you can click on it. In a few seconds, the calibration will be ready, and the COMMIT button will be enabled. After clicking this button, the calibration is saved in the ROS 2 system. In fact, the camera calibration is directly saved in a hidden directory of your computer, as you can check on the terminal where the USB camera has started:

$ [camera]: writing calibration data to /home/user/.ros/camera_info/default_cam.yaml

After saving the calibration, you can verify that it was saved correctly by restarting the USB camera node and checking the contents of the /camera_info topic. This topic includes parameters such as the focal length, optical center, and distortion coefficients. However, these parameters are generally not used directly. Instead, when a ROS 2 node requires these parameters to convert pixel coordinates to spatial coordinates, it subscribes directly to the /camera_info topic. However, even though we properly calibrate the camera, there is missing information that is often used in advanced robot applications: the depth information. For this reason, another kind of sensor used in robotics is the depth sensor, as introduced in the next section.

Using standard cameras is not possible to obtain information about the distance between the framed objects and the sensor. This makes these sensors unsuitable for many robotics tasks like object grasping, in which it is good to estimate the full pose of the object to manipulate, or obstacle avoidance, in which the distance from the obstacle is fundamental to performing safe navigation. For this scope, a different kind of sensor can be used: the depth sensor. Depth sensors are like cameras in terms of size and payload. They are compact devices and can be attached to the robot computer with a USB connector. Unlike cameras, these devices measure the distance to objects in their environment, providing depth information that enhances perception capabilities in robotics. Common types include LiDAR or time-of-flight sensors. These sensors are well integrated with ROS 2. Depth sensors publish depth in two formats:

  • Disparity matrix: Exactly like an image, this matrix stores a set of pixel values. Each pixel of the disparity matrix is encoded with the value representing the distance of that pixel from the sensor in meters.
  • Point Cloud: Generated from the disparity matrix, this data is a collection of points in 3D space representing the external surface of the objects framed by the sensor.

In recent years, Intel’s RealSense series represented a major development in depth sensing, deploying devices that leverage stereo vision technology combined with infrared filtering to capture high-resolution depth information in real time. Apart from the hardware itself, Intel also provides an SDK to interface a camera with Linux machines and so, with ROS 2.

In this book, we will use the Intel RealSense D435 (see Figure 10.4) to integrate a depth sensor with ROS 2. However, apart from the sensor installation part, you can use any other depth sensor available on the market to test the examples described in the following. In fact, exactly like OpenCV with image processing, we will use a library to manage the data generated from the depth sensors, the point cloud data. This library is called Point Cloud Library (PCL) and is an open-source library that offers tools for filtering, feature extraction, segmentation, and surface reconstruction for point cloud data.

From a certain point of view, PCL complements OpenCV, which handles 2D image processing, allowing developers to work seamlessly with both 2D and 3D data in robotic applications.

Figure 10.4: RealSense D435 device

Figure 10.4: RealSense D435 device

Let’s start installing the RealSense device before starting to use PCL. To install ROS 2 packages to handle a RealSense device in our system, use the following commands:

$ sudo apt-get install ros-jazzy-librealsense2
$ sudo apt-get install ros-jazzy-realsense2-*

The last command installs the realsense2_camera ROS 2 package, which includes a useful launch file for easily starting and configuring any supported RealSense devices. For example, after attaching the device to your laptop, use the following command to start streaming sensor data:

$ ros2 launch realsense2_camera rs_launch.py

The data generated from this sensor is visible in Figures 10.5 and 10.6. In Figure 10.5, the rqt_image_view ROS 2 node is used to visualize two images published from this sensor. In the left part of the image, there is the disparity matrix, which gives us information about the depth of the scene. In the right part, there is the RGB camera output.

Figure 10.5: RGB image (right) and depth matrix (left) streamed by the Intel RealSense depth sensor

Figure 10.5: RGB image (right) and depth matrix (left) streamed by the Intel RealSense depth sensor

Similarly, the depth sensor publishes the point cloud data. You can visualize such data using Rviz2 after importing the DepthCloud plugin (Rviz2 configuration is shown in Figure 10.6). In Rviz2, where point cloud data is visualized, you can observe how this data maps the 3D shape of the world using a collection of points. Can you recognize the shape of the hand captured by the RGB camera?

Figure 10.6: Point cloud data shown on Rviz2

Figure 10.6: Point cloud data shown on Rviz2

Before integrating point cloud data in our ROS 2 node, we must install the proper libraries and interfaces to handle PCL data:

$ sudo apt-get install libpcl-dev
$ sudo apt-get install ros-jazzy-pcl-*

Let’s now start to integrate point cloud data in a ROS 2 node:

$ ros2 pkg create --build-type ament_cmake pcl_processing --dependencies rclcpp sensor_msgs pcl_ros

We are now ready to elaborate on our point cloud data. The pipeline process is analogous to the one already considered for OpenCV: the data is received via topics, transformed into a PCL data format, and elaborated using the PCL libraries. Finally, it is published as a ROS 2 message to be used from other software modules.

What is the goal of this code? Crop and subsample a point cloud. In fact, point clouds can generate a huge amount of data and sometimes we don’t need all this information. Let’s discuss the content of the pcl_processing.cpp file. Also, in this case, we report only the salient parts of the code.

You can download the complete package from the book code repository:

  1. Let’s start by including the header files. Many of them are part of the PCL headers. In addition, here, we see the data used by ROS 2 to stream point cloud data types, the sensor_msgs/msg/point_cloud2.hpp:
    #include <pcl/filters/passthrough.h>
    #include <pcl/filters/voxel_grid.h>
    #include <pcl/point_cloud.h>
    #include <pcl/point_types.h>
    #include <pcl_conversions/pcl_conversions.h>
    #include <sensor_msgs/msg/point_cloud2.hpp>
  2. In the class of the node, subscribe to the points data streamed from the RealSense sensor:
    class PointCloudProcessor : public rclcpp::Node {
    public:
    PointCloudProcessor(): Node("pointcloud_processor") {
    subscription_ = this->create_subscription<sensor_msgs::msg::PointCloud2>(
    "/camera/camera/depth/color/points", 10,
    std::bind(&PointCloudProcessor::processPointCloud, this, std::placeholders::_1));
  3. Additionally, we want to publish the result on other point cloud data, to match the differences between the input and the output:
    publisher_ = this->create_publisher<sensor_msgs::msg::PointCloud2>("filtered_pointcloud", 10);
    private:
  4. All the work is done directly in the callback of the point cloud data. This also demonstrates the performance of this library, since all these operations are executed at the same framerate of the sensor input:
    void processPointCloud(const sensor_msgs::msg::PointCloud2::SharedPtr msg) {
  5. First, let’s translate the data from the input point cloud ROS 2 side to PCL data:
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>());
    pcl::fromROSMsg(*msg, *cloud);
  6. The first step is to crop the point cloud. To do this, we create an object called PassThrough, which takes the point cloud data as input. We can crop the data along the three axes: x, y, and z. In this case, we crop along all three axes. For the x -axis, we crop the data between -0.5 and 0.5 meters, meaning we only keep the points that fall within this range along the x direction relative to the sensor:
    pcl::PassThrough<pcl::PointXYZ> pass_x;
    pass_x.setInputCloud(cloud);
    pass_x.setFilterFieldName("x");
    pass_x.setFilterLimits(-0.5, 0.5); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered_x(new pcl::PointCloud<pcl::PointXYZ>());

To perform the crop, apply the filter to the input cloud, saving its result in the cloud_filtered_x object. We perform the same operation for the y -axis. Remember that, for each axis, a new PassThrough object must be declared and properly set. Of course, in the case of the y -axis, the input of the PassThrough object will be the cloud already filtered in the x direction. As for the z -axis, we enlarge the interval, cutting the points upto 1 meter from the sensor:

pass_x.filter(*cloud_filtered_x);
pcl::PassThrough<pcl::PointXYZ> pass_y;
pass_y.setInputCloud(cloud_filtered_x);
  1. After cropping the point cloud, we will down sample the data. For this reason, we apply a pcl/VoxelGrid filter by reducing its resolution. It divides the point cloud space into 3D voxels (cubes) of size 2 cm and keeps only one representative point per voxel, effectively reducing the number of points in the cloud while preserving the overall structure. In this way, we can maintain the shape of the original cloud but at the same time reduce the effort of its future elaboration:
    pcl::VoxelGrid<pcl::PointXYZ> voxel_grid;
    voxel_grid.setInputCloud(cloud_filtered);
    voxel_grid.setLeafSize(0.02f, 0.02f, 0.02f);
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_downsampled(new pcl::PointCloud<pcl::PointXYZ>());
    voxel_grid.filter(*cloud_downsampled);
  2. Finally, we are ready to convert back the PCL data to a ROS 2 format, publishing it on a topic:
    sensor_msgs::msg::PointCloud2 output_msg;
    pcl::toROSMsg(*cloud_downsampled, output_msg);
    output_msg.header = msg->header;
    publisher_->publish(output_msg);
  3. Remember to declare in the class member the subscriber and the publisher of the point cloud data:
    rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr subscription_;
    rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr publisher_;
    };
  4. Our code is now complete. We can add the compilation instructions to the CMakeLists.txt file:
    add_executable(pcl_processing src/pcl_processing.cpp)
    ament_target_dependencies(pcl_processing rclcpp sensor_msgs pcl_ros)
    target_link_libraries(pcl_processing ${PCL_LIBRARIES})
    install(TARGETS pcl_processing DESTINATION lib/${PROJECT_NAME})

Finally, compile and source the workspace before executing the PCL processing and the RealSense camera driver. Notice that, in this case, we add a parameter to the rs_launch.py file, setting pointcloud.enable to true. This allows the RealSense driver to directly stream the point cloud points subscribed by our node:

$ ros2 launch realsense2_camera rs_launch.py pointcloud.enable:=true
$ ros2 run pcl_processing pcl_processing

Using Rviz2, you can compare the original point cloud with respect to the one generated by the pcl_processing node. This comparison is also shown in Figure 10.7, where, on the left side, there is the complete cloud, while on the right side, the cropped and down sampled cloud is shown.

Figure 10.7: Point cloud data elaboration. Left: full point cloud, right: cropped and down sampled point cloud

Figure 10.7: Point cloud data elaboration. Left: full point cloud, right: cropped and down sampled point cloud

By comparing the result of this algorithm with the output from OpenCV image processing, you can see the vast range of applications made possible by this information. Robots can gain a comprehensive understanding of their environment, from colors and features to 3D shapes. Developers have long implemented applications based on point cloud data, such as localization, mapping, object detection, and 3D reconstruction. Additionally, depth sensor data can be converted to laser scan messages, providing a low-cost solution for autonomous navigation (as implemented in the pointclud_to_laserscan package [1]). However, processing large datasets like images and point clouds is challenging, which is why developers have increasingly turned to GPUs for faster computation, as discussed in the last section of this chapter.

Using NVIDIA ISAAC ROS to speed up image processing

Section titled “Using NVIDIA ISAAC ROS to speed up image processing”

Processing large amounts of data, such as images or point clouds, can lead to performance issues if algorithms cannot handle the resource demands. To address this, developers have begun leveraging the high computational power of GPUs. This shift has been driven by the popularity of NVIDIA Jetson computers, which are compact devices equipped with powerful GPUs, making them ideal for robotics applications. In this view, NVIDIA directly supports the ROS 2 developers by providing a collection of packages that solve robotics perception problems by directly exploiting the GPU, and directly communicating with the ROS 2 ecosystem. This collection of packages is known as NVIDIA ISAAC ROS and covers many problems of robotic perception.

In this section, we will learn how NVIDIA ISAAC is structured and how to install it on our machines, running some of the ROS 2 nodes implemented in this package collection.

Before running ISAAC nodes, let’s describe how the ISAAC ROS project is structured. ISAAC ROS implements different perception algorithms in the form of the ROS 2 package. Each of them is linked to a code repository. At this link, you can find all the repositories currently maintained [2].

For example, if we are interested in performing marker detection (the first example of this section), we should refer to the main repository page for its documentation [3], and to its package for the tutorial on how to start [4]. In each starting tutorial, you will find all the steps needed to create and properly start the Docker container, download the asset directory (a sort of additional files needed for the package), and start the desired node. We will discuss these steps later in this section.

As of now, ISAAC is compatible only with ROS 2 Humble, but support for newer versions like Jazzy is planned. This won’t pose a problem for us, as NVIDIA provides all the necessary files to create a Docker container with the appropriate version of ROS 2. Furthermore, our Jazzy ROS setup will communicate seamlessly with the input and output of the NVIDIA packages over our computer network, making the communication process transparent. Therefore, we will establish a separate ROS 2 workspace for running the NVIDIA ISAAC code, while our packages, which utilize the output from ISAAC, will remain in our workspace with the desired ROS 2 version.

Another important feature of ISAAC is the implementation of the so-called NITROS (short for NVIDIA Isaac Toolkit for Robotics Operating System). NITROS is a framework that provides high-performance communication and interoperability between robotic applications and services. It is designed to enhance the capabilities of ROS 2 by leveraging NVIDIA’s hardware and software optimizations, offering efficient data handling and processing for robotics applications. In this way, the computational throughput to copy data from the CPU to the GPU before being processed is minimized.

Now that the general idea of ISAAC ROS has been introduced, we are ready to discuss some initial examples. First, let’s start defining the system requirements.

NVIDIA ROS requires the CUDA toolkit to be installed on your computer. CUDA (Compute Unified Device Architecture) is a parallel computing platform that allows developers to harness the processing power of a GPU. To install CUDA, your computer must have a CUDA-enabled graphics card.

Figure 10.8: Download page of the CUDA toolkit

Figure 10.8: Download page of the CUDA toolkit

To install the CUDA toolkit, it’s best to follow the steps provided on NVIDIA’s official developer page, where you can also download the package for the installation of CUDA [5]. Here, you can select the specs of your system (see Figure 10.8). After this selection, you will see a quick guide on how to install the downloaded package. After you’ve executed all the suggested steps, you can test the installation using the following command:

$ nvcc --version

Information on the installed CUDA toolkit version should be shown. Now that CUDA is installed, we can start configuring our environment:

  1. We need to set up our system to run Docker containers that have access to NVIDIA GPUs. You can do it by following this page [6]. From this page, follow the sections: Installing with Apt and Configuring Docker.
  2. We must create another workspace to store the ISAAC packages.

For that, we will run the following commands. First, install some programs needed for ISAAC:

$ sudo apt-get install git-lfs
  1. The environment variable ISAAC_ROS_WS will be set to point to the ROS 2 workspace where all the packages needed by ISAAC will be downloaded. For this reason, let’s start creating a new folder called isaac_ros-dev and set the value of this variable:
    $ mkdir -p ~/workspaces/isaac_ros-dev/src
    $ echo "export ISAAC_ROS_WS=${HOME}/workspaces/isaac_ros-dev/" >> ~/.bashrc
    source ~/.bashrc

In the next section, we will explore two common applications of computer vision in robotics: estimating the position and orientation of an object using AprilTag, and identifying the semantic class of an object using YOLO. Both applications will be tested with the ISAAC ROS framework. However, they can also run on a CPU alone, leveraging specific ROS-integrated packages.

As already said, ISAAC ROS has already solved several common problems of robotics. Among them, isaac_ros_apriltag provides an implementation of AprilTag, a fiducial marker system that can retrieve the 6D pose of an AR marker. ISAAC has already made available the resources to test these packages using the corresponding bagfiles. Follow these steps to run AprilTag with a bagfile:

  1. The first time that we run an ISAAC package, we must download isaac_ros_common in the proper workspace:
    $ cd ${ISAAC_ROS_WS}/src && \
    git clone -b release-3.1 https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_common.git isaac_ros_common
  2. Now it’s time to download the asset of the package. For this, the most convenient way is to follow the steps of the Download Quickstart Assets section at the link [7].
  3. Now, we can start with the AprilTag detector. Download the package from the NVIDIA repository:
    $ cd ${ISAAC_ROS_WS}/src && git clone -b release-3.1 https://github.com/NVIDIA-ISAAC-ROS/isaac_ros_apriltag.git isaac_ros_apriltag
  4. Start the container using the convenient script included in the common resource of ISAAC:
    $ cd ${ISAAC_ROS_WS}/src/isaac_ros_common && ./scripts/run_dev.sh
  5. Now you are in the NVIDIA container. The ROS 2 workspace is a shared volume; however, you should leave the code and the configuration file as they are. Install the dependencies of the AprilTag package:
    $ rosdep install --from-paths ${ISAAC_ROS_WS}/src/isaac_ros_apriltag --ignore-src –y
  6. Compile the workspace and source it:
    $ cd ${ISAAC_ROS_WS}/ && colcon build --symlink-install --packages-up-to isaac_ros_apriltag && source install/setup.bash
  7. Still inside the Docker container, install the dependencies:
    $ sudo apt-get install -y ros-humble-isaac-ros-examples
  8. Use isaac_ros_examples to start the AprilTag detector:
    $ ros2 launch isaac_ros_examples isaac_ros_examples.launch.py launch_fragments:=apriltag interface_specs_file:=${ISAAC_ROS_WS}/isaac_ros_assets/isaac_ros_apriltag/quickstart_interface_specs.json
  9. Now you should only start the bagfile. Start a new terminal in the same container:
    $ cd ${ISAAC_ROS_WS}/src/isaac_ros_common && \
    ./scripts/run_dev.sh
  10. Start the bagfile:
    ros2 bag play -l ${ISAAC_ROS_WS}/isaac_ros_assets/isaac_ros_apriltag/quickstart.bag --remap image:=image_rect camera_info:=camera_info_rect

Now, you can check the result of the detector using rqt_image_view, to display the input marker framed by the camera, and Rviz2 to visualize the pose of the markers in the camera frame, as shown in Figure 10.9. Notice that you can start these last two programs from ROS 2 Jazzy Docker or directly from your host computer. Do you now understand how it is possible to integrate ISAAC ROS into your ROS 2 programs?

Figure 10.9: Input-output of isaac_ros_apriltg

Figure 10.9: Input-output of isaac_ros_apriltg

A key aspect of image processing involves machine learning. Using machine learning techniques for image processing has shown great potential. In the next section, we will discuss a machine learning library integrated into ISAAC, which is used for the semantic classification of objects in images.

Performing object classification using YOLOv8 and NVIDIA ISAAC

Section titled “Performing object classification using YOLOv8 and NVIDIA ISAAC”

A typical problem of advanced robotics is related to object detection and classification using standard cameras. In this way, any robot can directly interact with the world in a smart and efficient way. In recent years, a widespread approach has been the use of the You Only Look Once (YOLO) library. This library permits you to detect and classify objects from just one image. The possibility to perform this classification with just one frame, makes YOLO usable in real-world applications. YOLO can run directly on the CPU. However, ISAAC provides an implementation of YOLO (version 8) to run on the GPU. In this way, YOLO runs faster, without impacting the performance of the programs running on the CPU.

In this case, the best way to execute the code is by following the steps on the documentation page of isaac_ros_yolov8 [8].

Of course, you can skip the first instruction – that is, the downloading of the isaac_ros_common package – if you already did so in the AprilTag example. To run YOLO, perform the following steps. Notice that all these actions must be executed in the Docker container:

  1. Download Quickstart Assets, as discussed on the documentation page.
  2. Start the Docker container:
    $ cd ${ISAAC_ROS_WS}/src/isaac_ros_common && \
    ./scripts/run_dev.sh
  3. Obtain the weight of the YOLO neural network. These weights are used from the neural network implemented in the YOLO library to recognize objects. These weights must be converted from PyTorch to Open Neural Network Exchange (ONNX) format:
    $ wget https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s.pt
    $ pip3 install ultralytics
    $ pip3 install onnx
  4. To convert the weights, we will use Python functions:
    $ python3
    >> from ultralytics import YOLO
    >> model = YOLO('yolov8s.pt')
    >> model.export(format='onnx')
    $ mkdir -p ${ISAAC_ROS_WS}/isaac_ros_assets/models/yolov8
    $ cp yolov8s.onnx ${ISAAC_ROS_WS}/isaac_ros_assets/models/yolov8
  5. Install the YOLO packages:
    $ sudo apt-get install -y ros-humble-isaac-ros-examples
    $ sudo apt-get install -y ros-humble-isaac-ros-yolov8 ros-humble-isaac-ros-dnn-image-encoder ros-humble-isaac-ros-tensor-rt
  6. Launch the YOLO node:
    $ cd /workspaces/isaac_ros-dev && ros2 launch isaac_ros_examples isaac_ros_examples.launch.py launch_fragments:=yolov8 interface_specs_file:=${ISAAC_ROS_WS}/isaac_ros_assets/isaac_ros_yolov8/quickstart_interface_specs.json model_file_path:=${ISAAC_ROS_WS}/isaac_ros_assets/models/yolov8/yolov8s.onnx engine_file_path:=${ISAAC_ROS_WS}/isaac_ros_assets/models/yolov8/yolov8s.plan
  7. Now it’s time to stream the data. After being correctly launched, YOLO expects an image or video stream data on the topic /image_rect (note that the word rect in the topic name stands for rectified – a rectified image refers to an image that has been processed to remove distortions or misalignments). You can publish such data using the camera publisher developed in this chapter, simply changing the output topic using the mapping function of the launch file. The result of the elaboration is shown on the /yolov8_processed_image topic, as shown in Figure 10.10.

Figure 10.10: Output of YOLOv8 running under the ISAAC framework

Figure 10.10: Output of YOLOv8 running under the ISAAC framework

NVIDIA Isaac ROS 2 is a powerful framework designed to harness the full potential of GPUs for processing images and other multimedia data. In addition to the pre-built packages it offers, developers can integrate their own algorithms into the Isaac ROS 2 framework. This integration optimizes the communication between the CPU and GPU, leading to faster processing and improved performance for your applications. To better understand how the GPU improves an image processing algorithm, NVIDIA ISAAC ROS provides a benchmark at this reference [9].

This chapter focuses on integrating computer vision algorithms with robotics. This integration allows robots to perceive their environment, detect objects, and better understand the world they operate in. However, computer vision is a complex field. Efficiently processing images and 3D data can be challenging. To simplify these computations, the robotics community often uses off-the-shelf libraries like OpenCV and PCL. In this chapter, we utilized these libraries, interfacing them with sensors such as a standard USB webcam and a RealSense depth sensor. We also explored ways to accelerate these tasks, first through GPU-based calculations and later by applying machine learning techniques for object detection and classification, using NVIDIA’s ROS ISAAC framework and the YOLOv8 library.

This chapter concludes the second part of the book. Moving forward, we will build on what we’ve learned to explore advanced tools and applications in robotics. The next chapter will dive into the integration of simulated aerial robotics.