Extracting patches from large images using Python
When training any deep learning algorithm we preferred to use small images because using small images gives better performance. But what to do when we have large images. One way to overcome this problem is by dividing the larger images into smaller patches so that we can train any algorithm.
In this article, we will learn how to extract patches from large images using Python. There is a Python library called patchify that can use to cut down images and store the cropped images or patched images into a NumPy. We can install patchify library using the command
pip install patchify
Patchify can divide the image into small overlapping areas according to the given patch unit size, and merge the areas with the original image.
Usage of patchify
Splitting 2D images into patches
# This command will split the 2D image into smaller images of size [3, 3] patches = patchify(image, (3, 3), step=1)
Splitting 3D images into patches
# This command will split the 3D image into smaller images of size [3, 3, 3] patches = patchify(image, (3, 3, 3), step=1)
import numpy as np from patchify import patchify # image of shape 4*4 image = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13, 14, 15, 16]]) print(image.shape) patches = patchify(image, (2,2), step=2) # split image into 2*2 small 2*2 patches. print(patches.shape)
(2, 2, 2, 2)
Similarly, we can perform for 3D images.