Image Convolution in NumPy

  • Read
  • Discuss

Image convolution applies a filter or kernel to an image. The kernel is a small matrix that modifies the image by performing mathematical operations on the pixels. This tutorial will use the NumPy library to perform image convolution.

First, do the necessary imports 

import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline

Step 2: Load the image:

img_raw = cv2.imread("garden.jpeg")
img = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)

The following will be the output

Step 4: Create the kernel:

kernel = np.array([[1, 1, 1], [1, 4, 1], [1, 1, 1]])

Step 5: convolution function:

def matrix_convolve2(image,kernel,a,b,mul):
  img_x, img_y = image.shape
  kernl_x, kernl_y = kernel.shape
  result = image
  for i in range(img_x-int(len(kernel)/2)):
      for j in range(img_y-int(len(kernel)/2)):
          result[i][j] = 0
          summ = 0
          for s in range(-a,a+1):
              for t in range(-b,b+1):
                  summ += kernel[s,t] * image[i+s,j+t]
          result[i][j] = mul*summ
  return result

Step 6: Call the convolve function:

image = matrix_convolve2(img, kernel, 1,1,(1/9))
plt.imshow(img, cmap="gray")

The following will be the output:

Note that this is a very simple example of image convolution, and many other types of kernels can be used for different effects. Also, the above code assumes that the image has a single color channel and you can modify it accordingly for multi-channel images.

Leave a Reply

Leave a Reply

Scroll to Top