Skip to content

Instantly share code, notes, and snippets.

@zori
Forked from kylemcdonald/showarray.py
Last active November 21, 2017 07:24
Show Gist options
  • Save zori/3e946a189a21ff660f535302cf87aea6 to your computer and use it in GitHub Desktop.
Save zori/3e946a189a21ff660f535302cf87aea6 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.
# python3
from io import BytesIO
import IPython.display
import numpy as np
import PIL.Image
def showarray(a, fmt='png'):
a = np.uint8(a)
f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
showarray(np.random.rand(300, 700, 3) * 255)
# # python2
# 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()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment