Created
November 26, 2020 15:19
-
-
Save siddydutta/3698c1eac0e72112eaad4c47b4909cb7 to your computer and use it in GitHub Desktop.
A function that applies the convolution operation to a given image with a given kernel with or without padding.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import cv2 | |
import numpy as np | |
def convulate(image, kernel, padding=False, paddingType=cv2.BORDER_CONSTANT): | |
''' | |
@param image: 2D array of type <numpy.ndarray> for given image. | |
@param kernel: 2D array of type <numpy.ndarray> for given kernel. | |
@param padding: Type <bool> to indicate if padding required. | |
@param borderType: Type of padding from cv2 border types. | |
returns: Image after convolution operation of kernel | |
(Upto 2 Decimal Places) | |
''' | |
image = cv2.copyMakeBorder(image, 1, 1, 1, 1, paddingType) | |
result = cv2.filter2D(image, -1, kernel, borderType=cv2.BORDER_CONSTANT) | |
if padding: | |
return np.round(result[1:-1, 1:-1], 2) | |
else: | |
return np.round(result[2:-2, 2:-2], 2) | |
# Example Code | |
if __name__ == '__main__': | |
# Simple 2D matrix | |
image = [[17, 14, 13, 9, 17], | |
[21, 64, 62, 41, 19], | |
[42, 54, 61, 52, 40], | |
[41, 30, 31, 34, 38], | |
[20, 24, 40, 58, 55]] | |
image = np.array(image).astype('float64') | |
# Simple averaging kernel for blurring | |
kernel = [[1, 1, 1], | |
[1, 1, 1], | |
[1, 1, 1]] | |
kernel = np.array(kernel) | |
kernel = kernel/9 | |
# Convolution with no padding | |
print('No Padding') | |
print(convulate(image, kernel)) | |
# Convultion after symmetric padding | |
print('\nWith Padding') | |
print(convulate(image, kernel, True, cv2.BORDER_REFLECT)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment