Search code examples
pythonnumpypython-imaging-librarypngcolor-palette

How to retain the colors of a PNG image when converting back from an array


Whenever I convert a PNG image to a np.array and then convert it back to a PNG I lose all the colors of the image. I would like to be able to retain the colors of the original PNG when I am converting it back from a np.array.

Original PNG Image

enter image description here

My code:

from PIL import Image    

im = Image.open('2007_000129.png')
im = np.array(im)

#augmenting image
im[0,0] = 1

im = Image.fromarray(im, mode = 'P')

Outputs a black and white version of the image

enter image description here

I also try using getpalette and putpalette but this does not work it just returns a NonType object.

im = Image.open('2007_000129.png')
pat = im.getpalette()
im = np.array(im)
im[0,0] = 1
im = Image.fromarray(im, mode = 'P')
im= im.putpalette(pat)

Solution

  • Using the second code provided, the error comes from this line:

    im= im.putpalette(pat)
    

    If you refer to the documentation of Image.putpalette, you see that this function doesn't return any value, thus Image.putpalette is applied to the corresponding image directly. So, (re-)assigning the non-existent return value (which then is None) is not necessary – or, as seen here, erroneous.

    So, the simple fix is just to use:

    im.putpalette(pat)
    

    Using this change, the second code provided works as intended.