Last active
October 23, 2023 11:32
-
-
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`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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