ROS下使用python发布Image消息
博主去官网看了很久,都没有python端发布Image的例子。特地来补充一下。
首先Image类型是源自于sensor_msgs.msg里面的。其类型包括以下几个成员。
(摘自于ros官网)
首先我们要先初始化header,因为Image不需要fix_frame等东西的定义,所以发布的时候只需要给一个时间戳就可以了。
接下来就是我们的图片的大小和编码了。编码有很多种,这里博主使用的rbg格式的,所以编码也是rbg8格式。
接下来就是is_bigendian翻译过来就是是否为大端模式,大端模式为一种数据排列方式。例如你传输一个整数,1024。因为在系统中都是以byte传输了。大端模式发送就是0x04,0x00。小端模式就是0x00,0x04。但是对于我这个8bit的数值来说,不存在大端小端的。所以可以忽略。
step是值每一行的数据有多少byte,我的一行为1241个点,每个点有三个byte,所以,我的step应该为1241×3。
data就是我们的传输的数据了。不能直接的把cv2读出来的数值赋过去,因为此data接受的是一个string,而不是array。所以我们要先转一下。
接下来就是所有的程序了。(你可以从博主github上面下载本样例程序。git@github.com:lucky-ing/ROS_Publish_Image.git)
import rospy
from std_msgs.msg import Header
from sensor_msgs.msg import Image
import os
import cv2
import numpy as np
import time
IMAGE_WIDTH=1241
IMAGE_HEIGHT=376
rospy.init_node("listener", anonymous=True)
image_pubulish=rospy.Publisher('/camera/image_raw',Image,queue_size=1)
def publish_image(imgdata):
image_temp=Image()
header = Header(stamp=rospy.Time.now())
header.frame_id = 'map'
image_temp.height=IMAGE_HEIGHT
image_temp.width=IMAGE_WIDTH
image_temp.encoding='rgb8'
image_temp.data=np.array(imgdata).tostring()
#print(imgdata)
#image_temp.is_bigendian=True
image_temp.header=header
image_temp.step=1241*3
image_pubulish.publish(image_temp)
file_list=os.listdir('/home/lucky/open/data/kitti/00/image_0')
file_list.sort()
for i in file_list:
img=cv2.imread('/home/lucky/open/data/kitti/00/image_0/'+i)
publish_image(img)
#time.sleep(1)
cv2.imshow('123',img)
key=cv2.waitKey(1000)
if key==ord('q'):
break
print("pubulish")
any question you can contact lucky, by email @lucky_lsq@163.com