[Python] Convert boolean numpy array to pillow image

Discussão em 'Python' iniciado por Stack, Maio 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm currently working with image processing in python using the scikit-image library. I'm trying to make a binary image using sauvola thresholding with the following code:

    from PIL import Image
    import numpy
    from skimage.color import rgb2gray
    from skimage.filters import threshold_sauvola

    im = Image.open("test.jpg")
    pix = numpy.array(im)
    img = rgb2gray(pix)

    window_size = 25
    thresh_sauvola = threshold_sauvola(img, window_size=window_size)
    binary_sauvola = img > thresh_sauvola


    Which gives the following result: [​IMG]

    the output is a numpy array with data type of this image is a bool

    [[ True True True ... True True True]
    [ True True True ... True True True]
    [ True True True ... True True True]
    ...
    [ True True True ... True True True]
    [ True True True ... True True True]
    [ True True True ... True True True]]


    The problem is that I need to convert this array back to a PIL image using the following line of code:

    image = Image.fromarray(binary_sauvola)


    which makes the image look like this:

    [​IMG]

    I also tried to change the data type from bool to uint8 but then I'll get the following exception:

    AttributeError: 'numpy.ndarray' object has no attribute 'mask'


    So far I haven't found a solution to get a PIL image which looks like the result of the thresholding.

    Continue reading...

Compartilhe esta Página