I'm trying to plot a png file using matplotlib.pyplot.imshow()
but it's showing a bluish image(see below). It works for jpeg file but not for png.
This is the code:
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
im = Image.open('apple_logo.png')
im.save('test.png') #test.png is same as original
data = np.array(im)
print(data)
plt.imshow(data) #shows a bluish image of the logo
The image i'm using:
bluish image:
Python 3.8.2
matplotlib 3.3.0
Pillow 7.2.0
numpy 1.19.0
OS: Windows 10
The original PNG image is an indexed PNG file. That is, it has a palette (i.e. a lookup table for the colors), and the array of data that makes up the image is an array of indices into the lookup table. When you convert im
to a numpy array with data = np.array(im)
, data
is the array of indices into the palette, instead of the array of actual colors.
Use the convert()
method before passing the image through numpy.array
:
data = np.array(im.convert())
thanks! it worked. But can you tell me how does png files' array store which pixel is transparent? because when I do
print(data)
the array contains arrays of just 3 elements like[255 255 255]
only for rgb colors same as jpg files.