Convert boolean numpy array to pillow image Convert boolean numpy array to pillow image numpy numpy

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 npfrom 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_greydef 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.


This option might was not available 2018 but currently

from skimage.io._plugins.pil_plugin import ndarray_to_pil, pil_to_ndarrayndarray_to_pil(some_binary_image).convert("1")

seems to do the trick.