python - 如何在没有 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 连接发送原始二进制文件?
谢谢
解决方案
确实, 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)
推荐阅读
- python - Colorama 输出随机的东西
- draw.io - draw.io 调整容器形状的展开/折叠 (+/-) 按钮
- log4j2 - 如何配置具有两个根级别的 log4j2?
- c# - 在 C# 中如何将属性名称和值列表转换为实例化的类对象
- javascript - 我怎样才能找到像“!”这样的特殊字符 或者 '?' 在 JavaScript 的对象数组中?
- c# - 自定义 WebOptimizer 缓存清除算法
- r - 主题标签会影响 R 中 lmer 模型的 p 值吗?
- java - 为什么当请求 url 相同并使用 CompletableFuture 处理时,Tomcat 使用不同的线程?
- javascript - 如何缩放一组圆圈以使它们在整个缩放过程中保持可见?
- logistic-regression - 混合 logit (mlogit) 与社会人口变量