python - 如何在PIL和numpy之间转换模式为 "1"的图像?

标签 python numpy python-imaging-library

我刚开始使用 Python 进行图像处理,遇到了一个奇怪的问题。

例如我有一个 2*2 的黑白位图图像,其像素如下:

black white

white black

使用 PIL 并将其转换为 numpy:

>>> import Image
>>> import numpy
>>> im = Image.open('test.bmp')
>>> im
<BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x95A54EC>
>>> numpy.asarray(im)
array([[ True,  True],
       [False, False]], dtype=bool)
>>>

令我困惑的是数组中像素的顺序。为什么不是 [[True, False], [False, True]]?谢谢。


更新:位图在这里: http://njuer.us/clippit/test.bmp

最佳答案

在使用 1 模式转换为 numpy 或从 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)

此外,如果您尝试将 bool 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>

关于python - 如何在PIL和numpy之间转换模式为 "1"的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597525/

相关文章:

python - 选择随机 Action 的 Tensorflow 代理

python - 用另一个 numpy 数组索引 numpy 数组

python - 如何强制 Pillow 将图像调整为任意大小?

python - 如何为 PIL Python 库添加 Tkinter 支持

python - PIL : draw transparent text on top of an image

python - 通过 python django 显示路径中的图像

python - Matplotlib 图形以奇怪的方式显示聚合函数

python - 如何在列的两个值之间选择数据框中的所有行

python - 使用 sys.argv[1] 时为 "list index out of range"

python - 无法建立连接,因为目标机器主动拒绝它(Django)