有史以来第一次使用 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')
抱歉,浏览器可能会尝试对此进行插值,但它是一个 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
最佳答案
在 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')
关于模式= 1的数组中的Python PIL位图/png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159076/