看起来使用1
模式进行numpy转换存在一些错误。
如果您先将其转换为L
,它就可以正常工作:
>>> im
<BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x17F17E8>
>>> im2 = im.convert('L')
>>> numpy.asarray(im2)
array([[ 0, 255],
[255, 0]], dtype=uint8)
此外,如果你尝试将一个布尔值 numpy 数组转换为 PIL 格式,你会得到奇怪的结果:
>>> testarr = numpy.array([[True,False],[True,False]], dtype=numpy.bool)
>>> testpil = Image.fromarray(testarr, mode='1')
>>> numpy.asarray(testpil)
array([[False, False],
[False, False]], dtype=bool)
然而,使用
uint8
没有问题:
>>> testarr = numpy.array([[255,0],[0,255]], dtype=numpy.uint8)
>>> Image.fromarray(testarr)
<Image.Image image mode=L size=2x2 at 0x1B51320>
>>> numpy.asarray(Image.fromarray(testarr))
array([[255, 0],
[ 0, 255]], dtype=uint8)
因此,我建议将L
用作中间数据类型,并在保存之前转换为1
,如果您需要以该格式保存它。可以像这样实现:
>>> im
<BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x17F17E8>
>>> im2 = im.convert('L')
>>> arr = numpy.asarray(im2)
>>> arr
array([[ 0, 255],
[255, 0]], dtype=uint8)
>>> arr = arr == 255
>>> arr
array([[False, True],
[ True, False]], dtype=bool)
然后进行转换回来:
>>> backarr = numpy.zeros(arr.shape, dtype=numpy.uint8)
>>> backarr[arr] = 255
>>> backarr
array([[ 0, 255],
[255, 0]], dtype=uint8)
>>> Image.fromarray(backarr).convert('1')
<Image.Image image mode=1 size=2x2 at 0x1B41CB0>