核心原理
订阅相机发布的ros话题进入回调函数,在回调函数中进行转换,即ros话题转换为cv_bridge,再转换为opencv图像
ros中图像格式
sensor_msgs::ImageConstPtr
cv_bridge图像格式
cv_bridge::CvImagePtr
opencv图像格式
cv::Mat
c++版本代码
test2.cpp
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
cv_bridge::CvImagePtr cv_ptr;
cv::Mat a;
void callback(const sensor_msgs::ImageConstPtr& msg)
{
cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
a = cv_ptr->image;
cv::imshow("window", a);
cv::waitKey(3);
}
int main(int argc, char** argv){
ros::init(argc, argv, "main");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/usb_cam/image_raw", 1, callback);
ros::spin();
return 0;
}
CmakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(ros2cv)
set(CMAKE_BUILD_TYPE "Debug")
find_package(catkin REQUIRED COMPONENTS
roscpp
sensor_msgs
cv_bridge
)
find_package( OpenCV REQUIRED )
generate_messages(
DEPENDENCIES
)
include_directories(
# include
${catkin_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS}
)
add_executable(test2 src/test2.cpp)
target_link_libraries(test2 ${catkin_LIBRARIES} ${OpenCV_LIBS} )
功能包上传到csdn,链接为https://download.csdn.net/download/zhaohaowu/19405550
python版本代码
test.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import cv2
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
class image_converter:
def __init__(self):
# 创建cv_bridge,声明图像的发布者和订阅者
self.image_pub = rospy.Publisher("cv_bridge_image", Image, queue_size=1)
self.bridge = CvBridge()
self.image_sub = rospy.Subscriber("/usb_cam/image_raw", Image, self.callback)
def callback(self,data):
# 使用cv_bridge将ROS的图像数据转换成OpenCV的图像格式
try:
cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
except CvBridgeError as e:
print e
# 在opencv的显示窗口中绘制一个圆,作为标记
(rows,cols,channels) = cv_image.shape
if cols > 60 and rows > 60 :
cv2.circle(cv_image, (60, 60), 30, (0,0,255), -1)
# 显示Opencv格式的图像
cv2.imshow("Image window", cv_image)
cv2.waitKey(3)
# 再将opencv格式额数据转换成ros image格式的数据发布
try:
self.image_pub.publish(self.bridge.cv2_to_imgmsg(cv_image, "bgr8"))
except CvBridgeError as e:
print e
if __name__ == '__main__':
try:
# 初始化ros节点
rospy.init_node("cv_bridge_test")
rospy.loginfo("Starting cv_bridge_test node")
image_converter()
rospy.spin()
except KeyboardInterrupt:
print "Shutting down cv_bridge_test node."
cv2.destroyAllWindows()
直接python test.py运行