ROS使用自带opencv显示图片

桌面进入终端

新建工作空间

mkdir -p ros_opencv/src

初始化工作空间

cd ros_opencv/src
catkin_init_workspace

创建功能包

catkin_create_pkg opencv_test sensor_msgs cv_bridge roscpp std_msgs image_transport

 编译功能包

cd ..
catkin_make
source devel/setup.bash

 在opencv_test/src下创建opencv_test_node.cpp

cd src/opencv_test/src
gedit opencv_test_node.cpp
#include 
#include 
#include 
#include 
#include 
#include 
#include 
 
static const char WINDOW[] = "Image window";
int main(int argc, char** argv)
{
  ros::init(argc, argv, "image_converter");
  cv::Mat cv_image = cv::imread("/home/abb/桌面/u=2621658848,3952322712&fm=193&f=GIF.jpeg");

  if(cv_image.empty() )
    {
        ROS_ERROR("Read the picture failed!");
        return -1;
    }
 
  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!");
  cv::namedWindow(WINDOW);
  cv::imshow(WINDOW,cv_image);
  cv::waitKey(0);
  ros::spin();
  return 0;
}

 修改CMakeLists.txt

cd ..
cmake_minimum_required(VERSION 3.0.2)
project(opencv_test)

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


catkin_package(
  INCLUDE_DIRS include
  LIBRARIES opencv_test
  CATKIN_DEPENDS cv_bridge image_transport roscpp sensor_msgs std_msgs
  DEPENDS system_lib
)


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

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

编译工作空间

cd ~
cd ros_opencv
catkin_make

 运行节点管理器和节点

roscore
source devel/setup.bash
rosrun opencv_test opencv_test_node

你可能感兴趣的:(ubuntu)