How do I convert a numpy array to (and display) an image?
The following should work:
from matplotlib import pyplot as pltplt.imshow(data, interpolation='nearest')plt.show()
If you are using Jupyter notebook/lab, use this inline command before importing matplotlib:
%matplotlib inline
A more featureful way is to install ipyml pip install ipympl
and use
%matplotlib widget
see an example.
You could use PIL to create (and display) an image:
from PIL import Imageimport numpy as npw, h = 512, 512data = np.zeros((h, w, 3), dtype=np.uint8)data[0:256, 0:256] = [255, 0, 0] # red patch in upper leftimg = Image.fromarray(data, 'RGB')img.save('my.png')img.show()
Shortest path is to use scipy
, like this:
from scipy.misc import toimagetoimage(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:
from scipy.misc import imshowimshow(data)