Apparently ROS2 installs OpenCV, so it is definitely worth verifying if that is the case. To to so run the following in your terminal:
pkg-config --modversion opencv4
If you get a version number you already have it.
Then to integrate OpenCV with ROS2 you have to create a ROS2 package and specify OpenCV as dependency:
ros2 pkg create my_ros2_opencv_pkg --dependencies rclcpp OpenCV
If you plan to subscribe or publish images to the ROS2 network include at least cv_bridge,
sensor_msgs
and image_transport
, for instance:
ros2 pkg create my_ros2_opencv_pkg --dependencies rclcpp std_msgs sensor_msgs cv_bridge image_transport OpenCV
This will automatically populate the package.xml
file and most part of the CMakeLists.txt
for you.
In your .cpp file don't forget to add (in addition to any ROS2 includes) these #include
statements at the top:
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.hpp>
#include <opencv2/opencv.hpp>
Finally modify your CMakeLists.txt
to generate the executable like so:
add_executable(my_ros2_opencv_node src/name_of_your_cpp_file.cpp)
And add the node dependencies to the ament_target_dependencies()
function, for instance:
ament_target_dependencies(my_ros2_opencv_node rclcpp std_msgs sensor_msgs cv_bridge image_transport OpenCV)
And install it:
install(TARGETS
my_ros2_opencv_node
DESTINATION lib/${PROJECT_NAME}
)
This is how I integrate OpenCV with ROS2 using C++ when I create a new package from scratch.