Skip to content

Instantly share code, notes, and snippets.

@lucaspar
Last active October 4, 2019 20:33
Show Gist options
  • Save lucaspar/cb67548b802a19328113c205c0ab7391 to your computer and use it in GitHub Desktop.
Save lucaspar/cb67548b802a19328113c205c0ab7391 to your computer and use it in GitHub Desktop.
[ SCR ] Correlation and Convolution Script
#!/usr/bin/env python
# Implementation of correlation and convolution kernels with no dependencies (e.g. numpy)
# Translated from the mathematical expressions with a focus on readability (not very "pythonic")
# ----------
# print image matrix
def printimg(img, title=''):
print(title + ':')
for x in img:
for y in x:
print(y, end='\t')
print('')
print('')
def correlation(img, kernel):
return convolution(img, kernel, conv=False)
def convolution(img, kernel, conv=True):
# more readable measurements
kernel_rows = len(kernel)
kernel_cols = len(kernel[0])
padding_rows = int(kernel_rows / 2)
padding_cols = int(kernel_cols / 2)
img_rows = len(img)
img_cols = len(img[0])
# pad image with zeros
img_padding_rows = img_rows + padding_rows * 2
img_padding_cols = img_cols + padding_cols * 2
cnv_img = [[0] * img_cols for sliding_x in range(img_rows)]
padded_image = [[0] * img_padding_cols for sliding_x in range(img_padding_rows)]
for image_x in range(padding_rows, img_rows + padding_rows):
for image_y in range(padding_cols, img_cols + padding_cols):
padded_image[image_x][image_y] = img[image_x - padding_rows][image_y - padding_cols]
# iterate through image (x,y)
for image_x in range(0, img_rows):
for image_y in range(0, img_cols):
new_pixel = 0
# iterate through kernel (s,t) to calculate new pixel value
for kernel_x in range(0, kernel_rows):
for kernel_y in range(0, kernel_cols):
# indices over the padded image
sliding_x = 0
sliding_y = 0
# if doing convolution, we need to rotate the kernel in 180 deg
if conv:
# this algebra emulates this rotation
sliding_x = image_x - kernel_x + (kernel_rows - 1)
sliding_y = image_y - kernel_y + (kernel_cols - 1)
else:
sliding_x = image_x + kernel_x
sliding_y = image_y + kernel_y
new_pixel += kernel[kernel_x][kernel_y] * \
padded_image[sliding_x][sliding_y]
# set new pixel value
cnv_img[image_x][image_y] = new_pixel
return cnv_img
if __name__ == "__main__":
img = [
[4, 6, 9, 6, 4, 6],
[9, 6, 4, 9, 9, 9],
[9, 6, 2, 2, 9, 2],
[10, 10, 10, 10, 10, 10],
]
kernels = {
'Isotropic': [
[1, 1, 1],
[1, 1, 1],
[1, 1, 1],
],
'Anisotropic': [
[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1],
],
'KA': [
[1, 1, 1],
[0, 0, 0],
[1, 1, 1],
],
'KB': [
[0, -1, 0],
[-1, 5, -1],
[0, -1, 0],
],
}
printimg(img, 'Original')
for k_name, k in kernels.items():
img_conv = convolution(img, k)
img_corr = correlation(img, k)
print('\t--------\n')
printimg(k, k_name + ' Kernel')
printimg(img_conv, 'Convolution for ' + k_name)
printimg(img_corr, 'Correlation for ' + k_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment