Warm tip: This article is reproduced from stackoverflow.com, please click
image-processing matplotlib numpy python-imaging-library

png file shows bluish image when using plt.imshow()

发布于 2020-11-25 19:45:41

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:

apple_logo image i'm using

bluish image:

bluish image of the apple_logo

Python 3.8.2
matplotlib 3.3.0
Pillow 7.2.0
numpy 1.19.0
OS: Windows 10

Questioner
Manik
Viewed
1
Warren Weckesser 2020-07-20 01:45

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())