Last active
September 2, 2022 04:19
-
-
Save crackwitz/975e81dc4ed48c67af0515cb0924ceb9 to your computer and use it in GitHub Desktop.
"imshow" shim for jupyter notebooks, kinda like google colab's cv_imshow
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
try: | |
# https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook | |
get_ipython() # ipython/jupyter context? | |
from PIL import Image | |
from IPython.display import display # takes a while... | |
# IPython.display.clear_output(wait=True) | |
from matplotlib import pyplot as plt | |
def imshow(im): | |
if len(im.shape) == 3: | |
h,w,ch = im.shape | |
else: | |
h,w = im.shape | |
ch = 1 | |
if im.dtype in (np.float32, np.float64): | |
#print("float to uint8") | |
im = np.round(np.clip(im, 0, 1) * 255).astype(np.uint8) | |
if ch == 4: | |
display(Image.fromarray(im[:,:,(2,1,0,3)], mode='RGBA')) | |
elif ch == 3: | |
display(Image.fromarray(im[:,:,(2,1,0)], mode='RGB')) | |
else: | |
if im.dtype == np.uint8: | |
display(Image.fromarray(im, mode='L')) | |
else: | |
display(Image.fromarray(np.clip(im * 255, 0, 255).astype(np.uint8), mode='L')) | |
except NameError as e: | |
#print("NameError:", e) | |
pass | |
except ImportError as e: | |
print(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment