One of the easiest ways is to install the cv_bridge package. That brings in OpenCV and all requirements, plus functionality to use it more easily in the context of ROS 2.
To do that, add the following to the package.xml of your package:
<depend>cv_bridge</depend>
and the following near the top of your CMakeLists.txt file:
find_package(cv_bridge REQUIRED)
and don't forget to add it to ament_target_dependencies
as well.
Then if you run rosdep to install all dependencies, cv_bridge, and with that OpenCV, will be installed and available in your workspace:
rosdep install --from-paths src -r -y
Or on Ubuntu you could also install it by hand with:
sudo apt install ros-${ROS_DISTRO}-cv-bridge
You would then normally use cv_bridge to convert between ROS image messages and OpenCV images, and to perform some operations such as colour conversions.
For an example of a package that depends on cv_bridge, see:
https://gitlab.com/boldhearts/ros2_v4l2_camera
and specifically an example of it operating on images here:
https://gitlab.com/boldhearts/ros2_v4l2_camera/-/blob/e35e57095da9a7e4e3a6f1b44c89e542e1991443/src/v4l2_camera.cpp#L371-379
Also see the cv_bridge tutorials:
http://wiki.ros.org/cv_bridge/Tutorials/UsingCvBridgeToConvertBetweenROSImagesAndOpenCVImages
They are for ROS 1 but still mostly relevant for ROS 2 as well.
Originally posted by sgvandijk with karma: 649 on 2022-10-08
This answer was ACCEPTED on the original site
Post score: 3
Original comments
Comment by Werewolf_86 on 2022-10-16:
Thank you very much for such a detailed answer, Sander ! Was very helpful. Regards