Convert boolean numpy array to pillow image

Update

This bug has now been solved in Pillow==6.2.0. The link to the issue on GitHub is here.

If you cannot update to the new version of Pillow, please see below.


PIL's Image.fromarray function has a bug with mode '1' images. This Gist demonstrates the bug, and shows a few workarounds. Here are the best two workarounds:

import numpy as np
from PIL import Image

# The standard work-around: first convert to greyscale 
def img_grey(data):
    return Image.fromarray(data * 255, mode='L').convert('1')

# Use .frombytes instead of .fromarray. 
# This is >2x faster than img_grey
def img_frombytes(data):
    size = data.shape[::-1]
    databytes = np.packbits(data, axis=1)
    return Image.frombytes(mode='1', size=size, data=databytes)

Also see Error Converting PIL B&W images to Numpy Arrays.