# What’s the best way to turn a numpy array into (and display) an image?

## Problem

I’ve made an array like this:

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

The goal is to make a single red dot appear in the center of a 512×512 image. (At least for now… I think I’ll be able to work out the rest.)

## Solution #1

The following should be sufficient:

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

Use this inline command before importing matplotlib if you’re using Jupyter notebook/lab:

``````%matplotlib inline
``````

Installing ipyml pip is a more feature-rich option. Install ipympl and start using it.

``````%matplotlib widget
``````

see an example.

## Solution #2

You could make (and display) an image with PIL:

``````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()
``````

## Solution #3

The shortest path is to utilize scipy, as shown here:

``````from scipy.misc import toimage
toimage(data).show()
``````

This also necessitates the installation of PIL or Pillow.

A related approach, which similarly necessitates PIL or Pillow but may use a different viewer, is:

``````from scipy.misc import imshow
imshow(data)
``````

## Solution #4

There are easier answers, but this one will help you grasp how images are generated from a numpy array.

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

One image is displayed in an array.

``````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.]])
``````

To visualize 100 photos, create empty 10 x 10 subplots.

``````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:

What is the purpose of axes.flat? It generates a numpy enumerator that can be used to iterate through axes and draw things on them. Example:

``````import numpy as np
x = np.arange(6).reshape(2,3)
x.flat
for item in (x.flat):
print (item, end=' ')
``````

``````import numpy as np