Skip to content

Instantly share code, notes, and snippets.

@cychitivav
Created September 1, 2022 19:39
Show Gist options
  • Save cychitivav/8cd9cb9192540f1c69f1a32876fe2c8f to your computer and use it in GitHub Desktop.
Save cychitivav/8cd9cb9192540f1c69f1a32876fe2c8f to your computer and use it in GitHub Desktop.
Function to find the convolution of an image with a mask of size nxn (n odd)
import cv2
import numpy as np
import matplotlib.pyplot as plt
def convolution2D(Img, Mask):
inv_mask = Mask[::-1,::-1]
dim = Mask.shape
img_conv = np.zeros(Img.shape)
for i in range(1,Img.shape[0]-1):
for j in range(1,Img.shape[1]-1):
img_conv[i, j] = np.abs(np.sum((Img[i-dim[0]//2:i+dim[0]//2+1, j-dim[0]//2:j+dim[0]//2+1] * inv_mask)))
return img_conv
@cychitivav
Copy link
Author

cychitivav commented Sep 19, 2022

This code represents the following operation

$$ f(x,y) =g(x,y)*h(x,y)= \sum_{i=1}^{M} \sum_{j=1}^{N} h(i,j)\cdot g(x-i,y-j) $$

Where:

  • $g(x,y)$ is the image
  • $h(x,y)$ is the kernel with size $M\times N$

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment