ros2 rolling c++ opencv

 https://www.cnblogs.com/YiYA-blog/p/10082635.html

https://mp.weixin.qq.comsKHPzb25Vr2QYH7Jez-NhCA

 

 

0、ubuntu24 +vscode + opencv4

vscode点击菜单: run/start debugging ,报错,就是找不到 opencv的头文件

*  Executing task: C/C++: g++ build active file 

Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g /home/ubuntu/cv_ws/p1/main.cpp -o /home/ubuntu/cv_ws/p1/main
/home/ubuntu/cv_ws/p1/main.cpp:1:10: fatal error: opencv2/opencv.hpp: 没有那个文件或目录
    1 | #include <opencv2/opencv.hpp>
      |          ^~~~~~~~~~~~~~~~~~~~
compilation terminated.

Build finished with error(s).

 *  The terminal process failed to launch (exit code: -1). 
 *  Terminal will be reused by tasks, press any key to close it.

按如下,设置 json文件,解决。原因不清楚

项目文件结构

 

ubuntu@ubuntu-VMware-Virtual-Platform:~$ cd /home/ubuntu/.vscode
ubuntu@ubuntu-VMware-Virtual-Platform:~/.vscode$ ls
argv.json  cli  extensions  settings.json
ubuntu@ubuntu-VMware-Virtual-Platform:~/.vscode$ cat settings.json
{
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}
ubuntu@ubuntu-VMware-Virtual-Platform:~/.vscode$ 
settings.json

 

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "Build with OpenCV",
            "command": "g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-I/usr/include/opencv4",  // 确保这个路径正确
                "-I/usr/include/opencv4/opencv2",  // 显式添加二级目录
                "$(pkg-config --cflags --libs opencv4)"  // 同时包含编译和链接标志
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build"
        },
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",// 设置动态链接库
                "-I", "/usr/include/opencv4",
                "-I", "/usr/include/opencv4/opencv2",
                "-L", "/usr/local/lib",
                "-l", "opencv_core",
                "-l", "opencv_imgproc",
                "-l", "opencv_imgcodecs",
                "-l", "opencv_features2d",
                "-l", "opencv_video",
                "-l", "opencv_ml",
                "-l", "opencv_highgui",
                "-l", "opencv_objdetect",
                "-l", "opencv_flann",
                "-l", "opencv_imgcodecs",
                "-l", "opencv_photo",
                "-l", "opencv_videoio"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ]
}
task.json

 

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include/opencv4/**",
                "/usr/include/opencv4/opencv2/**"
            ],
            "defines": [],
            "cStandard": "c17",
            "cppStandard": "gnu++17",
            "intelliSenseMode": "linux-gcc-x64"
        }
    ],
    "version": 4
}
c_cpp_properties.json

 

cmake_minimum_required(VERSION 3.0)
project(OpenCV_Project)

find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
include_directories("/usr/include/opencv4/opencv2")
add_executable(main main.cpp)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
CMakeLists.txt

 

//#include <opencv2/opencv.hpp>
#include <iostream>
#include <opencv2/opencv.hpp>  
int main() {
    // 打印OpenCV版本信息
    std::cout << "OpenCV Version: " << CV_VERSION << std::endl;
    return 0;
}
main.cpp

 

https://blog.csdn.net/weixin_28487725/article/details/148152940

1、编译通过的 一个 cpp节点

ubuntu@ubuntu-VMware-Virtual-Platform:~/ros_ws/src$ tree -L 3
.
└── cv_pkg
    ├── CMakeLists.txt
    ├── include
    │   └── cv_pkg
    ├── package.xml
    └── src
        └── cv_image.cpp

5 directories, 3 files

 

cv_image.cpp

#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <cv_bridge/cv_bridge.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
 
std::shared_ptr<rclcpp::Node> node;
 
void CamRGBCallback(const sensor_msgs::msg::Image::SharedPtr msg)
{
    cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
 
cv::Mat imgOriginal = cv_ptr->image;
    cv::imshow("RGB", imgOriginal);
    cv::waitKey(1);
}
 
int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);
    node = std::make_shared<rclcpp::Node>("cv_image_node");
 
    auto rgb_sub = node->create_subscription<sensor_msgs::msg::Image>(
        "/kinect2/qhd/image_raw", 1, CamRGBCallback);
 
    cv::namedWindow("RGB");
 
    rclcpp::spin(node);
     
    cv::destroyAllWindows();
     
    rclcpp::shutdown();
 
    return 0;
}
View Code

CMakeLists.txt

cmake_minimum_required(VERSION 3.8)
project(cv_pkg)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()

# find dependencies
find_package(ament_cmake REQUIRED)
# uncomment the following section in order to fill in
# further dependencies manually.
# find_package(<dependency> REQUIRED)

find_package(rclcpp REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(cv_bridge REQUIRED)
find_package(OpenCV REQUIRED)  # 必须加上这一行!

add_executable(cv_image src/cv_image.cpp)
#deprecated ament_target_dependencies(cv_image "rclcpp" "sensor_msgs" "cv_bridge" "OpenCV")
target_link_libraries(cv_image PUBLIC
${sensor_msgs_TARGETS}
cv_bridge::cv_bridge
rclcpp::rclcpp
sensor_msgs::sensor_msgs_library
${OpenCV_LIBS}  # 必须链接 OpenCV
)

# # 添加头文件路径
# target_include_directories(cv_image PRIVATE
#   ${rclcpp_INCLUDE_DIRS}
#   ${sensor_msgs_INCLUDE_DIRS}
#   ${cv_bridge_INCLUDE_DIRS}
#   ${OpenCV_INCLUDE_DIRS}
# )


install(TARGETS  cv_image
DESTINATION  lib/${PROJECT_NAME})

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # comment the line when a copyright and license is added to all source files
  set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # comment the line when this package is in a git repo and when
  # a copyright and license is added to all source files
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()
View Code

package.xml

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>cv_pkg</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="ubuntu@todo.todo">ubuntu</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>rclcpp</depend>
  <depend>sensor_msgs</depend>
  <depend>cv_bridge</depend>
  <depend>OpenCV</depend> 

  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>
View Code

 建立一个 包usb_cam_viewer

ros2 pkg create --build-type ament_cmake usb_cam_viewer \
  --dependencies rclcpp sensor_msgs cv_bridge OpenCV

 

错误:找不到头文件 或 库文件

ros2 rolling 编译报错:fatal error: cv_bridge/cv_bridge.hpp: 没有那个文件或目录 6 | #include <cv_bridge/cv_bridge.hpp>

判断是否安装并有相应的头文件、库文件

  # 检查头文件是否存在
ls -la /opt/ros/rolling/include/cv_bridge/cv_bridge.hpp

或则:

ls -la /opt/ros/rolling/include/cv_bridge/cv_bridge/cv_bridge.hpp
# 检查库文件
ls -la /opt/ros/rolling/lib/libcv_bridge*

修改CmakeLists.h 文件

# 头文件路径
set(INCLUDE_DIRS
${rclcpp_INCLUDE_DIRS}
${sensor_msgs_INCLUDE_DIRS}
${cv_bridge_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
/opt/ros/rolling/include # 强制添加ROS2全局路径
/opt/ros/rolling/include/cv_bridge #加入后可以找到头文件,注意:#include <cv_bridge/cv_bridge.hpp>
)
 
# 库文件路径
target_link_libraries(usb_cam_viewer
${rclcpp_LIBRARIES}
${sensor_msgs_LIBRARIES}
${cv_bridge_LIBRARIES} # 链接 cv_bridge 库
${OpenCV_LIBRARIES}
cv_bridge::cv_bridge # 加入后可以找到库文件
)

 

posted @ 2025-06-30 20:17  辛河  阅读(41)  评论(0)    收藏  举报