Reputation: 55
I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:
import matplotlib.pyplot as plt
import numpy as np
import PIL
rgb_img = plt.imread('some-image.png')
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))
plt.imshow(PIL_rgb_img)
I get a black screen. I tried with and without converting to uint8, and I also tried only keeping the RGB channels out of the entire RGBA data. Nothing worked.
Upvotes: 2
Views: 2551
Reputation: 967
I may not give you a full explanation , (for that, you may read matplotlib's functions docs) but clearly with some tests the following is happening:
when you call:
rgb_img = plt.imread('img.png')
it gives a numpy float array, which will read colors between [0 - 1] as white and black ( and for RGB also )
when you call:
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))
which convert it to uint8
values, it just take what supposed to be 255 and make it 1
which is completely wrong,
you know in uint8
the values should be between [0 - 255]
and when you put :
plt.imshow(PIL_rgb_img)
it just show a 255 times 'faded' image , which is very close to black..
P. S.:
That's only happen with '.png' files,
something with plt.imread
..
to solve just put :
img = 'some_img.png'
rgb_img = plt.imread(img)
if img.split('.')[-1]=='png':
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img*255))
else:
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))
plt.imshow(PIL_rgb_img)
That's should fix it.
Upvotes: 2
Reputation: 49
from PIL import Image
import numpy as np
#PIL to Numpy
pil_img = Image.open('some-image.png')
numpy_img = np.asarray(pil_img)
#Numpy to PIL
resultImage = Image.fromarray(numpy_img)
Upvotes: 1