模式= 1的数组中的Python PIL位图/png

标签 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')

抱歉,浏览器可能会尝试对此进行插值,但它是一个 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/

相关文章:

python - 舍入到 pandas 数据框中最接近的最小值

Python 原生解析具有未知路径分隔符的路径名

python - Pandas 文档操作 k 至 1000

python - Scrapy - 动态创建字段的正确选择器

python - Celery WorkerLostError Worker 过早退出 : signal 6 (SIGABRT)

MATLAB大规模多任务技术

python - 高效计算点云的体素指数

Python:如何使类 `__call__` 方法接受 NumPy 数组和单个值?

python - 如何在Python中使用second作为透明二进制掩码合并两个图像?

android 崩溃屏幕旋转