Extract patches from an image

from sklearn.datasets import load_sample_image from sklearn.feature_extraction.image import extract_patches_2d import numpy as np from PIL import Image import matplotlib.pyplot as plt dpi = 100 plot_width, plot_height = 1200, 800 width_inches, height_inches = plot_width/dpi, plot_height/dpi plt.figure(figsize=(width_inches, height_inches), dpi=dpi, facecolor='w', edgecolor='k', frameon=False) flower = load_sample_image('flower.jpg') patches = extract_patches_2d(flower, patch_size=(80, 120), max_patches=100) # Note: forgetting to set max_patches may quickly fill your disk with images! # Save patches as images for i, patch in enumerate(patches): im = Image.fromarray(patch, 'RGB') im.save('patches/patch%d.jpg' % (i,)) # Show original image plt.imshow(flower) plt.axis('off') plt.tight_layout() plt.show() # Show patches in a 10x10 grid gridx, gridy = 10, 10 fig, ax = plt.subplots(gridx, gridy, figsize=(width_inches, height_inches), dpi=dpi, facecolor='w', edgecolor='k', frameon=False) for i in range(gridx): for j in range(gridy): im = np.array(Image.open('patches/patch%d.jpg' % (10*i + j,))) ax[i, j].axis('off') ax[i, j].imshow(im) # Save grid as image plt.savefig('image_grid.jpg', dpi=dpi, bbox_inches='tight', transparent=True) # Show grid plt.show()

The image used to obtain patches

The original image of the flower

The patches

The patches resulting from the input image