from pathlib import PosixPath
import ipyplot
import cv2
from PIL import Image
= get_ipython().__class__.__name__ == 'ZMQInteractiveShell' is_jupyter
Visualizations
Images
# !pip install opencv-python
= 'assets/image_20211012_row53_col1.png'
im = 'assets/mask_20211012_row53_col1.png' mask
The easiest way to visualize images is through PIL:
= Image.open(im)
im_pil im_pil
If one needs to use OpenCV:
def load_image(im):
if isinstance(im, (str, PosixPath)): # if str or Path load image
= cv2.imread(str(im))
im elif isinstance(im, Image.Image): # convert PIL.Image.Image to numpy.array
= np.array(im)
im return im
def show_image(im, title=None):
"""
Load and show (or not) image using cv2.
Args:
im (str or Path or numpy.array or PIL.Image.Image)
Returns:
key pressed (str)
"""
= load_image(im)
im if not is_jupyter:
print('Image is shown on desktop.')
if title else 'pic-display', im)
cv2.imshow(title print('Press any button to continue (if needed click on an image window too; Q to break).')
= chr(cv2.waitKey(0)) # 0 to wait for user input, >0 for milliseconds to wait
key_pressed return key_pressed
else:
display(Image.fromarray(im))
'image') show_image(im,
Matplotlib.pyplot.axis.plot
See here.
Plot multiple images
We can use ipyplot
(pip install ipyplot
), but it has annoying issue. Instead I made a custom one:
from utils.plot import plot_pil_images
plot_pil_images([im_pil, im_pil, im_pil.transpose(Image.ROTATE_90)], 'orig', 'no change', 'transpose 90']) [
Graphs
The following is a pseudo-code for demonstration.
To specify the legend location:
=(1.04,1)) plt.legend(leg, bbox_to_anchor
some legend arguments:
= plt.legend(loc='best', ncol=2, mode="expand", shadow=True, fancybox=True)
leg 0.5) leg.get_frame().set_alpha(
if no legend is specified then the label
will be used:
**n, label=f"n={n}") plt.plot(t1, t1