Skip to content

Instantly share code, notes, and snippets.

@kwcooper
Last active March 5, 2019 06:21
Show Gist options
  • Save kwcooper/57ff42a5ccc1106a7a7318caec8429c6 to your computer and use it in GitHub Desktop.
Save kwcooper/57ff42a5ccc1106a7a7318caec8429c6 to your computer and use it in GitHub Desktop.
Convolve a N-D kernel with a NxN matrix, such as an image
import numpy as np
import matplotlib.image as img
import matplotlib.pyplot as plt
image = img.imread('school.png') # Grab the image
def toGreyscale(image):
# convert the RGB to Greyscale
return np.dot(image[...,:3], [0.114, 0.299, 0.587])
image = toGreyscale(image)
if 0:
plt.imshow(image)
plt.show()
kernel = np.array([[-1,-1,1],[-1,1,-1],[1,-1,-1]]) # kernel
img = image
# Apply the kernel
# Inspired from: https://stackoverflow.com/questions/43373521/how-to-do-convolution-matrix-operation-in-numpy
x,y = kernel.shape
x_dif, y_dif = np.subtract(img.shape,kernel.shape)
lst = []
for x_i in range(1+x_dif):
for y_i in range(1+y_dif):
lst.append(np.sum(np.multiply(img[x_i:x+x_i,y_i:y+y_i],kernel)))
result_shape = np.add((x_dif,y_dif),(1,1))
result = np.reshape(lst, result_shape)
if 1:
plt.imshow(result)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment