基于topic通信的图像/视频传输(C++)

构建ROS pkg

1
2
cd catkin_ws/src
catkin_create_pkg vid roscpp rospy std_msgs

cpp编写

头文件引用

1
2
3
4
5
6
7
#include<ros/ros.h>
#include "sensor_msgs/Image.h"
#include "sensor_msgs/CompressedImage.h"
#include "sensor_msgs/image_encodings.h"
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>

回调函数

我们使用ROS的图像话题格式:sensor_msgs::ImageConstPtr、sensor_msgs::CompressedImageConstPtr(压缩后)作为msg格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void vidCallback(const sensor_msgs::CompressedImageConstPtr& msg)
{
cv::Mat cv_ptr;//
try
{
//转换:CompressedImageConstPtr转为ImageConstPtr
cv_bridge::CvImagePtr cv_ptr_compressed = cv_bridge::toCvCopy(msg,sensor_msgs::image_encodings::BGR8);
//转换:ImageConstPtr转为cv::Mat
cv_ptr = cv_ptr_compressed->image;
//显示帧
cv::imshow("imgCallback",cv_ptr);
cv::waitKey(1);
ROS_INFO("loading...");//输出信息
}
catch (cv_bridge::Exception& e)
{
//格式错误的处理
}
}

主函数

1
2
3
4
5
6
7
8
9
int main(int argc, char** argv){
ros::init(argc,argv,"listener");
ros::NodeHandle n;//句柄

//订阅话题、消息队列长度、回调函数
ros::Subscriber sub = n.subscribe("话题名字",1,vidCallback);
ros::spin();//循环
return 0;
}

编译

CMakeLists更改

cmake不太会,先赶出来一版能用的顶上去,暂时没有bug

1
2
3
4
5
6
7
8
9
10
11
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
sensor_msgs
cv_bridge
image_transport
OpenCV
)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIBRARY_DIRS})
1
2
3
4
5
add_executable(vidDemo src/test.cpp)
target_link_libraries(vidDemo
${catkin_LIBRARIES}
${OpenCV_LIBRARIES}
)

执行编译

1
catkin_make