高斯滤波器核不同于Matlab高斯滤波器核

时间:2017-02-04 06:07:04

标签: matlab filter computer-vision gaussian

我在Matlab中创建了一个高斯滤波器。我创建了以下用于创建内核的代码。

function kernel = gaussian_filter(sigma)
    kernel_width = 3 * sigma - 1;
    [x, y] = meshgrid(-kernel_width/2:kernel_width/2, -kernel_width/2:kernel_width/2);
    normalized_constant = 1/(2 * pi * sigma * sigma);
    kernel = normalized_constant * exp(-(x.^2 + y.^2)/ (2 * sigma * sigma));
    K = mat2gray(kernel);
    imshow(K);
    title('Gaussian Kernel');
 end

我的输出是:

gaussian_filter(3)

ans =

  Columns 1 through 7

    0.0030    0.0044    0.0058    0.0069    0.0073    0.0069    0.0058
    0.0044    0.0065    0.0086    0.0101    0.0107    0.0101    0.0086
    0.0058    0.0086    0.0113    0.0134    0.0142    0.0134    0.0113
    0.0069    0.0101    0.0134    0.0158    0.0167    0.0158    0.0134
    0.0073    0.0107    0.0142    0.0167    0.0177    0.0167    0.0142
    0.0069    0.0101    0.0134    0.0158    0.0167    0.0158    0.0134
    0.0058    0.0086    0.0113    0.0134    0.0142    0.0134    0.0113
    0.0044    0.0065    0.0086    0.0101    0.0107    0.0101    0.0086
    0.0030    0.0044    0.0058    0.0069    0.0073    0.0069    0.0058

  Columns 8 through 9

    0.0044    0.0030
    0.0065    0.0044
    0.0086    0.0058
    0.0101    0.0069
    0.0107    0.0073
    0.0101    0.0069
    0.0086    0.0058
    0.0065    0.0044
    0.0044    0.0030

但是当我运行Matlab高斯滤波器时,结果略微偏离输出。

h = fspecial('gaussian', 9, 3)

h =

  Columns 1 through 7

    0.0040    0.0059    0.0077    0.0091    0.0096    0.0091    0.0077
    0.0059    0.0086    0.0114    0.0135    0.0142    0.0135    0.0114
    0.0077    0.0114    0.0150    0.0178    0.0188    0.0178    0.0150
    0.0091    0.0135    0.0178    0.0210    0.0222    0.0210    0.0178
    0.0096    0.0142    0.0188    0.0222    0.0235    0.0222    0.0188
    0.0091    0.0135    0.0178    0.0210    0.0222    0.0210    0.0178
    0.0077    0.0114    0.0150    0.0178    0.0188    0.0178    0.0150
    0.0059    0.0086    0.0114    0.0135    0.0142    0.0135    0.0114
    0.0040    0.0059    0.0077    0.0091    0.0096    0.0091    0.0077

  Columns 8 through 9

    0.0059    0.0040
    0.0086    0.0059
    0.0114    0.0077
    0.0135    0.0091
    0.0142    0.0096
    0.0135    0.0091
    0.0114    0.0077
    0.0086    0.0059
    0.0059    0.0040

我没有错过算法中的任何步骤。我想弄清楚为什么我们的结果不匹配。

1 个答案:

答案 0 :(得分:0)

我忘了规范化内核:

kernel = kernel/(sum(kernel(:)));

https://www.mathworks.com/help/images/ref/fspecial.html