如何将pydrake / Drake的标签图像直接保存到磁盘? 选项1.a:PIL 选项1.b:OpenCV

问题描述

如何使用PIL标签图像从Drake写入磁盘?

如果我尝试Image.fromarray(label),则会收到如下错误

  File ".../PIL/Image.py",line 2751,in fromarray
    raise TypeError("Cannot handle this data type: %s,%s" % typekey) from e
TypeError: Cannot handle this data type: (1,1,1),<i2

解决方法

某些图像库,例如PIL,OpenCV等,可能需要您重塑输入并投射到特定的dtype

假设您从以下笔记本中获得标签图像:
drake/tutorials/rendering_multibody_plant.ipynb

label = sensor.label_image_output_port().Eval(sensor_context).data

选项1.a:PIL

对于PIL(至少在Ubuntu 18.04上可用),可以使用np.int32
示例:

from PIL import Image

img = label.squeeze(-1).astype(np.int32)
file = "/tmp/test.png"
Image.fromarray(img).save(file)
img_2 = np.asarray(Image.open(file))
label_2 = np.expand_dims(img_2.astype(np.int16),axis=-1)

# This should print 0,showing that you get the same image out.
print(np.max(label - label_2))

请参阅:https://github.com/python-pillow/Pillow/issues/2970

选项1.b:OpenCV

对于OpenCV(3.4.0),除了np.uint16之外,您还可以使用IMREAD_UNCHANGED

import cv2

img = label.squeeze(-1).astype(np.uint16)
file = "/tmp/test.png"
cv2.imwrite(file,img)
img_2 = cv2.imread(file,cv2.IMREAD_UNCHANGED)
label_2 = np.expand_dims(img_2.astype(np.int16),showing that you get the same image out.
print(np.max(label - label_2))

请参阅:http://jamesgregson.ca/16-bit-image-io-with-python.html

笔记本的屏幕截图示例:\

enter image description here

选项2:使用*.npy*.pkl

如果您只是为Python本身加载/保存,则可以只使用np.savepickle

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...