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();
  }
}



(3)编辑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(rosopencv ${OpenCV_LIBS})
target_link_libraries(rosopencv ${catkin_LIBRARIES})


2编译和运行
编译

cd ~/dev/workspace/rosopencv
catkin_make


运行

rosrun rosopencv rosopencv 


输入

rostopic echo /camera/image


全是数字。

3.在rviz 中显示

rosrun rviz rviz


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

ROS使用OpenCV读取图像并发布图像消息在rviz中显示_第1张图片
--------------------- 
作者:沧海飞帆 
来源:CSDN 
原文:https://blog.csdn.net/ktigerhero3/article/details/70157582 
版权声明:本文为博主原创文章,转载请附上博文链接!

你可能感兴趣的:(ROS)