在ROS节点中添加OpenCV,需要在CMakeLists.txt里面加入一下内容:
#添加OPENCV库
#指定OpenCV版本,代码如下
#find_package(OpenCV 3.3 REQUIRED)
#如果不需要指定OpenCV版本,代码如下
find_package(OpenCV REQUIRED)
#添加OpenCV头文件
include_directories(${OpenCV_INCLUDE_DIRS})
#显示OpenCV_INCLUDE_DIRS的值
message(${OpenCV_INCLUDE_DIRS})
# 添加一个可执行程序
# 语法:add_executable( 程序名 源代码文件 )
add_executable( main main.cpp )
# 将库文件链接到可执行程序上
target_link_libraries( main ${OpenCV_LIBS})
如果出现报错:
CMakeFiles/collision_detect.dir/src/collision_methods/CV_picture/CV_picture.cpp.o: In function `cv::String::~String()':
/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv2/core/cvstd.hpp:648: undefined reference to `cv::String::deallocate()'
/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv2/core/cvstd.hpp:648: undefined reference to `cv::String::deallocate()'
CMakeFiles/collision_detect.dir/src/collision_methods/CV_picture/CV_picture.cpp.o: In function `cv::String::operator=(cv::String const&)':
/opt/ros/kinetic/include/opencv-3.3.1-dev/opencv2/core/cvstd.hpp:656: undefined reference to `cv::String::deallocate()'
collect2: error: ld returned 1 exit status
需要指定OpenCV的路径,不同的系统添加的链接库文件可能不同,具体的库文件可以通过在ubuntu终端下输入命令pkg-config --cflags --libs opencv获取本地的安装路径:
pkg-config --cflags --libs opencv
将路径的内容放在CMakeLists.txt里面,如下:
target_link_libraries(node_name -I/usr/local/include/opencv -I/usr/local/include /usr/local/lib/libopencv_calib3d.so /usr/local/lib/libopencv_contrib.so /usr/local/lib/libopencv_core.so /usr/local/lib/libopencv_features2d.so /usr/local/lib/libopencv_flann.so /usr/local/lib/libopencv_gpu.so /usr/local/lib/libopencv_highgui.so /usr/local/lib/libopencv_imgproc.so /usr/local/lib/libopencv_legacy.so /usr/local/lib/libopencv_ml.so /usr/local/lib/libopencv_nonfree.so /usr/local/lib/libopencv_objdetect.so /usr/local/lib/libopencv_photo.so /usr/local/lib/libopencv_stitching.so /usr/local/lib/libopencv_ts.so /usr/local/lib/libopencv_video.so /usr/local/lib/libopencv_videostab.so)
如果为mac电脑需要先安装brew,在输入:
brew install pkg-config --cflags --libs opencv