出处:http://www.cnblogs.com/steven-blog/
操作步骤
1:利用catkin新建一个workspace叫ros_opencv,并进行初始化
1 $ mkdir -p ros_opencv/src 2 $ cd ros_opencv/src 3 $ catkin_init_workspace
2:进入src目录,新建一个package叫opencv_test
1 $ catkin_create_pkg opencv_test sensor_msgs opencv2 cv_bridge roscpp std_msgs image_transport
3:修改opencv_test目录下CMakeLists.txt文件,代码如下
1 cmake_minimum_required(VERSION 2.8.3) 2 project(opencv_test) 3 4 ## Find catkin macros and libraries 5 6 find_package(catkin REQUIRED COMPONENTS cv_bridge image_transport roscpp sensor_msgs std_msgs) 7 find_package(OpenCV REQUIRED) 8 9 ## Declare a catkin package 10 catkin_package() 11 12 ## Include directories, 13 ## Add target and link libraries 14 15 include_directories(include ${OpenCV_INCLUDE_DIRS}) 16 include_directories(include ${catkin_INCLUDE_DIRS}) 17 18 add_executable(opencv_test_node src/opencv_test_node.cpp) 19 target_link_libraries(opencv_test_node ${catkin_LIBRARIES} ${OpenCV_LIBRARIES}) 20 add_dependencies(opencv_test_node opencv_test_gencpp)
4:在src下添加源代码
1 #include <ros/ros.h> 2 #include <stdio.h> 3 #include <image_transport/image_transport.h> 4 #include <cv_bridge/cv_bridge.h> 5 #include <sensor_msgs/image_encodings.h> 6 #include <opencv2/imgproc/imgproc.hpp> 7 #include <opencv2/highgui/highgui.hpp> 8 9 static const char WINDOW[] = "Image window"; 10 static void help() 11 { 12 printf("\nThis program demonstrates converting OpenCV Image to ROS Image messages \n" 13 ); 14 15 } 16 17 int main(int argc, char** argv) 18 { 19 help(); 20 ros::init(argc, argv, "image_converter"); 21 22 //Reading an image from the file 23 cv::Mat cv_image = cv::imread(image directory); 24 if(cv_image.empty() ) 25 { 26 ROS_ERROR("Read the picture failed!"); 27 return -1; 28 } 29 30 //Convert OpenCV image to ROS message 31 ros::NodeHandle node; 32 image_transport::ImageTransport transport(node); 33 image_transport::Publisher image_pub; 34 image_pub=transport.advertise("OutImage", 1); 35 ros::Time time=ros::Time::now(); 36 37 cv_bridge::CvImage cvi; 38 cvi.header.stamp = time; 39 cvi.header.frame_id = "image"; 40 cvi.encoding = "bgr8"; 41 cvi.image = cv_image; 42 43 sensor_msgs::Image im; 44 cvi.toImageMsg(im); 45 image_pub.publish(im); 46 ROS_INFO("Converted Successfully!"); 47 48 //Show the image 49 cv::namedWindow(WINDOW); 50 cv::imshow(WINDOW,cv_image); 51 cv::waitKey(0); 52 53 ros::spin(); 54 return 0; 55 }
5:在ros_opencv目录下进行 catkin_make
1 $ catkin_make
6:运行
1 $ roscore 2 #open a new terminal 3 $ source devel/setup.bash
4 $ rosrun opencv_test opencv_test_node
注意的地方
- 因为最新推出的ros版本中默认使用的是catkin(一种类似与cmake的工程构建工具,不过仍然兼容原来的构建方式rosbuild),因此在参考相关的学习资料时要特别注意两者的区别,比如说像指令和CMakeLists.txt中的代码等;
- 运行时,在输入rosrun之前,要先 source devel/setup.bash,不然会出现无法找到package之类的错误;
参考资料