Python3 ROS Image与CV image相互转换,不用cv_bridge

1. Publisher

import numpy as np
import cv2
import rospy
from sensor_msgs.msg import Image
from std_msgs.msg import Header


def ros_img_pub(video_path, ros_img, header):
    rospy.init_node('img_pub', anonymous=True)
    pub_ = rospy.Publisher("/front_camera/image_raw", Image, queue_size=2)
    rate = rospy.Rate(30)

    print("/front_camera/image_raw ros image topic publish...")
    while not rospy.is_shutdown():
        cap = cv2.VideoCapture(video_path)
        ret, image = cap.read()
        while ret and not rospy.is_shutdown():
            ret, image = cap.read()
            if image is None:
                break
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)                
            header = Header(stamp=rospy.Time.now())
            header.frame_id = 'result'            
            ros_img.encoding = 'rgb8'            
            ros_img.header = header
            ros_img.height = image.shape[0]
            ros_img.width = image.shape[1]                
            ros_img.step = image.shape[1] * image.shape[2]
            ros_img.data = np.array(image).tostring()
            
            pub_.publish(ros_img)
            rate.sleep()


def main():    
    video_path = './front_12.avi'
    ros_img = Image()
    header = Header
    ros_img_pub(video_path, ros_img, header)


if __name__ == '__main__':
    main()

2. Subscriber

import numpy as np
import cv2
import rospy
from sensor_msgs.msg import Image


def img_callback(ros_img_msg, args):

    # print(args)
    assert isinstance(ros_img_msg, Image)
    cv_img = np.frombuffer(ros_img_msg.data, dtype=np.uint8).reshape(ros_img_msg.height, ros_img_msg.width, -1)
    cv_img = cv2.cvtColor(cv_img, cv2.COLOR_RGB2BGR)
    cv2.imshow("cv_img", cv_img)
    cv2.waitKey(1)


def main():
    rospy.init_node('img_sub', anonymous=True)

    # ('args'): img_callback args
    sub_ = rospy.Subscriber('/front_camera/image_raw', Image, img_callback, ('args'))
    rospy.spin()


if __name__ == '__main__':
    main()
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值