Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Created January 3, 2016 08:56
Show Gist options
  • Star 41 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kylemcdonald/2f1b9a255993bf9b2629 to your computer and use it in GitHub Desktop.
Save kylemcdonald/2f1b9a255993bf9b2629 to your computer and use it in GitHub Desktop.
Minimal code for rendering a numpy array as an image in a Jupyter notebook in memory. Borrowed from the Deep Dream notebook.
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
@whyboris
Copy link

whyboris commented Aug 4, 2018

@ctmakro - thank you for the elegant solution -- image shows directly in Jupyter Lab 👍

@chrisdonahue
Copy link

This works for Google colab (mostly for my own reference)

import IPython.display
import PIL.Image
IPython.display.display(PIL.Image.fromarray(a))

@0xRampey
Copy link

0xRampey commented May 8, 2020

It's a lot simpler with matplotlib:

from matplotlib.pyplot import imshow
%matplotlib inline

#image is a numpy array
imshow(image)

https://gist.github.com/prampey/dc0e3326131baaf35c380e7ddbf5119a

@rueberger
Copy link

imshow does not faithfully render an array as an image and is generally annoying. There is good reason to use PIL for this

@0xRampey
Copy link

That’s strange, Imshow Has worked for me with any 3D NumPy array. Do you have an example? @rueberger
In fact, it also works with PIL images out-of-the-box.

import PIL.Image
imshow(PIL.Image.open(img_path))

@rueberger
Copy link

It interpolates by default. From the docs "The number of pixels used to render an image is set by the Axes size and the dpi of the figure. This can lead to aliasing artifacts when the image is resampled because the displayed image size will usually not match the size of X".

Just a lot of nonsense to wade through when you just want to see a faithful representation of an image array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment