我们以一个二维矩阵表示二元高斯滤波器,显然此二维矩阵的具体形式仅于其形状(shape)有关:

def gauss_filter(kernel_shape):

为实现二维高斯滤波器,需要首先定义二元高斯函数:

f(x,y)=12πσ2exp(x2+y22σ2)

def gauss(x, y, sigma=3.):
    Z = 2*np.pi*sigma**2
    return 1/Z*np.exp(-(x**2+y**2)/2/sigma**2)

则可进一步给出高斯滤波的实现:

def gauss_filters(kernel_shape):
    # kernel_shape 是一个四元元组,各个元素分别表示:滤波器的宽,滤波器的高,滤波器的个数,1
    kernels = np.zeros(kernel_shape, np.float32)
    mid = np.floor(kernel_shape[0]/2)
    for kernel_idx in range(kernel_shape[2]):
        for i in range(kernel_shape[0]):
            for j in range(kernel_shape[1]):
                kernels[i, j, kernel_idx, 0] = gauss(i-mid, j-mid)
    return kernels
posted on 2017-03-24 20:46  未雨愁眸  阅读(2116)  评论(0编辑  收藏  举报