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

11

372

I have created an array thusly:

import numpy as np
data = np.zeros( (512,512,3), dtype=np.uint8)
data[256,256] = [255,0,0]

What I want this to do is display a single red dot in the center of a 512x512 image. (At least to begin with... I think I can figure out the rest from there)

Babettebabeuf answered 17/4, 2010 at 17:28 Comment(1)
See also #903261 although that one imposed the constraint that PIL could not be used.Hauser
P
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()
Polytechnic answered 17/4, 2010 at 17:46 Comment(6)
It seems that there is a bug. You create array with size (w,h,3), but it should be (h,w,3), because indexing in PIL differs from indexing in numpy. There is related question: #33725737Carditis
@user502144: Thanks for pointing out my error. I should have created an array of shape (h,w,3). (It's now fixed, above.) The length of the first axis can be thought of as the number of rows in the array, and the length of the second axis, the number of columns. So (h, w) corresponds to an array of "height" h and "width" w. Image.fromarray converts this array into an image of height h and width w.Polytechnic
img.show() don't work in ipython notebook.img_pil = Image.fromarray(img, 'RGB') display(img_pil.resize((256,256), PIL.Image.LANCZOS))Sheryl
@Polytechnic this method seems to distort images ... #62293577Arlina
Having Image.fromarray(...) as the last expression of a cell sufficed to display the image for me in Google Colab. No need to write to a file or call .show().Demitria
How can i use matrix data in html for showing image.Architectonics
K
437

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 
Karen answered 17/4, 2010 at 17:43 Comment(4)
This is more accurate than PIL. PIL rescales/normalizes the array values, whereas pyplot uses the actual RGB values as they are.Effervesce
Maybe good to know: If you want to display grayscale images, it is advisable to call plt.gray() once in your code to switch all following graphs to grayscale. Not what the OP wants but good to know nevertheless.Barris
How to save it?Unmistakable
@Barris Also, grayscale images should have shape(h, w) rather than (h, w, 1). You can use squeeze() to eliminate the third dimension: plt.imshow(data.squeeze())Dalmatia
P
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()
Polytechnic answered 17/4, 2010 at 17:46 Comment(6)
It seems that there is a bug. You create array with size (w,h,3), but it should be (h,w,3), because indexing in PIL differs from indexing in numpy. There is related question: #33725737Carditis
@user502144: Thanks for pointing out my error. I should have created an array of shape (h,w,3). (It's now fixed, above.) The length of the first axis can be thought of as the number of rows in the array, and the length of the second axis, the number of columns. So (h, w) corresponds to an array of "height" h and "width" w. Image.fromarray converts this array into an image of height h and width w.Polytechnic
img.show() don't work in ipython notebook.img_pil = Image.fromarray(img, 'RGB') display(img_pil.resize((256,256), PIL.Image.LANCZOS))Sheryl
@Polytechnic this method seems to distort images ... #62293577Arlina
Having Image.fromarray(...) as the last expression of a cell sufficed to display the image for me in Google Colab. No need to write to a file or call .show().Demitria
How can i use matrix data in html for showing image.Architectonics
H
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)
Hauser answered 17/4, 2010 at 17:42 Comment(6)
So this method is incompatible with python 3.5...?Abyssinia
@bordeo, why would it be incompatible with 3.5? It just an import and a couple of function calls.Hauser
PIL is incompatible with 3.5 (won't install)Abyssinia
Ftr: you can shorten this further by directly using scipy.misc.imshow(data).Abbotson
toimage was deprecated in scipy-1.0.0 and removed in 1.2.0, in favor of Pillow’s Image.fromarray.Accordingly
scipy.misc.imshow() is deprecated. Use matplotlib.pyplot.imshow(data) instead. Also, in IPython, you need to run matplotlib.pyplot.show() to show the image display window.Saleem
P
19

How to show images stored in numpy array with example (works in Jupyter notebook)

I know there are simpler answers but this one will give you understanding of how images are actually drawn from a numpy array.

Load example

from sklearn.datasets import load_digits
digits = load_digits()
digits.images.shape   #this will give you (1797, 8, 8). 1797 images, each 8 x 8 in size

Display array of one image

digits.images[0]
array([[ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.],
       [ 0.,  0., 13., 15., 10., 15.,  5.,  0.],
       [ 0.,  3., 15.,  2.,  0., 11.,  8.,  0.],
       [ 0.,  4., 12.,  0.,  0.,  8.,  8.,  0.],
       [ 0.,  5.,  8.,  0.,  0.,  9.,  8.,  0.],
       [ 0.,  4., 11.,  0.,  1., 12.,  7.,  0.],
       [ 0.,  2., 14.,  5., 10., 12.,  0.,  0.],
       [ 0.,  0.,  6., 13., 10.,  0.,  0.,  0.]])

Create empty 10 x 10 subplots for visualizing 100 images

import matplotlib.pyplot as plt
fig, axes = plt.subplots(10,10, figsize=(8,8))

Plotting 100 images

for i,ax in enumerate(axes.flat):
    ax.imshow(digits.images[i])

Result:

enter image description here

What does axes.flat do? It creates a numpy enumerator so you can iterate over axis in order to draw objects on them. Example:

import numpy as np
x = np.arange(6).reshape(2,3)
x.flat
for item in (x.flat):
    print (item, end=' ')
Phosphine answered 12/12, 2019 at 2:12 Comment(1)
Useful content about the axes.flat. I have always been writing two for loops for nothing... Crazy stuff!Selfjustifying
A
9

Using pillow's fromarray, for example:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()
Aphra answered 21/8, 2019 at 18:54 Comment(0)
S
9
import numpy as np
from keras.preprocessing.image import array_to_img
img = np.zeros([525,525,3], np.uint8)
b=array_to_img(img)
b
Scotticism answered 6/8, 2020 at 7:28 Comment(0)
K
7

Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You'll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.

Kanya answered 17/4, 2010 at 17:35 Comment(0)
S
3

Supplement for doing so with matplotlib. I found it handy doing computer vision tasks. Let's say you got data with dtype = int32

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))
Sort answered 19/5, 2020 at 17:41 Comment(0)
S
3

For example your image is in an array names 'image'

All you do is

plt.imshow(image)
plt.show

This will display an array in the form of an image Also, dont forget to import PLT

Sinclare answered 20/3, 2022 at 16:8 Comment(0)
S
0

The Python Imaging Library can display images using Numpy arrays. Take a look at this page for sample code:

EDIT: As the note on the bottom of that page says, you should check the latest release notes which make this much simpler:

http://effbot.org/zone/pil-changes-116.htm

Sacci answered 17/4, 2010 at 17:39 Comment(1)
this doesn't answer the questionLavena
H
0

this could be a possible code solution:

from skimage import io
import numpy as np
data=np.random.randn(5,2)
io.imshow(data)
Hunkydory answered 23/10, 2020 at 6:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.