Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL bitmap/png from array with 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')

Sorry browser is probably going to try to interpolate this, but it is an 8x8 PNG.

What am I missing?

Relevant PIL docs: https://pillow.readthedocs.org/handbook/concepts.html#concept-modes

$ pip freeze
numpy==1.9.2
Pillow==2.9.0
wheel==0.24.0
like image 709
Jason Dunkelberger Avatar asked Aug 22 '15 17:08

Jason Dunkelberger


People also ask

What is mode in PIL image?

Modes. The mode of an image is a string which defines the type and depth of a pixel in the image. Each pixel uses the full range of the bit depth.

How do I read an image using Python PIL?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).


1 Answers

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')
like image 100
hennes Avatar answered Sep 22 '22 16:09

hennes