首页 > 解决方案 > 如何在没有 OpenCV 的情况下通过 ROS 发布 PIL 图像二进制文件?

问题描述

我目前正在尝试编写一个 ROS Publisher/Subscriber 设置来传递 PIL 打开的图像二进制文件。由于操作限制,我不想使用 OpenCV,我想知道是否有办法这样做。这是我当前的代码:

#!/usr/bin/env python
import rospy
from PIL import Image
from sensor_msgs.msg import Image as sensorImage
from rospy.numpy_msg import numpy_msg
import numpy

def talker():
    pub = rospy.Publisher('image_stream', numpy_msg(sensorImage), queue_size=10)
    rospy.init_node('image_publisher', anonymous=False)
    rate = rospy.Rate(0.5)
    while not rospy.is_shutdown():
        im = numpy.array(Image.open('test.jpg'))
        pub.publish(im)
        rate.sleep()

if __name__ == '__main__'
    try:
        talker()
    except ROSInterruptException:
        pass

在 pub.publish(im) 尝试抛出:

TypeError: Invalid number of arguments, args should be ['header', 'height', 'width', 'encoding', 'is_bigendian', 'step', 'data'] args are (array([[[***array data here***]]], dtype=uint8),)

如何将图像转换为正确的形式,或者是否有一种转换方法/不同的消息类型支持仅通过 ROS 连接发送原始二进制文件?

谢谢

标签: pythonnumpypython-imaging-libraryrosrospy

解决方案


确实, Mark Setchell 的答案非常有效(在此示例中忽略了 alpha 通道):

#!/usr/bin/env python
import rospy
import urllib2  # for downloading an example image
from PIL import Image
from sensor_msgs.msg import Image as SensorImage
import numpy as np

if __name__ == '__main__':
    pub = rospy.Publisher('/image', SensorImage, queue_size=10)

    rospy.init_node('image_publisher')

    im = Image.open(urllib2.urlopen('https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png'))
    im = im.convert('RGB')

    msg = SensorImage()
    msg.header.stamp = rospy.Time.now()
    msg.height = im.height
    msg.width = im.width
    msg.encoding = "rgb8"
    msg.is_bigendian = False
    msg.step = 3 * im.width
    msg.data = np.array(im).tobytes()
    pub.publish(msg)

推荐阅读