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 查看图像