来自模式为 1 的数组的 Python PIL 位图/png

Jas*_*ger 5 python numpy image-processing python-imaging-library

有史以来第一次使用 PIL(和 numpy)。我试图通过 mode='1' 生成黑白棋盘格图像,但它不起作用。

from PIL import Image
import numpy as np

if __name__ == '__main__':
    g = np.asarray(dtype=np.dtype('uint8'), a=[
        [0, 1, 0, 1, 0, 1, 0, 1, ],
        [1, 0, 1, 0, 1, 0, 1, 0, ],
        [0, 1, 0, 1, 0, 1, 0, 1, ],
        [1, 0, 1, 0, 1, 0, 1, 0, ],
        [0, 1, 0, 1, 0, 1, 0, 1, ],
        [1, 0, 1, 0, 1, 0, 1, 0, ],
        [0, 1, 0, 1, 0, 1, 0, 1, ],
        [1, 0, 1, 0, 1, 0, 1, 0, ],
    ])
    print(g)

    i = Image.fromarray(g, mode='1')
    i.save('checker.png')
Run Code Online (Sandbox Code Playgroud)

抱歉,浏览器可能会尝试插入此内容,但它是 8x8 PNG。

我错过了什么?

相关 PIL 文档:https : //pillow.readthedocs.org/handbook/concepts.html#concept-modes

$ pip freeze
numpy==1.9.2
Pillow==2.9.0
wheel==0.24.0
Run Code Online (Sandbox Code Playgroud)

hen*_*nes 9

将模式与 numpy 数组一起使用时似乎存在问题1。作为解决方法,您可以使用模式L并在保存之前转换为模式1。下面的代码片段产生了预期的棋盘。

from PIL import Image
import numpy as np

if __name__ == '__main__':
    g = np.asarray(dtype=np.dtype('uint8'), a=[
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0],
        [0, 255, 0, 255, 0, 255, 0, 255],
        [255, 0, 255, 0, 255, 0, 255, 0]
    ])
    print(g)

    i = Image.fromarray(g, mode='L').convert('1')
    i.save('checker.png')
Run Code Online (Sandbox Code Playgroud)

  • 然而,这是可行的,“Image.frombytes(mode='1', size=data.shape[::-1], data=np.packbits(data, axis=1))”大约比“Image.”快 2 倍。 fromarray(data * 255, mode='L').convert('1')` (5认同)