在ROS中使用opencv-查看图片

参考http://www.cnblogs.com/steven-blog/archive/2013/05/12/3074518.html

吐槽一下,好多步骤,- -,打开一张图片都这么繁琐,好气啊,不过学生时代玩一玩无所谓,开心就好,熟悉一下ROS这个工具

运行效果:

在ROS中使用opencv-查看图片_第1张图片

1、创建工作空间

 $ mkdir -p ros_opencv/src
 $ cd ros_opencv/src
 $ catkin_init_workspace

2、进入src目录,创建opencv_test包

 $ catkin_create_pkg opencv_test sensor_msgs opencv2 cv_bridge roscpp std_msgs image_transport

3、修改opencv_test目录下的CMakeLists.txt

cmake_minimum_required(VERSION 2.8.3)
project(opencv_test)

## Find catkin macros and libraries

find_package(catkin  REQUIRED COMPONENTS cv_bridge image_transport  roscpp sensor_msgs std_msgs)
find_package(OpenCV REQUIRED)

## Declare a catkin package
catkin_package()

## Include directories,
## Add target and link libraries

include_directories(include ${OpenCV_INCLUDE_DIRS})
include_directories(include ${catkin_INCLUDE_DIRS})

add_executable(opencv_test_node src/opencv_test_node.cpp)
target_link_libraries(opencv_test_node ${catkin_LIBRARIES} ${OpenCV_LIBRARIES})
add_dependencies(opencv_test_node opencv_test_gencpp)

4、在opencv_test\src目录下创建opencv_test_node.cpp

#include 
#include 
#include 
#include 
#include 
#include 
#include 

static const char WINDOW[] = "Image window";
static void help()
{
    printf("\nThis program demonstrates converting OpenCV Image to ROS Image messages  \n"
        );

}

int main(int argc, char** argv)
{
  help();
  ros::init(argc, argv, "image_converter");

  //Reading an image from the file
  cv::Mat cv_image = cv::imread("/home/cheng/1.jpg");
  if(cv_image.empty() )
    {
        ROS_ERROR("Read the picture failed!");
        return -1;
    }

  //Convert OpenCV image to ROS message
  ros::NodeHandle node;
  image_transport::ImageTransport transport(node);
  image_transport::Publisher image_pub; 
  image_pub=transport.advertise("OutImage", 1);
  ros::Time time=ros::Time::now(); 

  cv_bridge::CvImage cvi;
  cvi.header.stamp = time;
  cvi.header.frame_id = "image";
  cvi.encoding = "bgr8";
  cvi.image = cv_image;

  sensor_msgs::Image im;
  cvi.toImageMsg(im);
  image_pub.publish(im);
  ROS_INFO("Converted Successfully!");

  //Show the image
  cv::namedWindow(WINDOW);
  cv::imshow(WINDOW,cv_image);
  cv::waitKey(0);

  ros::spin();
  return 0;
}

5、编译

$ cd ros_opencv
$ catkin_make

6、运行

$ roscore
$ source devel/setup.bash
$ rosrun opencv_test opencv_test_node

 

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