Why are pillow and numpy incorrectly converting my image sometimes (but not all of the time)?

I’m making a program that involves converting pillow (PIL) images to numpy arrays and numpy arrays back to images. However, it is converting some (but not all) images back into a grainy, grayscale version of what they were before.

The relevant part of the code is:

from PIL import Image, fromarray
from numpy import asarray
im = Image.open("C:\path\to\image")
pixels = asarray(im)
Image.fromarray(pixels).show()

This code is supposed to display the same image that it originally opened. It works for some images. For example, the following image of the flag of Andorra: The flag of Andorra . However, it doesn’t work for other images, such as this image of the flag of Albania: The flag of Albania. Instead, it becomes a grainy black and white image:Flag of Albania 2. Having looked at the numpy arrays it generates, it looks like it is generating a number rather than an RGB tuple for each pixel in the the images where this doesn’t work, but I can’t figure out why. How would I make it so that the flag converts back and forth correctly?

Answer

The Andorra flag is an RGB image, the Albania flag is a colormap image. PIL can convert colormap to RGB:

im = Image.open("C:\path\to\image").convert('RGB')
print(im.mode)  # => now it prints always RGB, without convert it would print P for colormap images

You may find some documentation here.

Leave a Reply

Your email address will not be published. Required fields are marked *