# define kernel calculate defsum_kernel(matrix, kernel): n = len(kernel) sum = 0 for i inrange(n): for j inrange(n): sum += matrix[i,j]*kernel[i,j] returnsum
# define correlation calculate defimage_correlation(im, kernel): n = len(kernel) # padding size: 2*(kernelsize - 1) im_padding = np.zeros((im.shape[0]+2*(n-1), im.shape[1]+2*(n-1))) # im data copy to padding im im_padding[(n-1):(n+im.shape[0]-1), (n-1):(n+im.shape[1]-1)] = im im_conv = np.zeros((im_padding.shape[0]-n+1, im_padding.shape[1]-n+1)) for i inrange(im_padding.shape[0]-n+1): for j inrange(im_padding.shape[1]-n+1): neighbor = im_padding[i:i+n, j:j+n] im_conv[i, j] = conv2d_kernel(neighbor, kernel) pos = int((n-1)/2) im_new = im_conv[pos:(pos+im.shape[0]), pos:(pos+im.shape[1])] return im_new