Add Padding to Images in Python

Image padding is adding layers of pixels to an image to modify its shape for a given purpose, as shown in the Figure below.

The original image of size (w1, h1) is padded with t pixels to the top, b to the bottom, l to the left, and r to the right. The resulting padded image is (w2, h2) in shape here w2=w1+l+r and h2=h1+t+b.

Figure 1: a pictorial representation of image padding.

This article covers different ways of padding an image (using OpenCV, NumPy, and pillow packages). We will use the following image in our examples. (source: Unsplash)

Example 1: Padding an image using the pillow package

If you don’t have the pillow installed, you can install it with pip with the command

pip install pillow

This package performs padding in two steps. First, it creates an area that matches the desired size of the padded image and fills it with the padding color.

Secondly, it passes the original image to the area created in step 1. The region outside the pasted image becomes the padding region. Let’s see an example.

Output (the padded image):

Example 2: Padding a portrait or landscape image to make it square in shape

To turn a portrait image into a squared image, we need to pad it along the width, and if we want to turn a landscape image into a square, we have to increase the height to match the width through horizontal padding.

Let’s see how to use the pillow to achieve that in coding.

Output (the square padded image):

Shape of original image:  (377, 251)
Shape of padded image:  (377, 377)

The two examples we have discussed perform padding with a solid color. The next two examples use other modes of determining the contents of padding pixels.

Example 3: Using OpenCV for image padding

You can install OpenCV using pip with this command:

pip install opencv-python


Example 4: Use numpy.pad() function to get more padding modes

If you want more options for padding mode than those given by OpenCV in example 3, consider using numpy.pad() method as shown below.



We have covered how to use OpenCV, pillow, and NumPy packages for padding images. After going through the four examples, you should be able to tweak the code examples provided to fit your purpose.