Python Patchify – Extracting Patches from Large Images

Feautured Img Image Patches

In this tutorial, we’ll look at how to use the Python programming language to extract patches from huge photos.


Introduction

When training any deep learning algorithm, we prefer to use small images because they produce better results. But what if we have huge images? One solution is to divide the larger photos into smaller patches, allowing us to train any algorithm.

You might be wondering what patch means? As the name implies, an image patch is a group of pixels in a picture. Assume I have a 20 by 20-pixel image. It can be divided into 1000 square patches of 2 × 2 pixels each.


Introduction to Python Patchify

Python Patchify is a package that is used to crop photos and save the cropped or patched images in a Numpy array. But first, make sure that you have patchify installed in your system using the pip command.

pip install patchify

Patchify can divide a picture into small overlapping sections based on the patch unit size specified, and then fuse the areas with the original image.


Using Python Patchify to Extract Image Patches

Let’s get started with using the module now and start extracting image patches here.

1. Importing Modules

We start off by importing modules necessary for converting large images to patches. Numpy here is used to create image data and the patchify module is used to convert images to image patches.

import numpy as np
from patchify import patchify

2. Create Image Data

We create the image data in the form of numpy array and let’s look at the initial shape of the image.

image = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13, 14, 15, 16]])
print(image.shape)

3. Extract Patches from Image

patches = patchify(image, (2,2), step=2) 
print(patches.shape)

Complete Code and Output

import numpy as np
from patchify import patchify
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) 
print(patches.shape)
(4, 4)
(2, 2, 2, 2)

I hope you are clear with the concept and understood generating patches as well. The same can be applied to 3D images as well! Try it out!

Happy coding! 😇