Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()))
@zhannar
Copy link

zhannar commented May 5, 2016

This was awesome. Thanks!

Loading

@zori
Copy link

zori commented Jun 28, 2017

for python3 you have to use BytesIO

Loading

@chrisdonahue
Copy link

chrisdonahue commented Oct 18, 2017

I swear I google for this twice a day... thx

Loading

@skulas
Copy link

skulas commented Dec 25, 2017

The StringIO and cStringIO modules are gone after Python 3. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

Loading

@dubois
Copy link

dubois commented Jan 24, 2018

IPython can display PIL.Image directly! So you can skip the encode-to-png and decode-from-png:

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

Loading

@jameslan
Copy link

jameslan commented Mar 21, 2018

Actually,

PIL.Image.fromarray(a)

in jupyter notebook, is enough.

Loading

@michaelarg
Copy link

michaelarg commented Mar 21, 2018

Thanks

Loading

@ctmakro
Copy link

ctmakro commented Apr 29, 2018

things can be made easier if you have cv2: https://gist.github.com/ctmakro/3ae3cd9538390b706820cd01dac6861f

Loading

@whyboris
Copy link

whyboris commented Aug 4, 2018

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

Loading

@chrisdonahue
Copy link

chrisdonahue commented Jul 25, 2019

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

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

Loading

@prampey
Copy link

prampey 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

Loading

@rueberger
Copy link

rueberger commented Jun 25, 2020

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

Loading

@prampey
Copy link

prampey commented Jun 29, 2020

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

Loading

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