How to split an Image into Patches with Python
Split an image into parts of equal size with this Python library

For different reasons, someone might need to split an image into patches of the same size. Once, I had to do it because my Machine Learning model couldn’t process high-resolution images, thus, I divided them into multiple parts. In the beginning, I myself wrote the code for splitting, but then I discovered Patchify, which is a great library made for this purpose. It provides two functions: patchify and unpatchify. The former is used to split an image into patches and the latter to merge them.
To install the latest version of Patchify from PyPI use:
pip install patchify
Patchify
This function splits an image into multiple patches of the same size.

To call it use:
patchify(image, patch_shape, step)
Arguments:
imageis a NumPy array with shape (image_height, image_width) for grayscale images or (image_height, image_width, N) for N-channels images (3 if RGB).patch_shapeis the shape of each patch, (patch_height, patch_width) or (patch_height, patch_width, N). It’s not required to define a square patch, even a rectangular patch can be defined.stepdefines the distance between one patch and the next one (vertically and horizontally). If step ≥ patch_height there is no overlap between patches in the same row. If step ≥ patch_width there is no overlap between patches in the same column.
Return:
If image is N-channels, the function returns a NumPy array with shape (n_rows, n_cols, 1, H, W, N), where n_rows is the number of patches for each column and n_cols is the number of patches for each row.
Otherwise, if image is grayscale, the function returns a NumPy array with shape (n_rows, n_cols, 1, H, W).
The code below splits an RGB image and saves each patch in a new file using an incrementing filename:













