思路:
(1)使用opencv读取本地图像
(2)调用cv_bridge::CvImage().toImageMsg()将本地图像发送给rviz显示
1.使用opencv读取本地图像并发布图像消息
(1)利用catkin新建一个工程叫rosopencv,并进行初始化
mkdir -p rosopencv/src cd rosopencv/src catkin_create_pkg rosopencv sensor_msgs cv_bridge roscpp std_msgs image_transport cd .. catkin_make source ./devel/setup.bash
(2)编辑主函数代码
在rosopencv包文件夹src目录下创建rosopencv.cpp
主函数rosopencv.cpp内容如下
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> #include <stdio.h> int main(int argc, char** argv) { ros::init(argc, argv, "image_publisher"); ros::NodeHandle nh; image_transport::ImageTransport it(nh); image_transport::Publisher pub = it.advertise("camera/image", 1); cv::Mat image = cv::imread("~/rosopencv/test.jpg", CV_LOAD_IMAGE_COLOR); if(image.empty()){ printf("open error\n"); } sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg(); ros::Rate loop_rate(5); while (nh.ok()) { pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } }
(3)编辑CmakeLists.txt
cmake_minimum_required(VERSION 3.0.2) project(rosopencv) find_package(catkin REQUIRED COMPONENTS cv_bridge image_transport roscpp sensor_msgs std_msgs ) catkin_package( INCLUDE_DIRS include # LIBRARIES rosopencv CATKIN_DEPENDS cv_bridge image_transport roscpp sensor_msgs std_msgs # DEPENDS system_lib ) include_directories( include ${catkin_INCLUDE_DIRS} ) add_executable(${PROJECT_NAME}_node src/rosopencv.cpp)
target_link_libraries(${PROJECT_NAME}_node ${catkin_LIBRARIES} )
2编译和运行
编译
- cd ~/rosopencv
- catkin_make
打开一个终端运行 roscore
另外一个终端工作空间运行
source devel/setup.bash
rosrun rosopencv rosopencv_node
3.在rviz 中显示
rviz
左边点击add
选中image
在image的topic选项中选
/camera/image
即可显示图片