Created
September 2, 2020 21:03
-
-
Save yinleon/8a6bf8c2f3226a521680f930f3d4339f to your computer and use it in GitHub Desktop.
A helpful function to display grids of images in Jupyter Notebooks.
This file contains hidden or 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
| from PIL import Image | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| img_width, img_height = 400, 300 | |
| def resize_img_to_array(img, img_shape=(244, 244)): | |
| img_array = np.array( | |
| img.resize( | |
| img_shape, | |
| Image.ANTIALIAS | |
| ) | |
| ) | |
| return img_array | |
| def image_grid(fn_images : list, | |
| text : list =[], | |
| top : int = 8, | |
| per_row : int =4): | |
| """ | |
| fn_images is a list of image paths. | |
| text is a list of annotations. | |
| top is how many images you want to display | |
| per_row is the number of images to show per row. | |
| """ | |
| for i in range(len(fn_images[:top])): | |
| if i % 4 == 0: | |
| _ , ax = plt.subplots(1, per_row, | |
| sharex='col', | |
| sharey='row', | |
| figsize=(24, 6)) | |
| j = i % 4 | |
| image = Image.open(fn_images[i]) | |
| image = resize_img_to_array(image, | |
| img_shape=(img_width, | |
| img_height)) | |
| ax[j].imshow(image) | |
| ax[j].axis('off') | |
| if text: | |
| ax[j].annotate(text[i], | |
| (0,0), (0, -32), | |
| xycoords='axes fraction', | |
| textcoords='offset points', | |
| va='top') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for your code.
Important:
Image.ANTIALIASdeprecated, now should be useImage.LANCZOS