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

2024-10-01 15:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

有史以来第一次玩皮尔(和纽比)。我试图通过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')

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

我错过了什么?在

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

^{pr2}$

Tags: namefrom图像imageimportnumpy棋盘if
3条回答

我想是个虫子。据报道on Github。虽然有些fix has been commited,但似乎它并没有解决这个问题。如果您使用模式“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')

对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')

正如另一个答案所指出的,你遇到了一个枕头虫,而接受的答案是好的。在

作为PIL/Pillow的替代,您可以使用^{},也可以使用numpngw,这是我编写的一个库,用于将numy数组写入PNG和动画PNG文件。它在github上:https://github.com/WarrenWeckesser/numpngw(它有python包的所有样板文件,但基本文件是numpngw.py),它也在PyPI上。在

下面是一个使用numpngw.write_png创建棋盘图像的示例。这将创建位深度1的图像:

In [10]: g
Out[10]: 
array([[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],
       [0, 1, 0, 1, 0, 1, 0, 1]], dtype=uint8)

In [11]: import numpngw

In [12]: numpngw.write_png('checkerboard.png', g, bitdepth=1)

这是它创造的形象:

8x8 checkerboard

相关问题 更多 >

    热门问题