【发布时间】:2017-12-01 16:23:49
【问题描述】:
使用 PIL 将 RGB 图像转换为 (H, W, 3) numpy 数组非常快。
im = np.array(PIL.open(path))
但是,我找不到将灰度图像转换为 (H, W, 1) 数组的快速方法。我尝试了两种方法,但它们都比上面慢得多:
im = np.array(PIL.open(path)) # return an (H, W) array
im = np.expand_dims(im, axis=0)
im = im.astype(int)
这种方法也很慢:
img = PIL.open(path)
im = np.array(img.getdata()).reshape(img.size[1], img.size[0], 1)
请指教...
【问题讨论】:
-
使用
intdtype 作为最终dtype 而不是uint8或类似的有什么特殊原因吗?如果降低精度/无符号 dtype 没问题,我们可以优化很多。 -
@Divakar 感谢您的回答和帮助。灰度文件的数据类型(值)为int(0~255)...
-
听起来像
uint8。所以,我建议在这种情况下使用dtype=np.uint8。 -
另外,
np.expand_dims(im, axis=0)在开头附加新轴,所以它的(1,H,W),而第二个代码在末尾这样做:(H,W,1)。哪个是正确的? -
(1, H, W) 正是我想要的(只需编辑标题)。
标签: python numpy python-imaging-library