Skip to content

Instantly share code, notes, and snippets.

@rdinse
Created May 1, 2018 19:09
Show Gist options
  • Save rdinse/77b11fa7f232485b55f4e43f726de397 to your computer and use it in GitHub Desktop.
Save rdinse/77b11fa7f232485b55f4e43f726de397 to your computer and use it in GitHub Desktop.
Simple imshow for Jupyter Notebook and Google Colaboratory
# Valid image shapes: (H, W), (H, W, 1) for grey-scale images and (H, W, 3) for
# color images. For info about the interpolation order, see the
# [skimage docs](https://goo.gl/vGE6dv). Setting `fmt='jpeg'` might come in
# handy in case of large images. Example Output: https://i.stack.imgur.com/nb2vG.png
import numpy as np
from io import BytesIO
from base64 import b64encode
import PIL.Image, IPython.display
from skimage import transform
import imageio
def imshow(img, fmt='png', norm=False, clip=True, scale=1., order=0, title=''):
if len(img.shape) == 3 and img.shape[-1] == 1:
img = np.squeeze(img, axis=2)
if norm:
img = 255. * (img - img.min()) / (img.max() - img.min())
if clip:
img = np.clip(img, 0., 255.)
if scale != 1.:
new_size = (scale * img.shape[0], scale * img.shape[1])
img = transform.resize(img, new_size, order, preserve_range=True)
b = BytesIO()
PIL.Image.fromarray(np.uint8(img)).save(b, fmt)
h = '<img src="data:image/%s;base64,%s" style="vertical-align:middle;' \
'display:inline;"/> <small>%s</small>' \
% (fmt, b64encode(b.getvalue()).decode(), title)
IPython.display.display(IPython.display.HTML(h))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment