defgaussian_kernel(x, y, k, sigma): return k * np.exp(-(x**2+y**2)/(2*sigma**2))
kernel = np.zeros((11, 11)) for i inrange(kernel.shape[0]): for j inrange(kernel.shape[1]): x = np.abs(i-5) y = np.abs(j-5) kernel[i, j] = round(gaussian_kernel(x, y, 1, 1), 3) print(kernel)
import matplotlib.pyplot as plt import numpy as np import cv2 as cv
defconv2d_kernel(matrix, kernel): n = len(kernel) ans = 0 for i inrange(n): for j inrange(n): ans += matrix[i,j]*float(kernel[i,j]) return ans
defimage_conv2d(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 matrix 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
defgaussian_kernel_create(size, k, sigma): kernel = np.zeros((size, size)) center = (size-1)/2 for i inrange(kernel.shape[0]): for j inrange(kernel.shape[1]): x = np.abs(i-center) y = np.abs(j-center) kernel[i, j] = k * np.exp(-(x**2+y**2)/(2*sigma**2)) return kernel/np.sum(kernel)