Python PIL bitmap/png from array with mode=1

前端 未结 4 1194
长发绾君心
长发绾君心 2021-01-19 16:27

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.



        
4条回答
  •  时光取名叫无心
    2021-01-19 17:12

    I think it is a bug. It has been reported on Github. Although some fix has been commited, it seems that it didn't resolve this problem. Everything works fine if you use mode "L" and then convert image to mode "1", so you can use it as a workaround for your problem:

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

提交回复
热议问题