模式为1的数组中的Python PIL位图/png [英] Python PIL bitmap/png from array with mode=1

查看:105
本文介绍了模式为1的数组中的Python PIL位图/png的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次玩PIL(和numpy).我试图通过mode ='1'生成黑白棋盘图像,但它不起作用.

Playing with PIL (and numpy) for the first time ever. I was trying to generate a black and white checkerboard image through mode='1', but it doesn't work.

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.

Sorry browser is probably going to try to interpolate this, but it is an 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

推荐答案

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

There seem to be issues when using mode 1 with numpy arrays. As a workaround you could use mode L and convert to mode 1 before saving. The below snippet produces the expected checkerboard.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆