Working with 2D arrays or matrices is a fundamental aspect of data analysis and scientific computing. In many cases, it's necessary to add padding to a matrix, which means adding additional rows and columns around the edges of the matrix.
Adding padding to a numpy 2D matrix is quite easy and can be achieved using a few different numpy functions. In this article, we'll explore how to add padding to a 2D matrix in numpy with code examples.
What is Padding?
Padding is the process of adding additional rows and columns around the edges of a matrix. Padding is generally used when working with convolutional neural networks (CNNs) as well as image processing tasks, such as computer vision.
When working with matrices, it is often important to work with the edges of the matrix without losing data. Padding is a way to add extra spaces around the edges of the matrix so that the edges can be processed correctly.
There are two types of padding: zeropadding and reflection padding. Zeropadding is the process of adding rows and columns of zeros around the edges of the matrix, whereas reflection padding involves reflecting the original matrix around the edges instead of adding zeros.
Python Numpy
Python Numpy is a popular library that offers a wide range of tools and functions for working with arrays. One of the most common uses of Numpy is for working with 2D matrices or arrays.
Adding Padding to a 2D matrix using Numpy
To add padding to a 2D matrix using Numpy, there are a few essential steps to follow, which we’ll explain below.
Step 1: Create a 2D matrix or array.
Before you can add padding to a 2D matrix, you must first have a 2D matrix in the form of a numpy array.
For instance, assume you have a 2D array as shown below:
import numpy as np
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(matrix)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Step 2: Define the number of rows and columns to be added as padding.
You need to specify the number of rows and columns to be added as padding. For instance, if you want to add one row and one column of zeros around the edges of your matrix, you can use the following code:
pad_width = ((1, 1), (1, 1))
new_matrix = np.pad(matrix, pad_width, mode='constant')
print(new_matrix)
[[ 0 0 0 0 0 0]
[ 0 1 2 3 4 0]
[ 0 5 6 7 8 0]
[ 0 9 10 11 12 0]
[ 0 0 0 0 0 0]]
The above code adds one row of zeros above and below the matrix and one column of zeros to the left and right. The new_matrix is the padded matrix.
Step 3: Using other padding style modes
As discussed earlier, Numpy offers two different types of padding: zeropadding and reflection padding. The following functions are used for padding with numpy array.

constant: This is the default mode for padding and is used to add a specified constant value around the edges of a matrix.

reflect: Reflect padding reflects the edges of the matrix instead of adding zeros. It works by flipping the values of the edges of the matrix and attaching them to the edges of the existing matrix.

wrap: Wrap padding is similar to reflection padding but instead of flipping the edges, wrap mode attaches them in reverse order to the existing matrix.

symmetric: Symmetric padding works by taking the values from the edges of the matrix and repeating them in reverse order at the edges of the existing matrix.
For example, Let's see how reflection padding works with numpy
reflection_matrix = np.pad(matrix, pad_width, mode='reflect')
print(reflection_matrix)
[[12 11 10 11 12 13]
[ 8 7 6 7 8 9]
[ 4 3 2 3 4 5]
[ 8 7 6 7 8 9]
[12 11 10 11 12 13]]
Using the reflection mode of padding, the edges of the matrix are reflected around the edges of the matrix resulting in a slightly larger matrix.
Step 4: Padding an image
In addition to 2D arrays, numpy arrays can also be used to represent images. Images usually have different dimensions, for instance, 600 x 400 pixels.
To pad an image, you can convert it into a numpy array and use the same padding techniques as shown earlier.
from PIL import Image
import numpy as np
# Open image using pillow library
im = Image.open("image.png")
im.show()
# Convert to grayscale numpy array
im_array = np.array(im.convert('L'))
# define the number of pixels to add as padding
pad_pixels = 50
# pad the image with grayscale padding
padded_array = np.pad(im_array, ((pad_pixels, pad_pixels), (pad_pixels, pad_pixels)), mode="constant", constant_values=255)
padded_image = Image.fromarray(padded_array)
padded_image.show()
The code above adds 50 pixels of padding with a white color to the image.
Conclusion
Padding a 2D numpy array, scalar, or a list is an essential element in image processing and scientific computing. In this article, we have covered the basics of how to add padding to a 2D numpy array using Numpy’s constant and reflection modes. You can apply the same techniques demonstrated here to add padding to 1D arrays or higherdimensional matrices.
Now you are ready to pad a numpy matrix of any shape!
Padding is a technique that is widely used in machine learning, especially in convolutional neural networks (CNNs) for image processing tasks. Padding ensures that the output volume of the neuron will have the same size as the input volume during convolution, pooling, or other operations. Therefore, it's essential to have a solid understanding of how to implement padding efficiently.
In numpy, the method used to add padding to a matrix is np.pad()
, which takes three arguments: the matrix to be padded, the number of rows and columns of padding to be added, and the mode of padding.
The most common method of padding is zeropadding, which adds zeros to the edges of the matrix. You can use the constant
mode to achieve this. Alternatively, other padding modes like edge
, reflect
, symmetric
, wrap
can also be used for padding. The mode you choose depends on the problem you are working on.
Another important aspect to remember when employing padding is the size of the original matrix before padding. When padding, you'll be adding an extra row or column to the input volume, so the kernel's effective size (the dimension of the features being computed) is also increased.
In addition to padding a numpy array with zeros, you can also use masking to make certain parts of the array appear as if they're not even present. Masking can be defined as the process of removing or blocking off a particular part of an image or matrix.
Masking is achieved in numpy by setting the value of the array to be masked as zero. Masking can be helpful when you want to exclude certain areas of an image or data from processing, like a noisy portion or when you want to concentrate on a specific area of an image.
Here is an example of masking a numpy array using a random array:
import numpy as np
# Define a random 2D array
arr = np.random.rand(4, 4)
# Define the mask as an array of same shape with the elements as 0 or 1
mask = np.array([[0, 1, 1, 0], [1, 0, 0, 0], [0, 0, 1, 1], [1, 1, 0, 0]])
# Mask the array by multiplying with the mask array
masked_arr = arr * mask
print(masked_arr)
Output:
array([[0. , 0.87657995, 0.92363587, 0. ],
[0.60307602, 0. , 0. , 0. ],
[0. , 0. , 0.55820475, 0.85823091],
[0.98775622, 0.57071473, 0. , 0. ]])
The above code defines a random 2D numpy array of size 4×4 and defines a mask with four different sections. The code then applies the mask to the array, making the parts corresponding to the value 0
in the mask to become zero, and the other parts will retain their original value.
Now that you know how to add padding and apply masks to numpy arrays, you can explore and implement these techniques in different machine learning applications and image processing tasks.
Popular questions
 What is padding in the context of 2D matrices?
Padding is the process of adding additional rows and columns around the edges of a matrix. Padding is generally used when working with convolutional neural networks (CNNs) as well as image processing tasks, such as computer vision.
 What is the function used for adding padding to 2D matrices in Numpy?
The method used to add padding to a matrix is np.pad()
.
 What is the purpose of padding in machine learning?
Padding ensures that the output volume of the neuron will have the same size as the input volume during convolution, pooling, or other operations.
 Can different types of padding be used on a 2D matrix?
Yes, different types of padding like zeropadding, reflection padding, edge padding, symmetric padding, and wrap padding can be used on a 2D matrix.
 Is it possible to use masking on a 2D numpy array?
Yes, masking can be achieved in numpy by setting the value of the array to be masked as zero. Masking can be helpful when you want to exclude certain areas of an image or data from processing.
Tag
"Padding"