1. 二维高斯核函数
参考链接:https://blog.csdn.net/qq_16013649/article/details/78784791
g(x, y, sigma) = exp(-(x**2+y**2)/(2*sigma**2))
2. 卷积过程
高斯模糊:
G(xi, yi, sigma)= img*kernel
3. code
# 高斯核函数
import numpy as np
def gauss(kernel_size, sigma):
kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size//2
if sigma<=0:
sigma = ((kernel_size-1)*0.5-1)*0.3+0.8
s = sigma**2
sum_val = 0
for i in range(kernel_size):
for j in range(kernel_size):
x, y = i-center, j-center
kernel[i, j] = np.exp(-(x**2+y**2)/2*s)
sum_val += kernel[i, j]
kernel = kernel/sum_val
return kernel
gauss_kernel = gauss(3, 2)
import matplotlib.pyplot as plt
plt.imshow(gauss_kernel)
# cv2 filter
img = np.random.random([5,5])
import cv2
fl_cv = cv2.filter2D(img, -1, gauss_kernel)
plt.imshow(fl_cv)
# python
def conv_2d(kernel, img, mode='fill'):
if mode =='fill':
h = kernel.shape[0]//2
w = kernel.shape[1]//2
# opencv filter2d 默认采用reflect填充方式
# 前面测试了constant edge都不符合
img = np.pad(img, (h,w), 'reflect')
res_h = img.shape[0]-kernel.shape[0]+1
res_w = img.shape[1]-kernel.shape[1]+1
res = np.zeros((res_h, res_w))
dh = kernel.shape[0]
dw = kernel.shape[1]
for i in range(res_h):
for j in range(res_w):
res[i,j] = np.sum(img[i:i+dh, j:j+dw]*kernel)
return res
fl_py = conv_2d(gauss_kernel, img)
plt.imshow(fl_py)