
Let’s learn how to implement the convolution operations with NumPy.
Preparation
We need to install the NumPy library in our environment to start the article.
pip install numpy
With the NumPy library installed, we will learn more about how to use NumPy for convolution operations.
Convolution Operations with NumPy
Convolution operations is a process that combines two functions to produce the third function.
It’s often used in image processing to apply filters (kernel) to the image to perform tasks such as blurring, image sharpening, and others. A filter or kernel is a small matrix used to process input data by modifying or extracting it. If we apply the filter to the image input, we perform a convolution operation. By sliding the filter over the input, the filter can perform its tasks well.
Let’s see an example of code to execute the convolution operations. First, let’s develop a numpy function that takes an image input and the kernel. The function output would be the image to which we have applied the kernel with convolution operations.
import numpy as np
def convolve2d(image, kernel):
kernel = np.flipud(np.fliplr(kernel))
x_image, y_image = image.shape
x_kernel, y_kernel = kernel.shape
x_output = x_image - x_kernel + 1
y_output = y_image - y_kernel + 1
output = np.zeros((x_output, y_output))
for i in range(x_output):
for j in range(y_output):
region = image[i:i + x_kernel, j:j + y_kernel]
output[i, j] = np.sum(region * kernel)
return output
Then, we prepare the image representation and the kernel.
image = np.array([
[1, 1, 1, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 0],
[1, 1, 0, 0, 0]
])
kernel = np.array([
[1, 0, -1],
[1, 0, -1],
[1, 0, -1]
])
Lastly, let’s see how to perform the convolutional operations with the function we have prepared.
convolved_image = convolve2d(image, kernel) convolved_image
Output:
[[ 2. 0. -2.] [ 3. 2. -2.] [ 1. 1. -1.]]
The output is the image transformed with the kernel. The kernel we used in the example above is for edge detection.
You could try many filters, such as the sharpening filter.
sharpen_filter = np.array([
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]
])
Or the emboss filter to give the image a 3D appearance.
emboss_filter = np.array([
[-2, -1, 0],
[-1, 1, 1],
[ 0, 1, 2]
])
Try to experiment with the kernel and convolutional operations to manipulate your image.
