Skip to content

Instantly share code, notes, and snippets.

@jamesWalker55
Last active October 23, 2023 11:32
Show Gist options
  • Save jamesWalker55/39fbc9f7cc090629fa076e935800199e to your computer and use it in GitHub Desktop.
Save jamesWalker55/39fbc9f7cc090629fa076e935800199e to your computer and use it in GitHub Desktop.
Open and show an image in a Python notebook, using `IPython`, `PIL`, and `numpy`.
def open_image(path):
from PIL import Image
import numpy as np
img = Image.open(path)
return np.asarray(img)
# Using PIL and IPython
def show_img(img):
import IPython
from PIL import Image
from io import BytesIO
img = Image.fromarray(img)
with BytesIO() as f:
img.save(f, format="png")
data = f.getvalue()
i = IPython.display.Image(data=data)
IPython.display.display(i)
# Implementation using matplotlib
def show_img(img):
"""image should be in (channel, height, width)"""
assert len(img.shape) == 3
assert img.shape[0] == 3
img = img.permute(1, 2, 0)
%matplotlib inline
import matplotlib.pyplot as plt
from IPython import display
display.clear_output(wait=True)
plt.imshow(img)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment