本文主要讲解如何将本地的图片通过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
将image_common包中的tutorial复制到src目录下,命名为image_transport_tutorial。
- $ 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
现在我们启动叫my_publisher的发布节点,最后一个参数是本地图片的路径。
- $ rosrun image_transport_tutorial my_publisher path/to/some/image.jpg
想知道我们启动的节点是否正确,我们可以查看发布的主题(topics):
看话题中是否有 /camera/image
- 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
现在可以运行一个叫
my_subscriber的
订阅节点:
- rosrun image_transport_tutorial my_subscriber
这时候会看到弹出一个窗口,里面就是我们要发布的图片