1

I need to show a background to a matplotlib plot using ax.imshow(). The background images that I will be using are GIF-images. Despite having PIL installed, the following code results in an error complaining that the Python Image Library (PIL) is not installed (which it is):

from pylab import imread
im_file = open("test.gif")
im_obj = imread(im_file)

Reading the image using PIL directly works better:

from PIL import Image
import numpy
img = Image.open("test.gif")
img_arr = asarray(img.getdata(), dtype=numpy.uint8)

However, when reshaping the array, the following code does not work:

img_arr = img_arr.reshape(img.size[0], img.size[1], 3) #Note the number 3

The reason is that the actual color information is contained in a color table accessed through img.getcolors() or img.getpalette().

Converting all the images to PNG or another suitable format that results in RGB images when opening them with imread() or Image.open() is not an option. I could convert the images when needed using PIL but I consider that solution ugly. So the question is as follows: Is there a simple and fast (the images are 5000 x 5000 pixels) way to convert the GIF images to RGB (in RAM) so that I can display them using imshow()?

whiletrue
  • 10,500
  • 6
  • 27
  • 47
Jonas Nilsson
  • 85
  • 1
  • 10

1 Answers1

2

You need to convert the GIF to RGB first:

img = Image.open("test.gif").convert('RGB')

See this question: Get pixel's RGB using PIL

Community
  • 1
  • 1
user545424
  • 15,713
  • 11
  • 56
  • 70