本文主要讲解如何将本地的图片通过ROS来显示出来。主要利用了opencv库,一样是来源于ROS官网.
创建一个ROS工作区
工作区还是存放和编译我们的文件
$ mkdir -p ~/image_transport_ws/src $ cd ~/image_transport_ws $ catkin_make $ source devel/setup.bash
ROS官方有提供转换图片Demo,直接下载使用。
$ cd ~/image_transport_ws/ $ git clone https://github.com/ros-perception/image_common.git $ mkdir src
$ cp -r `pwd`/image_common/image_transport/tutorial/ ./src/image_transport_tutorial其中主要就是 my_publisher.cpp和my_subscriber.cpp这两个文件。my_publisher.cpp文件内容如下:
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> 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(argv[1], CV_LOAD_IMAGE_COLOR); cv:WaitKey(30); 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(); } }my_subscriber.cpp文件内容如下:
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> void imageCallback(const sensor_msgs::ImageConstPtr& msg) { try { cv::imshow("view", cv_bridge::toCvShare(msg, "bgr8")->image); } catch (cv_bridge::Exception& e) { ROS_ERROR("Could not convert from '%s' to 'bgr8'.", msg->encoding.c_str()); } } int main(int argc, char **argv) { ros::init(argc, argv, "image_listener"); ros::NodeHandle nh; cv::namedWindow("view"); cv::startWindowThread(); image_transport::ImageTransport it(nh); image_transport::Subscriber sub = it.subscribe("camera/image", 1, imageCallback); ros::spin(); cv::destroyWindow("view"); }
$ cd ~/image_transport_ws $ catkin_make
首先启动ROS
$ roscore
$ rosrun image_transport_tutorial my_publisher path/to/some/image.jpg
$ rostopic list -v
Published topics: * /rosout [roslib/Log] 1 publisher * /camera/image [sensor_msgs/Image] 1 publisher * /rosout_agg [roslib/Log] 1 publisher Subscribed topics: * /rosout [roslib/Log] 1 subscriber
rosrun image_transport_tutorial my_subscriber这时候会看到弹出一个窗口,里面就是我们要发布的图片