Skip to content

Instantly share code, notes, and snippets.

@crackwitz
Last active September 2, 2022 04:19
Show Gist options
  • Save crackwitz/975e81dc4ed48c67af0515cb0924ceb9 to your computer and use it in GitHub Desktop.
Save crackwitz/975e81dc4ed48c67af0515cb0924ceb9 to your computer and use it in GitHub Desktop.
"imshow" shim for jupyter notebooks, kinda like google colab's cv_imshow
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