python -- ros自定义msgs传输图片

方法:
  1. 自定义msgs:MyImage.msg
float64 time
int16[] size
uint8[] data
  1. 将cv2图片矩阵转为list赋值给msgs
#!/usr/bin/env python3
#coding=utf-8

import rospy
import cv2
from my_msgs.msg import MyImage
import numpy as np

def publish():
    image = MyImage()
    image.size = []
    size = 0
    while True:
        cap = cv2.VideoCapture('/home/fly/catkin_ws/src/ssd_pkg/new.avi') # 视频
        while cap.isOpened() and not rospy.is_shutdown():
            ret, frame = cap.read()
            if ret:
                frame = cv2.resize(frame, (1280, 720), interpolation=cv2.INTER_LINEAR)
                if not size:
                    image.size = list(frame.shape)
                    size = image.size[0]*image.size[1]*image.size[2]
                image.data = frame.reshape(size).tolist()	# 转一维list
                image.time = rospy.get_time()
                image_pub.publish(image)
                print("publish one:",image.time)

if __name__ == '__main__':
    try:
        print("publish start...")
        rospy.init_node('image_publish', anonymous=True)
        image_pub = rospy.Publisher('cam_image', MyImage, queue_size=5)
        publish()
        rospy.spin()
    except rospy.ROSInterruptException:
        print('ROSInterruptException')
        pass

  1. 然后节点收到msgs后再转为矩阵显示
import rospy
import cv2
from my_msgs.msg import MyImage
import numpy as np

def callback(datas):
    sec = datas.time
    image = np.array(list(datas.data), dtype=np.uint8).reshape(datas.size) # 注意转换成list才能转arrar,否者msg默认将uint8识别是bytes
    cv2.imshow('image', image)
    cv2.waitKey(1)

if __name__ == '__main__':
    try:
        print("show start...")
        rospy.init_node('image_show', anonymous=True)
        rospy.Subscriber('image', MyImage, callback, queue_size=5)
        rospy.spin()
    except rospy.ROSInterruptException:
        print('ROSInterruptException')
        pass

比较粗糙,只是适合少量图片传输,不追求效率的方案使用(高清图片数据量大,转换耗时)

适合测试使用,大数据图片传输使用cv_bridge转换对应的图片格式效率较高

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值