diff --git a/stereo_image_proc/README.md b/stereo_image_proc/README.md new file mode 100644 index 000000000..9cdf02d07 --- /dev/null +++ b/stereo_image_proc/README.md @@ -0,0 +1,30 @@ +# stereo_image_proc + +`stereo_image_proc` processes the images of a stereo camera. +It computes a disparity image and a point cloud from the left and right images, after debayering and rectifying them with `image_proc`. + +For a stereo camera that publishes `/my_stereo/left/image_raw`, `/my_stereo/right/image_raw` and their `camera_info`: + +```console +ros2 launch stereo_image_proc stereo_image_proc.launch.py namespace:=my_stereo +ros2 run image_view stereo_view --ros-args -r stereo:=/my_stereo -r image:=image_rect_color +``` + +The launch file publishes `/my_stereo/disparity` and `/my_stereo/points2`, and the rectified images of each camera. + +| Component | Executable | Topics | +| --- | --- | --- | +| `stereo_image_proc::DisparityNode` | `disparity_node` | `left/image_rect` + `right/image_rect` + camera infos → `disparity` | +| `stereo_image_proc::PointCloudNode` | `point_cloud_node` | `disparity` + `left/image_rect_color` + camera infos → `points2` | + +## Documentation + +The full documentation, including all the parameters, a tutorial on a recorded stereo camera and a tutorial on choosing good stereo parameters, is in the [doc](https://github.com/ros-perception/image_pipeline/blob/rolling/stereo_image_proc/doc/index.rst) directory and it is published at [docs.ros.org](https://docs.ros.org/en/rolling/p/stereo_image_proc/). + +To build it locally, [install rosdoc2](https://github.com/ros-infrastructure/rosdoc2#installation) and run: + +```console +rosdoc2 build --package-path . +``` + +The result is written to `docs_output/stereo_image_proc/index.html`. diff --git a/stereo_image_proc/doc/choosing_good_stereo_params.rst b/stereo_image_proc/doc/choosing_good_stereo_params.rst new file mode 100644 index 000000000..df906e939 --- /dev/null +++ b/stereo_image_proc/doc/choosing_good_stereo_params.rst @@ -0,0 +1,201 @@ +.. _choosing_good_stereo_parameters: + +Choosing Good Stereo Parameters +=============================== + +This tutorial tunes the parameters of ``DisparityNode`` to get a good disparity image: dense, with few holes on the objects of interest, and clean, without noise. +It continues :ref:`first-tutorial`: the pipeline is running, the bag is playing in a loop, and ``stereo_view`` shows the disparity image. + +The images below were all computed on the same frame of the bag, so they can be compared. +While the bag plays, the bottle and the table rotate, and your images will change a little. + +.. contents:: + :local: + :depth: 1 + +How the matching works +---------------------- + +``DisparityNode`` uses block matching. +For each pixel of the left image, it takes a small window around it, the correlation window, and searches the same row of the right image for the most similar window. +The distance, in pixels, between the two windows is the disparity. +Close points have a large disparity, far points a small one. + +The search covers the disparities from ``min_disparity`` to ``min_disparity + disparity_range - 1``. +This range defines the *horopter*, the range of depths that the matcher can see. +Points outside of it are not found. + +Then filters remove the doubtful matches: matches with too little texture (``texture_threshold``), matches not much better than the second best (``uniqueness_ratio``), and small isolated regions (``speckle_size`` and ``speckle_range``). + +Change the parameters while the node runs +----------------------------------------- + +All the matching parameters can be changed while the node runs. +Run ``rqt_reconfigure``, and select ``disparity_node`` under ``narrow_stereo_textured``: + +.. code-block:: console + + $ ros2 run rqt_reconfigure rqt_reconfigure + +.. image:: images/rqt_reconfigure.png + :alt: rqt_reconfigure showing the parameters of disparity_node + +You can also use ``ros2 param set``, as in the rest of this tutorial. +Change one parameter at a time, and look at the effect on the disparity image. + +1. Remove the speckles +---------------------- + +With the default parameters, there are small blobs of random disparity where the table and the bottle should be: + +.. image:: images/speckles.png + :alt: disparity image with speckles on the table + :width: 60% + +These *speckles* are false matches. +Block matching often makes them near the edges of objects, where the correlation window sees the object on one side and the background on the other. +Here, the matcher also finds small false matches in the texture projected on the table. + +The speckle filter removes regions of similar disparity smaller than ``speckle_size`` pixels. +Two neighbor pixels are in the same region if their disparities differ by at most ``speckle_range``. +The objects of this scene are large, so raise ``speckle_size`` from 100 to 1000 pixels, the maximum: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node speckle_size 1000 + +.. image:: images/table_object.png + :alt: disparity image without speckles + :width: 60% + +The speckles are gone. +If thin objects disappear too, lower ``speckle_size``. + +2. Find the table and the bottle +-------------------------------- + +The wall behind the table has a nice gradient of disparity, but there is a large hole where the table and the bottle should be. +They are too close to the camera: their disparity is larger than 63, the end of the default range ``[0, 63]``. + +Double ``disparity_range`` to 128, so that the range becomes ``[0, 127]``: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node disparity_range 128 + +.. image:: images/disparity_range_128.png + :alt: disparity image with disparity_range set to 128 + :width: 60% + +The table and the bottle are found. +The colors are scaled to the new range, so the wall is now blue. + +Two other things changed: + +* The gray band on the left of the image is twice as large. + The leftmost pixels of the left image cannot be searched over the whole range, because the matching window would leave the right image. + This band is a little wider than ``min_disparity + disparity_range`` pixels. +* There is a gray area on the left of the bottle. + This part of the table is seen by the left camera, but hidden by the bottle for the right camera, so it cannot be matched. + +``disparity_range`` must be a multiple of 16. +A larger range sees closer objects, but takes more time: use the smallest range that covers your scene. + +3. Move the range with min_disparity +------------------------------------ + +``min_disparity`` moves the range. +It is normally 0, to see as far as possible: a disparity of 0 is a point at infinity. + +* To see objects even closer to the camera, raise it. This moves the horopter toward the camera, at the cost of far objects. +* If the cameras are *verged*, inclined toward each other, far points have a negative disparity. Use a negative value to see them. + +For example, set ``disparity_range`` to 96, and raise ``min_disparity`` step by step: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node disparity_range 96 + $ ros2 param set /narrow_stereo_textured/disparity_node min_disparity 50 + +The disparity of the wall is about 51. +With ``min_disparity`` 50, it is at the far end of the range, in dark red. +Raise ``min_disparity`` to 60, for the range ``[60, 155]``: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node min_disparity 60 + +.. image:: images/disparity_min_60.png + :alt: disparity image with min_disparity set to 60 + :width: 60% + +The wall is now out of range and disappears, while the table and the bottle are still found. +The gray band on the left grew again, to the new ``min_disparity + disparity_range``. + +Set the range back before going on: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node min_disparity 0 + $ ros2 param set /narrow_stereo_textured/disparity_node disparity_range 128 + +4. Other parameters +------------------- + +The other parameters are changed less often. + +``correlation_window_size`` is the size of the matching window, 15 by 15 pixels by default. +A larger window fills small holes in the disparity image, but smears the edges of the objects. +A smaller window keeps the details, but gives more holes and more noise. +For example, with ``correlation_window_size`` set to 9: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node correlation_window_size 9 + +.. image:: images/correlation_windows_9.png + :alt: disparity image with correlation_window_size set to 9 + :width: 60% + +``texture_threshold`` rejects windows with too little texture, like blank walls. +Raise it to remove noisy matches on surfaces without texture, lower it to keep more matches on surfaces with little texture. + +``uniqueness_ratio`` rejects a match if it is not better than the second best match by this margin, in percent. +Raise it if ``texture_threshold`` and the speckle filter still let false matches through. + +``prefilter_size`` and ``prefilter_cap`` normalize the brightness of the images before the matching. +This makes the matching robust to brightness differences between the two cameras. +The defaults are usually fine. + +5. Semi-global block matching +----------------------------- + +``stereo_algorithm`` 1 selects semi-global block matching (SGBM). +It is slower than block matching, but it also takes into account the disparity of the neighbor pixels, and gives denser disparity images, in particular on surfaces with little texture. +Here, with ``correlation_window_size`` back to 15 and ``disparity_range`` 128: + +.. code-block:: console + + $ ros2 param set /narrow_stereo_textured/disparity_node correlation_window_size 15 + $ ros2 param set /narrow_stereo_textured/disparity_node stereo_algorithm 1 + +.. image:: images/disparity_sgbm.png + :alt: disparity image computed with semi-global block matching + :width: 60% + +SGBM has its own parameters: ``P1`` and ``P2`` control how smooth the disparity is, ``disp12_max_diff`` enables a left-right consistency check, and ``sgbm_mode`` selects a variant. +``texture_threshold`` and ``prefilter_size`` are not used by SGBM. +See :ref:`DisparityNode` for all the parameters. + +Keep the parameters +------------------- + +Parameters changed at runtime are lost when the node stops. +To keep them, pass them to the launch file: + +.. code-block:: console + + $ ros2 launch stereo_image_proc stereo_image_proc.launch.py namespace:=narrow_stereo_textured \ + speckle_size:=1000 disparity_range:=128 + +or save them from ``rqt_reconfigure`` (the save button at the top of the parameters), or with ``ros2 param dump /narrow_stereo_textured/disparity_node``. diff --git a/stereo_image_proc/doc/components.rst b/stereo_image_proc/doc/components.rst index 51b482bb4..4db3c078f 100644 --- a/stereo_image_proc/doc/components.rst +++ b/stereo_image_proc/doc/components.rst @@ -1,133 +1,129 @@ Nodes and Components ==================== -This package includes a number of ROS 2 components that can be assembled -into stereo image processing pipelines. -See the tutorial :ref:`Launch stereo_image_proc Components`. +Both components can be loaded in a container, which is what ``stereo_image_proc.launch.py`` does, or run as standalone nodes. -Alternatively, each component can be run as a standalone node. +.. _DisparityNode: stereo_image_proc::DisparityNode -------------------------------- -Performs block matching on a pair of rectified stereo images, producing a -disparity image. Also available as a standalone node with the name -``disparity_node``. + +Computes a disparity image from a pair of rectified stereo images, with OpenCV's `block matching `_ or `semi-global block matching `_. +The images are converted to ``mono8`` before matching, so color images can be used too. +The left image, the right image and both camera infos must have the same timestamp, or close timestamps with ``approximate_sync``. +Executable: ``disparity_node``. Default node name: ``disparity_node``. + +The disparity image is in the frame of the left camera info. +See :ref:`choosing_good_stereo_parameters` for how to tune the parameters. Subscribed Topics ^^^^^^^^^^^^^^^^^ - * **left/camera_info** (sensor_msgs/CameraInfo): Left camera metadata. - * **left/image_rect** (sensor_msgs/Image): Left monochrome rectified - image stream. - * **right/camera_info** (sensor_msgs/CameraInfo): Right camera metadata. - * **right/image_rect** (sensor_msgs/Image): Right monochrome rectified - image stream. +* **left/image_rect** (sensor_msgs/msg/Image): Rectified left image. +* **left/camera_info** (sensor_msgs/msg/CameraInfo): Camera info of the left camera, next to ``left/image_rect``. +* **right/image_rect** (sensor_msgs/msg/Image): Rectified right image. +* **right/camera_info** (sensor_msgs/msg/CameraInfo): Camera info of the right camera, next to ``right/image_rect``. + +The camera info topics are next to the image topics: if ``left/image_rect`` is remapped to ``/my_stereo/left/image_rect_color``, the left camera info is ``/my_stereo/left/camera_info``. +Set ``use_image_transport_camera_info`` to false to remap ``left/camera_info`` and ``right/camera_info`` independently. + +The node only subscribes while something subscribes to ``disparity``. Published Topics ^^^^^^^^^^^^^^^^ - * **disparity** (sensor_msgs/DisparityImage): Floating point disparity - image with metadata. +* **disparity** (stereo_msgs/msg/DisparityImage): Disparity image, in pixels, as a ``32FC1`` image. + Pixels without a match have a value lower than ``min_disparity``. Parameters ^^^^^^^^^^ -*Disparity algorithm variant* - * **sgbm_mode** (int, default: 0): Stereo matching algorithm variation: - - * SGBM (0) - * HH (1) - * SGBM_3WAY (2) - * HH4 (3) - -*Disparity pre-filtering* - - * **prefilter_size** (int, default: 9): Normalization window size, pixels. - * **prefilter_cap** (int, default: 31): Bound on normalized pixel values. - -*Disparity correlation* - - * **correlation_window_size** (int, default: 15): Edge size (pixels) of the - correlation window for matching. Values must be odd, in the range 5 to 255 - (but with an extra performance hit for values larger than 21). Larger values - have smoother disparity results, but smear out small features and depth - discontinuities. - * **min_disparity** (int, default: 0): Minimum disparity, or the offset to the - disparity search window. By setting to a positive value, the cameras become - more "cross-eyed" and will find objects closer to the cameras. If the cameras - are "verged" (inclined toward each other), it may be appropriate to set - min_disparity to a negative value. When min_disparity is greater than 0, - objects at large distances will not be found. - * **disparity_range** (int, default: 64): The size of the disparity search - window (pixels). Together with min_disparity, this defines the "horopter," - the 3D volume that is visible to the stereo algorithm. - -*Disparity post-filtering* - - * **uniqueness_ratio** (double, default: 15.0): Filters disparity readings - based on a comparison to the next-best correlation along the epipolar - line. Matches where uniqueness_ratio > (best_match - next_match) / next_match - are filtered out. - * **texture_threshold** (int, default: 10): Filters disparity readings based on - the amount of texture in the correlation window. - * **speckle_size** (int, default: 100): Filters disparity regions that are less - than this number of pixels. For example, a value of 100 means that all regions - with fewer than 100 pixels will be rejected. - * **speckle_range** (int, default: 4): Groups disparity regions based on their - connectedness. Disparities are grouped together in the same region if they are - within this distance in pixels. - -*Synchronization* - - * **approximate_sync** (bool, default: false): Whether to use approximate - synchronization. Set to true if the left and right cameras do not produce - exactly synced timestamps. - * **approximate_sync_tolerance_seconds** (double, default: 0.0): Tolerance - when using approximate sync. - * **image_transport** (string, default: raw): Image transport to use for left - image subscriber. - * **queue size** (int, default: 5): Size of message queue for each synchronized - topic. You may need to raise this if images take significantly longer to travel - over the network than camera info and/or the delay from disparity processing - is too long. - -*Common* - * **use_image_transport_camera_info** (bool, default: true): To control whether DisparityNode uses image_transport::getCameraInfoTopic for deriving camera_info topics. To set false, the node directly uses the camera_info topics specified via remapping (e.g., left/camera_info and right/camera_info), bypassing image_transport's derivation logic. +All the matching parameters can be changed at runtime, for example with ``ros2 param set`` or ``rqt_reconfigure``. + +*Algorithm* + +* **stereo_algorithm** (int, default: 0): Matching algorithm: + + * 0: block matching (BM), the fastest. + * 1: semi-global block matching (SGBM), slower, but denser on surfaces with little texture. + +*Search range* + +* **min_disparity** (int, default: 0, from -2048 to 2048): Smallest disparity searched, in pixels. + Raise it to see objects closer to the cameras, at the cost of far objects. + Use a negative value if the cameras are verged (inclined toward each other). +* **disparity_range** (int, default: 64, from 32 to 4096, multiple of 16): Number of disparities searched, in pixels. + The disparities searched are ``[min_disparity, min_disparity + disparity_range)``. + Together with ``min_disparity``, this defines the "horopter", the range of depths seen by the matcher. + +*Matching* + +* **correlation_window_size** (int, default: 15, odd, from 5 to 255): Side of the square window matched between the two images, in pixels. + Larger values give smoother and denser disparity images, but smear small details and depth discontinuities. + Values larger than 21 are slow. +* **prefilter_size** (int, default: 9, odd, from 5 to 255): Size of the window that normalizes the brightness of the images before matching. BM only. +* **prefilter_cap** (int, default: 31, from 1 to 63): Bound on the normalized pixel values. + +*Filtering* + +* **uniqueness_ratio** (double, default: 15.0, from 0.0 to 100.0): Margin, in percent, by which the best match must beat the second best. + Raise it to remove ambiguous matches. The value is truncated to an integer. +* **texture_threshold** (int, default: 10, from 0 to 10000): Minimum amount of texture in the window for a match. BM only. +* **speckle_size** (int, default: 100, from 0 to 1000): Regions of similar disparity smaller than this, in pixels, are removed as noise. +* **speckle_range** (int, default: 4, from 0 to 31): Largest difference of disparity, in pixels, between neighbors of the same region. + +*Semi-global block matching only* + +* **sgbm_mode** (int, default: 0): Variant of SGBM: + + * 0: SGBM, 5 directions. + * 1: HH, full 8 directions, uses much more memory. + * 2: SGBM_3WAY, 3 directions, faster. + * 3: HH4, 4 directions. + +* **P1** (double, default: 200.0, from 0.0 to 4000.0): Penalty for a disparity change of 1 between neighbor pixels. Larger values give smoother disparity images. +* **P2** (double, default: 400.0, from 0.0 to 4000.0): Penalty for a disparity change of more than 1 between neighbor pixels. Should be larger than ``P1``: OpenCV raises it to ``P1 + 1`` otherwise. +* **disp12_max_diff** (int, default: 0, from 0 to 128): Maximum difference, in pixels, between the left-to-right and the right-to-left disparities. 0 disables the check. + +*Synchronization and transport*, read only when the node starts: + +* **approximate_sync** (bool, default: false): Use approximate synchronization. Set it to true if the left and right cameras do not produce images with exactly the same timestamp. +* **approximate_sync_tolerance_seconds** (double, default: 0.0): Maximum time difference between the synchronized messages, with ``approximate_sync``. 0.0 means no limit. +* **queue_size** (int, default: 5): Size of the synchronization queue of each topic. + Raise it if the images arrive much later than the camera infos, for example over a slow network. +* **image_transport** (string, default: ``raw``): Transport used to subscribe to the left and right images. +* **use_image_transport_camera_info** (bool, default: true): If true, the camera info topics are next to the image topics. + If false, the node subscribes to ``left/camera_info`` and ``right/camera_info``, which can be remapped independently. + +.. _PointCloudNode: stereo_image_proc::PointCloudNode --------------------------------- -Combines a rectified color image and disparity image to produce a -``sensor_msgs::PointCloud2`` point cloud. Also available as a standalone -node ``point_cloud_node``. -Note: ROS 1 had both a ``point_cloud`` and ``point_cloud2`` version to -handle the now deprecated and removed ``sensor_msgs::PointCloud`` and -``stereo_msgs::PointCloud2``. This node corresponds to the ``point_cloud2`` -version although we have dropped the ``2``. +Computes a point cloud from a disparity image, the camera infos of both cameras, and the rectified left image for the color. +The four messages must have the same timestamp, or close timestamps with ``approximate_sync``. +Executable: ``point_cloud_node``. Default node name: ``point_cloud_node``. + +The point cloud is organized: it has the width and height of the disparity image, one point per pixel, and ``NaN`` points where there is no disparity. +It is in the frame of the disparity image, the optical frame of the left camera: x right, y down, z forward. Subscribed Topics ^^^^^^^^^^^^^^^^^ - * **disparity** (stereo_msgs/DisparityImage): Floating point disparity - image with metadata. - * **left/camera_info** (sensor_msgs/CameraInfo): Left camera metadata. - * **left/image_rect_color** (sensor_msgs/Image): Rectified image. - * **right/camera_info** (sensor_msgs/CameraInfo): Right camera metada. +* **disparity** (stereo_msgs/msg/DisparityImage): Disparity image, for example from ``DisparityNode``. +* **left/image_rect_color** (sensor_msgs/msg/Image): Rectified left image, for the color of the points. ``mono8``, ``rgb8`` or ``bgr8``. +* **left/camera_info** (sensor_msgs/msg/CameraInfo): Camera info of the left camera, next to ``left/image_rect_color``. +* **right/camera_info** (sensor_msgs/msg/CameraInfo): Camera info of the right camera. + +The node only subscribes while something subscribes to ``points2``. Published Topics ^^^^^^^^^^^^^^^^ - * **points2** (sensor_msgs/PointCloud2): Stereo point cloud with RGB color. +* **points2** (sensor_msgs/msg/PointCloud2): Point cloud, with the fields ``x``, ``y``, ``z`` and, with ``use_color``, ``rgb``. Parameters ^^^^^^^^^^ - * **approximate_sync** (bool, default: false): Whether to use approximate - synchronization. Set to true if the left and right cameras do not produce - exactly synced timestamps. - * **avoid_point_cloud_padding** (bool, default: false): Avoid using alignment - padding in the generated point cloud. This reduces bandwidth requirements, - as the point cloud size is halved. Using point clouds without alignment - padding might degrade performance for some algorithms. - * **image_transport** (string, default: raw): Image transport to use for left - image subscriber. - * **queue size** (int, default: 5): Size of message queue for each synchronized - topic. You may need to raise this if images take significantly longer to travel - over the network than camera info and/or the delay from disparity processing - is too long. - * **use_color** (oool, default: true): If false, point cloud will be XYZ only. +* **use_color** (bool, default: true): Add the ``rgb`` field, from ``left/image_rect_color``. Can be changed at runtime. +* **avoid_point_cloud_padding** (bool, default: false): Pack the fields without alignment padding. + This halves the size of the point cloud, but some algorithms may be slower with it. Can be changed at runtime. +* **approximate_sync** (bool, default: false): Use approximate synchronization. +* **approximate_sync_tolerance_seconds** (double, default: 0.0): Maximum time difference between the synchronized messages, with ``approximate_sync``. 0.0 means no limit. +* **queue_size** (int, default: 5): Size of the synchronization queue of each topic. +* **image_transport** (string, default: ``raw``): Transport used to subscribe to ``left/image_rect_color``. diff --git a/stereo_image_proc/doc/conf.py b/stereo_image_proc/doc/conf.py index b6fda617d..621f67f9f 100644 --- a/stereo_image_proc/doc/conf.py +++ b/stereo_image_proc/doc/conf.py @@ -12,183 +12,39 @@ # See the License for the specific language governing permissions and # limitations under the License. -# -*- coding: utf-8 -*- -# -# Configuration file for the Sphinx documentation builder. -# -# This file does only contain a selection of the most common options. For a -# full list see the documentation: -# http://www.sphinx-doc.org/en/master/config -# -- Path setup -------------------------------------------------------------- - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. +# Sphinx configuration for the stereo_image_proc package documentation. # -import os -import sys -sys.path.insert(0, os.path.abspath('.')) - - -# -- Project information ----------------------------------------------------- - -project = 'stereo_image_proc' -copyright = '2008-2024, Open Source Robotics Foundation, Inc.' # noqa -author = 'Open Source Robotics Foundation, Inc.' - -# The short X.Y version -version = '' -# The full version, including alpha/beta/rc tags -release = '3.2.1' - +# This file is not used directly: rosdoc2 exec()s it from a generated conf.py +# and then adds (or overrides) settings such as the project name, the version +# (both taken from package.xml), the theme and the breathe/exhale configuration +# used for the C++ API. Build the documentation with: +# +# rosdoc2 build --package-path # -- General configuration --------------------------------------------------- -# If your documentation needs a minimal Sphinx version, state it here. -# -# needs_sphinx = '1.0' - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.autosummary', - 'sphinx.ext.doctest', - 'sphinx.ext.coverage', 'sphinx_rtd_theme', ] -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The suffix(es) of source filenames. -# You can specify multiple suffix as a list of string: -# -# source_suffix = ['.rst', '.md'] source_suffix = '.rst' - -# The master toctree document. master_doc = 'index' -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = None - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = [] +# rosdoc2 copies this directory a second time under 'user_docs/' and generates +# 'user_docs.rst' / '__readme_include.rst' wrappers for packages that do not +# ship their own index. This one does, and index.rst already links the +# tutorials and the API reference, so exclude the duplicate tree. +exclude_patterns = ['user_docs', 'user_docs.rst', 'user_docs_tutorials.rst', + '__readme_include.rst'] -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = None +project = 'stereo_image_proc' +copyright = '2008-2024, Open Source Robotics Foundation, Inc.' # noqa: A001 +author = 'Open Source Robotics Foundation, Inc.' +pygments_style = 'sphinx' # -- Options for HTML output ------------------------------------------------- -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# html_theme = 'sphinx_rtd_theme' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# -# html_theme_options = {} - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = [] - -# Custom sidebar templates, must be a dictionary that maps document names -# to template names. -# -# The default sidebars (for documents that don't match any pattern) are -# defined by theme itself. Builtin themes are using these templates by -# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', -# 'searchbox.html']``. -# -# html_sidebars = {} - - -# -- Options for HTMLHelp output --------------------------------------------- - -# Output file base name for HTML help builder. -htmlhelp_basename = 'image_proc_doc' - - -# -- Options for LaTeX output ------------------------------------------------ - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - - -# -- Options for manual page output ------------------------------------------ - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - (master_doc, 'stereo_image_proc', 'stereo_image_proc Documentation', - [author], 1) -] - - -# -- Options for Texinfo output ---------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - (master_doc, 'stereo_image_proc', 'stereo_image_proc Documentation', - author, 'stereo_image_proc', 'ROS 2 components for stereo image processing.', - 'Miscellaneous'), -] - - -# -- Options for Epub output ------------------------------------------------- - -# Bibliographic Dublin Core info. -epub_title = project - -# The unique identifier of the text. This can be a ISBN number -# or the project homepage. -# -# epub_identifier = '' - -# A unique identification for the text. -# -# epub_uid = '' - -# A list of files that should not be packed into the epub file. -epub_exclude_files = ['search.html'] - - -# -- Extension configuration ------------------------------------------------- - -autoclass_content = 'both' - -autodoc_default_options = { - 'members': True, # document members - 'undoc-members': True, # also document members without documentation -} +htmlhelp_basename = 'stereo_image_proc_doc' diff --git a/stereo_image_proc/doc/configuration.rst b/stereo_image_proc/doc/configuration.rst deleted file mode 100644 index c5d5710e7..000000000 --- a/stereo_image_proc/doc/configuration.rst +++ /dev/null @@ -1,91 +0,0 @@ -.. _Configuration: - -Configuration -============= - -Overview --------- - -The ``stereo_image_proc.launch.py`` launch file provides a full example and -performs rectification and de-mosaicing of raw stereo camera image pairs. -It also perform stereo processing to generate disparity images and point clouds. - -In topic names below, left and right are remapped using the ``left_namespace`` -and ``right_namespace`` launch file parameters. - -|stereo| - -.. |stereo| image:: images/stereo_image_proc.png - :width: 75% - -All processing is on demand. Color processing is performed only if there is a -subscriber to a color topic. Rectification is performed only if there is a -subscriber to a rectified topic. Disparities and point clouds are generated -only if there is a subscriber to a relevant topic. While there are no subscribers -to output topics, the nodes unsubscribe from the ``image_raw`` and -``camera_info`` topics. - -Point clouds are generated in the optical frame of the left imager -(X Right, Y Down, Z out): - -|stereo_frames| - -.. |stereo_frames| image:: images/stereo_frames.png - :width: 50% - - -Quick Start ------------ - -Make sure your stereo camera driver(s) are running. You can check -``ros2 topic list | grep image_raw`` to see the available raw image -topics from compatible drivers. - -To get rectified and/or colorized image streams, you need to launch the -``stereo_image_proc.launch.py`` launch file. If you are running on a -robot, it's probably best to run the launch file there. For example, -if your stereo camera driver(s) are publishing: - -.. code-block:: - - /stereo/left/image_raw - /stereo/left/camera_info - /stereo/right/image_raw - /stereo/right/camera_info - -you could do: - -.. code-block:: bash - - ros2 launch stereo_image_proc stereo_image_proc.launch.py namespace:=stereo - -Notice that we add the ``stereo`` namespace. Internally the launch file -also has a ``left_namespace`` and ``right_namespace`` which default to -``left`` and ``right``. Using this launch file is equivalent to Launching -two instances of the ``image_proc/image_proc.launch.py`` launch file in the -``stereo/left`` and ``stereo/right`` namespaces, with the addition of -the stereo outputs: disparity images (``stereo/disparity`` topic) and point -clouds (``stereo/points2`` topic) - -In a separate terminal (on your home machine, if you are running on a robot): - -.. code-block:: bash - - $ ros2 run image_view image_view image:=/stereo/left/image_rect_color - -This will display a rectified color image from the left stereo camera. -Alternatively, stereo_view will show you both the left and right images -as well as a color-mapped disparity image: - -.. code-block:: bash - - $ ros2 run image_view stereo_view stereo:=/stereo image:=image_rect_color - -To view point clouds, you can use ``rviz2``. - -Choosing Good Stereo Parameters -------------------------------- - -There is an extensive tutorial on the -`ROS 1 wiki `, -however not all components exist in ROS 2 yet. diff --git a/stereo_image_proc/doc/docutils.conf b/stereo_image_proc/doc/docutils.conf new file mode 100644 index 000000000..fe7028b08 --- /dev/null +++ b/stereo_image_proc/doc/docutils.conf @@ -0,0 +1,4 @@ +[restructuredtext parser] +# rosdoc2/exhale emits the generated class hierarchy as a single very long line, +# which can exceed docutils' 10000-character default. +line_length_limit: 200000 diff --git a/stereo_image_proc/doc/images/correlation_windows_9.png b/stereo_image_proc/doc/images/correlation_windows_9.png new file mode 100644 index 000000000..999ccd4a7 Binary files /dev/null and b/stereo_image_proc/doc/images/correlation_windows_9.png differ diff --git a/stereo_image_proc/doc/images/disparity.jpg b/stereo_image_proc/doc/images/disparity.jpg deleted file mode 100644 index 7b053e012..000000000 Binary files a/stereo_image_proc/doc/images/disparity.jpg and /dev/null differ diff --git a/stereo_image_proc/doc/images/disparity_min_60.png b/stereo_image_proc/doc/images/disparity_min_60.png new file mode 100644 index 000000000..bc84233ac Binary files /dev/null and b/stereo_image_proc/doc/images/disparity_min_60.png differ diff --git a/stereo_image_proc/doc/images/disparity_range_128.png b/stereo_image_proc/doc/images/disparity_range_128.png new file mode 100644 index 000000000..02c2cb2a8 Binary files /dev/null and b/stereo_image_proc/doc/images/disparity_range_128.png differ diff --git a/stereo_image_proc/doc/images/disparity_sgbm.png b/stereo_image_proc/doc/images/disparity_sgbm.png new file mode 100644 index 000000000..e8804f2ab Binary files /dev/null and b/stereo_image_proc/doc/images/disparity_sgbm.png differ diff --git a/stereo_image_proc/doc/images/raw.png b/stereo_image_proc/doc/images/raw.png deleted file mode 100644 index 89954f9b3..000000000 Binary files a/stereo_image_proc/doc/images/raw.png and /dev/null differ diff --git a/stereo_image_proc/doc/images/rqt_bag_stereo.png b/stereo_image_proc/doc/images/rqt_bag_stereo.png new file mode 100644 index 000000000..27004c261 Binary files /dev/null and b/stereo_image_proc/doc/images/rqt_bag_stereo.png differ diff --git a/stereo_image_proc/doc/images/rqt_reconfigure.png b/stereo_image_proc/doc/images/rqt_reconfigure.png new file mode 100644 index 000000000..d92cfc2b8 Binary files /dev/null and b/stereo_image_proc/doc/images/rqt_reconfigure.png differ diff --git a/stereo_image_proc/doc/images/speckles.png b/stereo_image_proc/doc/images/speckles.png new file mode 100644 index 000000000..4bc309519 Binary files /dev/null and b/stereo_image_proc/doc/images/speckles.png differ diff --git a/stereo_image_proc/doc/images/stereo_image_proc.png b/stereo_image_proc/doc/images/stereo_image_proc.png deleted file mode 100644 index e54db0dc3..000000000 Binary files a/stereo_image_proc/doc/images/stereo_image_proc.png and /dev/null differ diff --git a/stereo_image_proc/doc/images/table_object.png b/stereo_image_proc/doc/images/table_object.png new file mode 100644 index 000000000..56fe4183b Binary files /dev/null and b/stereo_image_proc/doc/images/table_object.png differ diff --git a/stereo_image_proc/doc/index.rst b/stereo_image_proc/doc/index.rst index 800b9f7d2..82f244b32 100644 --- a/stereo_image_proc/doc/index.rst +++ b/stereo_image_proc/doc/index.rst @@ -1,57 +1,118 @@ -Overview -======== +stereo_image_proc +================= -This package contains a number of ROS 2 components, nodes, and launch files -for stereo image processing. +``stereo_image_proc`` processes the images of a stereo camera, a pair of calibrated cameras side by side. +It computes a disparity image, how much each point moves between the left and the right image, and from it a point cloud. +It does for a stereo camera what `image_proc `_ does for a single camera, and uses ``image_proc`` to debayer and rectify the images of each camera. -If porting from ROS 1, please note that the ``stereo_image_proc`` node no -longer exists and instead you should use ``stereo_image_proc.launch.py``. -See the :ref:`Configuration` page for more detail. +For a stereo camera that publishes ``/my_stereo/left/image_raw``, ``/my_stereo/right/image_raw`` and their ``camera_info``: -``DisparityNode`` can compute disparity images from incoming stereo -pairs using -`OpenCV's block matching `_ -algorithm. These are best inspected -using ``stereo_view`` which is available in the ``image_view`` package. +.. code-block:: console -``PointCloudNode`` can produce point clouds, which you can view in ``rviz``, -and process with PCL. + $ ros2 launch stereo_image_proc stereo_image_proc.launch.py namespace:=my_stereo + $ ros2 run image_view stereo_view --ros-args -r stereo:=/my_stereo -r image:=image_rect_color -The image below shows the **left/image_raw** and **right_image_raw**. -These are the raw images from each camera. +.. image:: images/disparity_range_128.png + :width: 50% -|raw| +See :doc:`tutorials` to get started, :doc:`choosing_good_stereo_params` to tune the disparity image, and :doc:`components` for the topics and parameters of each node. -.. |raw| image:: images/raw.png +.. toctree:: + :maxdepth: 2 -Below are the **left/image_rect_color** and **right/image_rect_color**. -These are the rectified images from each camera. -The red lines show that the same point in the real world -lies on the same horizontal line in each rectified image. + self + components + tutorials + choosing_good_stereo_params + references + Package information -|rectified| +1. Nodes +-------- -.. |rectified| image:: images/rectified.png +.. list-table:: + :header-rows: 1 + :widths: 20 30 50 -The resulting disparity image is shown below, -viewed with ``stereo_view`` from the ``image_view`` package. + * - Executable + - Component + - Description + * - ``disparity_node`` + - :ref:`stereo_image_proc::DisparityNode ` + - Computes a disparity image from the rectified left and right images. + * - ``point_cloud_node`` + - :ref:`stereo_image_proc::PointCloudNode ` + - Computes a point cloud from a disparity image. -|disparity| +There is no ``stereo_image_proc`` node as in ROS 1: use the ``stereo_image_proc.launch.py`` launch file instead. -.. |disparity| image:: images/disparity.jpg +.. _launch-file: +2. The launch file +------------------ -.. toctree:: - :maxdepth: 2 +``stereo_image_proc.launch.py`` runs the whole pipeline in one container: - self - components - configuration - tutorials - stereo_image_proc +* for each camera, the ``image_proc`` components that debayer and rectify the images (see `image_proc `_), +* a ``DisparityNode``, on ``left/image_rect`` and ``right/image_rect``, +* a ``PointCloudNode``, on the disparity image and ``left/image_rect_color``. + +The rectification uses the stereo calibration to align the two images: the same point of the scene is on the same row in both rectified images, as shown by the red lines below. +The matcher only has to search along that row. + +.. image:: images/rectified.png + :alt: left and right rectified images, with horizontal lines through the same points + +With ``namespace:=my_stereo``, it subscribes to: + +* ``/my_stereo/left/image_raw`` and ``/my_stereo/left/camera_info`` +* ``/my_stereo/right/image_raw`` and ``/my_stereo/right/camera_info`` + +and publishes: + +* ``/my_stereo/left/image_mono``, ``image_color``, ``image_rect`` and ``image_rect_color``, and the same for ``right`` +* ``/my_stereo/disparity`` (stereo_msgs/msg/DisparityImage) +* ``/my_stereo/points2`` (sensor_msgs/msg/PointCloud2) + +All processing is on demand: each node only subscribes to its inputs while something subscribes to its outputs. +For example, no disparity is computed until something subscribes to ``disparity`` or ``points2``. + +The left and right images must have the same timestamp. +If they do not, set ``approximate_sync:=true``. + +The main launch arguments are: + +* ``namespace`` (default: ``''``): Namespace of the stereo camera. +* ``left_namespace``, ``right_namespace`` (default: ``left``, ``right``): Namespaces of the two cameras, inside ``namespace``. +* ``approximate_sync`` (default: ``False``): Use approximate synchronization. +* ``launch_image_proc`` (default: ``True``): Run the ``image_proc`` components. Set it to ``False`` if the camera driver already publishes rectified images. +* ``container`` (default: ``''``): Load the components into this existing container, instead of starting a new one. +* ``use_color`` and ``avoid_point_cloud_padding``: Parameters of the ``PointCloudNode``. +* ``stereo_algorithm``, ``min_disparity``, ``disparity_range``, ``correlation_window_size`` and the other matching parameters of the ``DisparityNode``, with the same defaults. + +Run ``ros2 launch stereo_image_proc stereo_image_proc.launch.py --show-args`` for the full list. + +3. Frames +--------- + +The disparity image and the point cloud are in the frame of the left camera, the ``frame_id`` of its ``camera_info``. +It is an optical frame: x to the right, y down, and z forward, along the optical axis. + +.. image:: images/stereo_frames.png + :width: 40% + +The distance between the two cameras, the baseline, is taken from the projection matrix ``P`` of the right ``camera_info``, which is set by the stereo calibration of `camera_calibration `_. + +.. _known-issues: -Indices and tables -================== +4. Known issues +--------------- -* :ref:`genindex` -* :ref:`search` +* **Nothing is published with Fast DDS** if the camera info is published with a volatile durability, as most cameras and ``ros2 bag play`` do. + With Fast DDS, the default middleware, the rectification nodes of ``image_proc`` ask for a transient local durability and do not receive the camera info. + They log ``New publisher discovered on topic '.../camera_info', offering incompatible QoS``. + This is fixed by `#1232 `_. + Until then, use another middleware, for example with ``export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp``. +* **The valid_window of the disparity image is wrong.** + ``DisparityNode`` computes it before the size of the image is known, so its width and height are huge numbers. + Do not use it. diff --git a/stereo_image_proc/doc/references.rst b/stereo_image_proc/doc/references.rst new file mode 100644 index 000000000..b1c9293da --- /dev/null +++ b/stereo_image_proc/doc/references.rst @@ -0,0 +1,7 @@ +References +========== + +.. toctree:: + :maxdepth: 1 + + C++ API diff --git a/stereo_image_proc/doc/tutorials.rst b/stereo_image_proc/doc/tutorials.rst index 3293b7a72..9d7ebfa54 100644 --- a/stereo_image_proc/doc/tutorials.rst +++ b/stereo_image_proc/doc/tutorials.rst @@ -1,47 +1,146 @@ Tutorials ========= -.. _Launch stereo_image_proc Components: +.. _first-tutorial: -Launching stereo_image_proc Components --------------------------------------- -While each of the components is available as a ROS 2 node, the -recommended way to build pipelines is using the components as -this will save overhead by not having to serialize messages -between components. +Processing the images of a stereo camera +---------------------------------------- -For a detailed example, see ``stereo_image_proc.launch.py``. +This tutorial computes the disparity image and the point cloud of a recorded stereo camera, and shows them. +It uses a bag recorded with the narrow stereo camera of a PR2 robot: a detergent bottle on a rotating pan-tilt table, in front of a wall. +A projector adds a texture to the scene, which helps the stereo matching on blank surfaces like the wall and the table. -Using Compressed Image Transport +Prerequisites +^^^^^^^^^^^^^ + +Install ``stereo_image_proc``, ``image_view`` and ``rviz2`` if needed: + +.. code-block:: console + + $ sudo apt install ros-rolling-stereo-image-proc ros-rolling-image-view ros-rolling-rviz2 + +1. Get the bag +^^^^^^^^^^^^^^ + +The bag was recorded with ROS 1. +Download it, and convert it to a ROS 2 bag with `rosbags `_, installed in a virtual environment: + +.. code-block:: console + + $ wget http://download.ros.org/data/stereo_image_proc/rotating_detergent_1_6.bag + $ python3 -m venv ~/rosbags_venv + $ ~/rosbags_venv/bin/pip install rosbags + $ ~/rosbags_venv/bin/rosbags-convert --src rotating_detergent_1_6.bag --dst rotating_detergent_1_6 + +Check its topics: + +.. code-block:: console + + $ ros2 bag info rotating_detergent_1_6 + ... + Duration: 29.721329000s + ... + Topic information: Topic: /narrow_stereo_textured/left/camera_info | Type: sensor_msgs/msg/CameraInfo | Count: 437 | Serialization Format: cdr + Topic: /narrow_stereo_textured/left/image_raw | Type: sensor_msgs/msg/Image | Count: 437 | Serialization Format: cdr + Topic: /narrow_stereo_textured/right/camera_info | Type: sensor_msgs/msg/CameraInfo | Count: 437 | Serialization Format: cdr + Topic: /narrow_stereo_textured/right/image_raw | Type: sensor_msgs/msg/Image | Count: 437 | Serialization Format: cdr + +The stereo camera is in the ``narrow_stereo_textured`` namespace, with a ``left`` and a ``right`` camera. +The images are ``mono8``. + +You can also look at the images with ``rqt_bag rotating_detergent_1_6``: + +.. image:: images/rqt_bag_stereo.png + :alt: rqt_bag showing the topics of the bag + +2. Start the stereo pipeline +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Launch ``stereo_image_proc`` in the namespace of the camera: + +.. code-block:: console + + $ ros2 launch stereo_image_proc stereo_image_proc.launch.py namespace:=narrow_stereo_textured + +.. note:: + + With Fast DDS, the default middleware, nothing is published until `#1232 `_ is released, see :ref:`known-issues`. + Until then, run ``export RMW_IMPLEMENTATION=rmw_cyclonedds_cpp`` in every terminal of this tutorial. + +3. Play the bag +^^^^^^^^^^^^^^^ + +In another terminal, play the bag in a loop: + +.. code-block:: console + + $ ros2 bag play --loop rotating_detergent_1_6 + +4. Show the disparity image +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In a third terminal, run ``stereo_view``. +It shows the left and right rectified images, and the disparity image: + +.. code-block:: console + + $ ros2 run image_view stereo_view --ros-args \ + -r stereo:=narrow_stereo_textured -r image:=image_rect_color + +.. image:: images/speckles.png + :alt: disparity image with the default parameters + :width: 60% + +The colors show the disparity, scaled to the range searched by the matcher: from dark red for the smallest disparity, the farthest points, through blue, cyan, green and yellow, to red for the largest disparity, the closest points. +Gray pixels have no disparity: the matching failed, or the point is not seen by both cameras. + +With the default parameters, the wall is found, but the table and the bottle are not: they are too close to the camera. +:doc:`choosing_good_stereo_params` continues from here, and tunes the parameters to see them. + +5. Show the point cloud +^^^^^^^^^^^^^^^^^^^^^^^ + +Check that the point cloud is published, at the rate of the camera, about 15 Hz: + +.. code-block:: console + + $ ros2 topic hz /narrow_stereo_textured/points2 + average rate: 14.670 + ... + +To see it, run ``rviz2``, set the **Fixed Frame** to ``narrow_stereo_optical_frame``, the frame of the left camera, and add a **PointCloud2** display on ``/narrow_stereo_textured/points2``. + +Using compressed images +----------------------- + +Both components subscribe to their images with ``image_transport``, so they can use compressed images, for example over WiFi. +Set the ``image_transport`` parameter to the transport to use: + +.. code-block:: console + + $ ros2 run stereo_image_proc disparity_node --ros-args -p image_transport:=compressed + +The transport must be installed, for example with ``sudo apt install ros-rolling-compressed-image-transport``. + +Remapping the camera_info topics -------------------------------- -All of the components and nodes in ``stereo_image_proc`` support -``image_transport``. This allows a subscriber to specify the transport to -be used. By default, this is ``raw``, which means an uncompressed -``sensor_msgs/Image``. When transmitting images over limited bandwidth -networks, such as WiFi, it can be helpful to use ``compressed`` format. -.. code-block:: bash +The components find each camera info next to its image: if ``left/image_rect`` is remapped to ``/my/left/image``, the left camera info is ``/my/left/camera_info``. + +.. code-block:: console - $ ros2 run stereo_image_proc disparity_node --ros-args -p image_transport:=compressed + $ ros2 run stereo_image_proc disparity_node --ros-args \ + -r left/image_rect:=/my/left/image -r right/image_rect:=/my/right/image -Remapping camera_info Topics ----------------------------- -When a ``camera_info`` topic is needed, an image_transport camera subscriber -is typically used. ROS 2 convention for naming ``camera_info`` topics is: +subscribes to ``/my/left/image``, ``/my/left/camera_info``, ``/my/right/image`` and ``/my/right/camera_info``. - * camera/image - an image in namespace ``camera``. - * camera/camera_info - the associated camera info +If the camera info is somewhere else, set ``use_image_transport_camera_info`` to false on ``DisparityNode``, and remap ``left/camera_info`` and ``right/camera_info``: -So if a node subscribes to a topic called ``image``, and the user remaps this -to ``my_camera/image``, then the associated camera info will be automatically -remapped to ``mycamera/camera_info``. +.. code-block:: console -Most ROS 2 camera drivers will follow the convention, but occasionally they do -not. In this case, you will have to manually remap the camera_info - but due -to the way that ROS 2 remapping works you have to use the fully resolved -camera info topic. An example: + $ ros2 run stereo_image_proc disparity_node --ros-args \ + -r left/image_rect:=/my/left/image -r right/image_rect:=/my/right/image \ + -p use_image_transport_camera_info:=false \ + -r left/camera_info:=/other/left/camera_info -r right/camera_info:=/other/right/camera_info - * ``image`` is remapped to ``my_camera/image``. - * The fully resolved name for the camera info is now ``my_camera/camera_info``. - * If your camera driver actually publishes ``another_ns/camera_info``, then - you would have to remap ``my_camera/camera_info`` to ``another_ns/camera_info``. +``PointCloudNode`` always takes the left camera info next to ``left/image_rect_color``, and subscribes to ``right/camera_info``, which can be remapped. diff --git a/stereo_image_proc/include/stereo_image_proc/stereo_processor.hpp b/stereo_image_proc/include/stereo_image_proc/stereo_processor.hpp index 2a5f14a62..e8bd779d7 100644 --- a/stereo_image_proc/include/stereo_image_proc/stereo_processor.hpp +++ b/stereo_image_proc/include/stereo_image_proc/stereo_processor.hpp @@ -42,15 +42,26 @@ namespace stereo_image_proc { +/// The images, disparity image and point clouds computed by StereoProcessor::process(). struct StereoImageSet { + /// Images of the left camera. image_proc::ImageSet left; + /// Images of the right camera. image_proc::ImageSet right; + /// Disparity image, in the frame of the left camera. stereo_msgs::msg::DisparityImage disparity; + /// Point cloud, as the deprecated sensor_msgs::msg::PointCloud. sensor_msgs::msg::PointCloud points; + /// Point cloud. sensor_msgs::msg::PointCloud2 points2; }; +/// Computes disparity images and point clouds from stereo images, with OpenCV. +/// +/// The disparity is computed with block matching (cv::StereoBM) or semi-global +/// block matching (cv::StereoSGBM). The parameters of both matchers are kept, and +/// setStereoType() selects the one used. Used by DisparityNode. class StereoProcessor { public: @@ -60,11 +71,14 @@ class StereoProcessor sg_block_matcher_ = cv::StereoSGBM::create(1, 1, 10); } + /// Stereo matching algorithm. enum StereoType { - BM, SGBM + BM, ///< Block matching. + SGBM ///< Semi-global block matching. }; + /// Flags selecting the outputs computed by process(). enum { LEFT_MONO = 1 << 0, @@ -84,26 +98,31 @@ class StereoProcessor ALL = LEFT_ALL | RIGHT_ALL | STEREO_ALL }; + /// Matching algorithm used. inline StereoType getStereoType() const { return current_stereo_algorithm_; } + /// Select the matching algorithm. inline void setStereoType(StereoType type) { current_stereo_algorithm_ = type; } + /// Interpolation used for the rectification, a cv::InterpolationFlags. inline int getInterpolation() const { return mono_processor_.interpolation_; } + /// Set the interpolation used for the rectification, a cv::InterpolationFlags. inline void setInterpolation(int interp) { mono_processor_.interpolation_ = interp; } + /// Bound on the normalized pixel values. inline int getPreFilterCap() const { if (current_stereo_algorithm_ == BM) { @@ -112,12 +131,14 @@ class StereoProcessor return sg_block_matcher_->getPreFilterCap(); } + /// Set the bound on the normalized pixel values, from 1 to 63. inline void setPreFilterCap(int param) { block_matcher_->setPreFilterCap(param); sg_block_matcher_->setPreFilterCap(param); } + /// Side of the matching window, in pixels. inline int getCorrelationWindowSize() const { if (current_stereo_algorithm_ == BM) { @@ -126,12 +147,14 @@ class StereoProcessor return sg_block_matcher_->getBlockSize(); } + /// Set the side of the matching window, in pixels. Must be odd. inline void setCorrelationWindowSize(int param) { block_matcher_->setBlockSize(param); sg_block_matcher_->setBlockSize(param); } + /// Smallest disparity searched, in pixels. inline int getMinDisparity() const { if (current_stereo_algorithm_ == BM) { @@ -140,12 +163,14 @@ class StereoProcessor return sg_block_matcher_->getMinDisparity(); } + /// Set the smallest disparity searched, in pixels. inline void setMinDisparity(int param) { block_matcher_->setMinDisparity(param); sg_block_matcher_->setMinDisparity(param); } + /// Number of disparities searched, in pixels. inline int getDisparityRange() const { if (current_stereo_algorithm_ == BM) { @@ -154,12 +179,14 @@ class StereoProcessor return sg_block_matcher_->getNumDisparities(); } + /// Set the number of disparities searched, in pixels. Must be a multiple of 16. inline void setDisparityRange(int param) { block_matcher_->setNumDisparities(param); sg_block_matcher_->setNumDisparities(param); } + /// Margin, in percent, by which the best match must beat the second best. inline float getUniquenessRatio() const { if (current_stereo_algorithm_ == BM) { @@ -168,12 +195,14 @@ class StereoProcessor return sg_block_matcher_->getUniquenessRatio(); } + /// Set the margin, in percent, by which the best match must beat the second best. inline void setUniquenessRatio(float param) { block_matcher_->setUniquenessRatio(param); sg_block_matcher_->setUniquenessRatio(param); } + /// Largest size, in pixels, of the regions removed as speckles. inline int getSpeckleSize() const { if (current_stereo_algorithm_ == BM) { @@ -182,12 +211,14 @@ class StereoProcessor return sg_block_matcher_->getSpeckleWindowSize(); } + /// Set the largest size, in pixels, of the regions removed as speckles. inline void setSpeckleSize(int param) { block_matcher_->setSpeckleWindowSize(param); sg_block_matcher_->setSpeckleWindowSize(param); } + /// Largest disparity difference between neighbors of the same region. inline int getSpeckleRange() const { if (current_stereo_algorithm_ == BM) { @@ -196,78 +227,94 @@ class StereoProcessor return sg_block_matcher_->getSpeckleRange(); } + /// Set the largest disparity difference between neighbors of the same region. inline void setSpeckleRange(int param) { block_matcher_->setSpeckleRange(param); sg_block_matcher_->setSpeckleRange(param); } - // BM only - + /// Size of the normalization window, in pixels. Block matching only. inline int getPreFilterSize() const { return block_matcher_->getPreFilterSize(); } + /// Set the size of the normalization window, in pixels. Must be odd. Block matching only. inline void setPreFilterSize(int param) { block_matcher_->setPreFilterSize(param); } + /// Minimum texture of the matching window. Block matching only. inline int getTextureThreshold() const { return block_matcher_->getTextureThreshold(); } + /// Set the minimum texture of the matching window. Block matching only. inline void setTextureThreshold(int param) { block_matcher_->setTextureThreshold(param); } - // SGBM specific - - // getSgbmMode can return MODE_SGBM = 0, MODE_HH = 1. FullDP == 1 was MODE_HH so we're good + /// Mode of the semi-global block matcher, a cv::StereoSGBM mode. inline int getSgbmMode() const { return sg_block_matcher_->getMode(); } + /// Set the mode of the semi-global block matcher, a cv::StereoSGBM mode. inline void setSgbmMode(int param) { sg_block_matcher_->setMode(param); } + /// Penalty for a disparity change of 1 between neighbors. SGBM only. inline int getP1() const { return sg_block_matcher_->getP1(); } + /// Set the penalty for a disparity change of 1 between neighbors. SGBM only. inline void setP1(int param) { sg_block_matcher_->setP1(param); } + /// Penalty for a disparity change of more than 1 between neighbors. SGBM only. inline int getP2() const { return sg_block_matcher_->getP2(); } + /// Set the penalty for a disparity change of more than 1 between neighbors. SGBM only. inline void setP2(int param) { sg_block_matcher_->setP2(param); } + /// Maximum difference in the left-right disparity check, in pixels. SGBM only. inline int getDisp12MaxDiff() const { return sg_block_matcher_->getDisp12MaxDiff(); } + /// Set the maximum difference in the left-right disparity check, in pixels. + /// 0 disables it. SGBM only. inline void setDisp12MaxDiff(int param) { sg_block_matcher_->setDisp12MaxDiff(param); } - // Do all the work! + /// Rectify and debayer the raw images, and compute the disparity image and the point clouds. + /// + /// @param left_raw Raw left image. + /// @param right_raw Raw right image. + /// @param model Stereo camera model, from the camera infos of both cameras. + /// @param output The computed images, disparity image and point clouds. + /// @param flags Outputs to compute, a combination of the flags above. + /// @return False if the images could not be processed. bool process( const sensor_msgs::msg::Image::ConstSharedPtr & left_raw, const sensor_msgs::msg::Image::ConstSharedPtr & right_raw, @@ -275,12 +322,25 @@ class StereoProcessor StereoImageSet & output, int flags) const; + /// Compute the disparity image from rectified images. + /// + /// @param left_rect Rectified left image, mono8. + /// @param right_rect Rectified right image, mono8. + /// @param model Stereo camera model, from the camera infos of both cameras. + /// @param disparity The disparity image, as 32-bit floats. void processDisparity( const cv::Mat & left_rect, const cv::Mat & right_rect, const image_geometry::StereoCameraModel & model, stereo_msgs::msg::DisparityImage & disparity) const; + /// Compute a sensor_msgs::msg::PointCloud from a disparity image. + /// + /// @param disparity Disparity image. + /// @param color Rectified left image, for the color of the points. + /// @param encoding Encoding of color. + /// @param model Stereo camera model. + /// @param points The point cloud. void processPoints( const stereo_msgs::msg::DisparityImage & disparity, const cv::Mat & color, @@ -288,6 +348,13 @@ class StereoProcessor const image_geometry::StereoCameraModel & model, sensor_msgs::msg::PointCloud & points) const; + /// Compute a sensor_msgs::msg::PointCloud2 from a disparity image. + /// + /// @param disparity Disparity image. + /// @param color Rectified left image, for the color of the points. + /// @param encoding Encoding of color. + /// @param model Stereo camera model. + /// @param points The point cloud. void processPoints2( const stereo_msgs::msg::DisparityImage & disparity, const cv::Mat & color, diff --git a/stereo_image_proc/package.xml b/stereo_image_proc/package.xml index ecd572f8c..98a9806ac 100644 --- a/stereo_image_proc/package.xml +++ b/stereo_image_proc/package.xml @@ -10,7 +10,7 @@ Michael Ferguson BSD - https://index.ros.org/p/stereo_image_proc/ + https://docs.ros.org/en/rolling/p/stereo_image_proc/ https://github.com/ros-perception/image_pipeline/issues https://github.com/ros-perception/image_pipeline Patrick Mihelich @@ -43,5 +43,6 @@ ament_cmake + rosdoc2.yaml diff --git a/stereo_image_proc/rosdoc2.yaml b/stereo_image_proc/rosdoc2.yaml new file mode 100644 index 000000000..8e6a0bdda --- /dev/null +++ b/stereo_image_proc/rosdoc2.yaml @@ -0,0 +1,26 @@ +## This 'attic section' self-documents this file's type and version. +type: 'rosdoc2 config' +version: 1 + +--- + +settings: + ## Generate the standard package index (package.xml metadata, README, CHANGELOG, ...). + generate_package_index: true + + ## The C++ API is documented because of the 'ament_cmake' build type. + always_run_doxygen: false + + ## There is no Python API to document. + always_run_sphinx_apidoc: false + +builders: + - doxygen: { + name: 'stereo_image_proc Public C/C++ API', + output_dir: 'generated/doxygen' + } + - sphinx: { + name: 'stereo_image_proc', + doxygen_xml_directory: 'generated/doxygen/xml', + output_dir: '' + }