Skip to content

Instantly share code, notes, and snippets.

@dantp-ai
Last active March 18, 2023 14:35
Show Gist options
  • Save dantp-ai/3514370d07c51a1bb80da32ba32928d6 to your computer and use it in GitHub Desktop.
Save dantp-ai/3514370d07c51a1bb80da32ba32928d6 to your computer and use it in GitHub Desktop.
2d convolution for stride of one with same output shape
import numpy as np
def convolve2D_same_output_shape(input_volume, kernel):
kernel = np.flipud(np.fliplr(kernel))
kernel_height = kernel.shape[0]
kernel_width = kernel.shape[1]
input_height = input_volume.shape[0]
input_width = input_volume.shape[1]
padding_height = int((kernel_height - 1) / 2)
padding_width = int((kernel_width - 1) / 2)
output_volume_height = (input_height - kernel_height + 2*padding_height) + 1
output_volume_width = (input_width - kernel_width + 2*padding_width) + 1
output = np.zeros((output_volume_height, output_volume_width))
assert output.shape == input_volume.shape, f"Expected output.shape == {input_volume.shape}. Got {output.shape}."
input_padded = np.zeros((
input_height + 2*padding_height,
input_width + 2*padding_width
))
input_padded[
int(padding_height):int(-1 * padding_height),
int(padding_width): int(-1*padding_width)
] = input_volume
for x in range(input_height):
for y in range(input_width):
output[x, y] = (kernel * input_padded[x: x + kernel_height, y:y + kernel_width]).sum()
return output
if __name__ == "__main__":
kernel = np.array(
[
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
]
)
image = np.random.randint(0, 255, size=(128, 128))
output = convolve2D_same_output_shape(image, kernel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment