Skip to content

Instantly share code, notes, and snippets.

@DennisPing
Last active May 6, 2021 01:18
Show Gist options
  • Save DennisPing/b59cd0e57818c95a968a601a444771f2 to your computer and use it in GitHub Desktop.
Save DennisPing/b59cd0e57818c95a968a601a444771f2 to your computer and use it in GitHub Desktop.
def convolution(self, matrix, kernel):
# Matrix is a 3d array with shape of [width, height, channel]
# Kernel is a 2d array with shape of [width, height]
width = matrix.shape[0]
height = matrix.shape[1]
output_matrix = np.zeros((width, height, 3))
# a simple helper method to sum up the values of the kernel
kernel_sum = self._kernelSum(kernel)
offset = len(kernel) // 2
for row in range(width):
for col in range(height):
for ch in range(3):
# the convolution value for a kernel window on the image
accumulator = 0.0
for j in range(len(kernel)):
for k in range(len(kernel)):
xcoord = row + j - offset
ycoord = col + k - offset
value = 0
# if (x,y) coordinate is out of bounds, pick the kernel center instead
if xcoord < 0 or xcoord >= width or ycoord < 0 or ycoord >= height:
value = matrix[row][col][ch]
else:
value = matrix[xcoord][ycoord][ch]
accumulator += (value * kernel[j][k])
# An online guide told me that you should clamp convoluted values to a range of [0,255] and also
# normalize them by dividing by the kernel_sum.
average = self._clamp(accumulator) / kernel_sum
output_matrix[row][col][ch] = int(average)
return output_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment