The Python Oracle

How do I convert a numpy array to (and display) an image?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 How Do I Convert A Numpy Array To (And Display) An Image?
00:26 Answer 1 Score 53
00:54 Answer 2 Score 443
01:18 Accepted Answer Score 355
01:32 Answer 4 Score 9
01:42 Thank you

--

Full question
https://stackoverflow.com/questions/2659...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #image #numpy #datavisualization

#avk47



ANSWER 1

Score 443


Use plt.imshow to create the figure, and plt.show to display it:

from matplotlib import pyplot as plt
plt.imshow(data, interpolation='nearest')
plt.show()

For Jupyter notebooks, add this line before importing matplotlib:

%matplotlib inline 

For interactive plots in Jupyter [demo], install ipyml pip install ipympl, then use:

%matplotlib widget 



ACCEPTED ANSWER

Score 355


You could use PIL to create (and display) an image:

from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()



ANSWER 3

Score 53


Note: both these APIs have been first deprecated, then removed.

Shortest path is to use scipy, like this:

# Note: deprecated in v0.19.0 and removed in v1.3.0
from scipy.misc import toimage
toimage(data).show()

This requires PIL or Pillow to be installed as well.

A similar approach also requiring PIL or Pillow but which may invoke a different viewer is:

# Note: deprecated in v1.0.0 and removed in v1.8.0
from scipy.misc import imshow
imshow(data)



ANSWER 4

Score 9


Using pillow's fromarray, for example:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()