问题描述
如何使用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
笔记本的屏幕截图示例:\