ROS使用OpenCV读取图像并发布图像消息在rviz中显示

思路: 
(1)使用opencv读取本地图像 
(2)调用cv_bridge::CvImage().toImageMsg()将本地图像发送给rviz显示

1.使用opencv读取本地图像并发布图像消息

(1)利用catkin新建一个工程叫rosopencv,并进行初始化

 mkdir -p rosopencv/src
 cd rosopencv/src
 catkin_create_pkg rosopencv sensor_msgs cv_bridge roscpp std_msgs image_transport
 cd ..
 catkin_make
 source ./devel/setup.bash

(2)编辑主函数代码 
主函数rosopencv.cpp内容如下

#include 
#include 
#include 
#include 

#include 

int main(int argc, char** argv)
{
  ros::init(argc, argv, "image_publisher");
  ros::NodeHandle nh;
  image_transport::ImageTransport it(nh);
  image_transport::Publisher pub = it.advertise("camera/image", 1);

  cv::Mat image = cv::imread("/home/topeet/test.jpg", CV_LOAD_IMAGE_COLOR);
  if(image.empty()){
   printf("open error\n");
   }
  sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg();

  ros::Rate loop_rate(5);
  while (nh.ok()) {
    pub.publish(msg);
    ros::spinOnce();
    loop_rate.sleep();
  }
}

我的opencv2.4.11安装路径在/usr/local目录下 
(3)编辑CmakeLists.txt 
在工程目录下的/src/rosopencv/src/CmakeLists.txt中加入如下内容

add_executable(rosopencv src/rosopencv.cpp)
INCLUDE_DIRECTORIES(/usr/local/include)
link_directories(/usr/local/lib)
TARGET_LINK_LIBRARIES(rosopencv libopencv_calib3d.so libopencv_core.so
libopencv_features2d.so libopencv_flann.so libopencv_highgui.so libopencv_imgproc.so libopencv_ml.so libopencv_objdetect.so libopencv_photo.so libopencv_video.so libopencv_videostab.so)
target_link_libraries(rosopencv ${catkin_LIBRARIES})

告诉Cmake 库函数头文件,库函数路径,库函数名字,由于我安装了很多个版本的opencv,因此直接用暴力方法指导库函数名称。其实有一种方法可以很简单的设定调用哪种版本的opencv库,参考 
http://blog.csdn.net/u012816621/article/details/51732932 
方法是在CMakeLists.txt中用set语句设置OpenCV_DIR的值。这个路径是指定opencv版本的安装路径下的share/OpenCV(安装opencv 时会自动生成4个文件夹bin include lib share,share文件夹的作用原来是这样的!) 
因此,简单版的CmakeLists.txt如下。
 

set(OpenCV_DIR /usr/local/share/OpenCV)
message(STATUS "    version: ${OpenCV_VERSION}")
find_package(OpenCV REQUIRED)
add_executable(rosopencv src/rosopencv.cpp)
include_directories(${OpenCV_INCLUDE_DIRS})
target_link_libraries(cmaketest ${OpenCV_LIBS})

2编译和运行

编译

cd ~/dev/workspace/rosopencv
catkin_make

运行

rosrun rosopencv rosopencv 

输入

rosrun rosopencv rosopencv 

全是数字。

3.在rviz 中显示

rosrun rviz rviz

左边点击add 
选中image 
在image的topic选项中选 
/camera/image

这里写图片描述

你可能感兴趣的:(Opencv,ROS)