def convolve2d(image, kernel):
# This function which takes an image and a kernel
# and returns the convolution of them
# Args:
# image: a numpy array of size [image_height, image_width].
# kernel: a numpy array of size [kernel_height, kernel_width].
# Returns:
# a numpy array of size [image_height, image_width] (convolution output).
kernel = np.flipud(np.fliplr(kernel)) # Flip the kernel
output = np.zeros_like(image) # convolution output
# Add zero padding to the input image
image_padded = np.zeros((image.shape[0] + 2, image.shape[1] + 2))
image_padded[1:-1, 1:-1] = image
for x in range(image.shape[1]): # Loop over every pixel of the image
for y in range(image.shape[0]):
# element-wise multiplication of the kernel and the image
output[y, x] = (kernel * image_padded[y:y + 3, x:x + 3]).sum()
return output
# Convolve a sharpen kernel with an image
评论列表
文章目录