ros发布图像

ros版本: melodic
系统:ubuntu18
目的:
通过使用opencv的VideoCapture 获取 usb相机的图像,通过ros 发布出去

代码:

#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>

int main(int argc, char** argv) {
  cv::VideoCapture cap;
  cap.open(0);
  cv::Mat img;
  ros::init(argc, argv, "image_pub");
  // Convert OpenCV image to ROS message
  ros::NodeHandle node;
  image_transport::ImageTransport transport(node);
  image_transport::Publisher image_pub;
  image_pub = transport.advertise("ImageTopic", 1);
  ros::Time time = ros::Time::now();

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

  ros::Rate rate(1.0);

  while (1) {
    cap.read(img);
    cvi.image = img;
    sensor_msgs::Image im;
    cvi.toImageMsg(im);
    ROS_INFO_STREAM("publish");
    image_pub.publish(im);
  }
}


使用ros自带的结构体:

#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>

#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include "mymsg.h"

int main(int argc, char** argv) {
  cv::VideoCapture cap;
  cap.open(0);
  cv::Mat img;
  ros::init(argc, argv, "image_pub");
  ros::NodeHandle nh;
  ros::Publisher image_pub = nh.advertise<sensor_msgs::Image>("image_topic", 1);

  cv_bridge::CvImage cvi;
  // cvi.header.stamp = time;
  cvi.header.frame_id = "test_image";
  cvi.encoding = "bgr8";

  ros::Rate rate(1.0);

  while (1) {
		// pub.publish(m);
		// sleep(1);
    cap.read(img);
    cvi.image = img;
    sensor_msgs::Image im;
    cvi.toImageMsg(im);
    ROS_INFO_STREAM("publish");
    image_pub.publish(im);
  }
}

cmakelists

cmake_minimum_required(VERSION 3.0)
project(main)

find_package(catkin REQUIRED COMPONENTS
            cv_bridge
            image_transport
            roscpp
            sensor_msgs
            std_msgs)

find_package(OpenCV 3 REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS}
                    ${catkin_INCLUDE_DIRS})
link_libraries(${OpenCV_LIBS})
link_libraries(${catkin_LIBRARIES})


add_executable(main main.cpp)

使用:
1、把代码编译为可执行程序 ,先运行 roscore 再运行 mian
2、查看图像
2.1 使用 rosrun image_view image_view image:=/ImageTopic 这个指令查看图像 (/ImageTopic 这个是自己定义的topic的名字)
2.2 使用日rviz 查看图像

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值