convert RGB arrays to PIL image

Viewed 7308

In my code, I am creating a RGB array (256 * 256 * 3) and I need to show it. I am having trouble creating a PIL image from a RGB array. I wrote this code to explain:

import numpy as np
from PIL import Image

image = Image.open('img_test.png')
image.thumbnail((256, 256))
image = image.convert("RGB")
image = np.asarray(image, dtype=np.float32) / 255

PIL.Image.fromarray(image, "RGB").show()

I am getting this image back:

enter image description here

If I am using

import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()

Then I am getting this image: enter image description here

What am I doing wrong with this line?

PIL.Image.fromarray(image, "RGB").show()
3 Answers

You are expecting PIL to handle a 32-bit floating point RGB image, which it cannot - see here.

It can handle, amongst others:

  • RGB as three 8-bit integer values (RGB888), or
  • greyscale float32.

Just do

Image.fromarray(np.array(img).astype(np.uint8).transpose(1,2,0))

The line you mention seems fine, however, I wonder why you do this:

image = np.asarray(image, dtype=np.float32) / 255

If you replace that line by the following, it works for me, using either PIL or matplotlib to show the image:

image = np.asarray(image)
Related