Regarding the Gaussian filtering function imgaussfilt and the filter function fspecial.

6 次查看(过去 30 天)
I want to perform Gaussian filtering on an image, but the size of the filter will continue to increase as the program progresses, while the image is getting smaller and smaller. This inevitably leads to a situation where the image size is smaller than the filter size. So, I used these two functions to give a simple example to see if they can work properly.
Now that the execution has ended, I find that the results of the two functions are not the same. I would like to ask if these two functions have different ways of handling the issue of exceeding the matrix boundary? And which function would be more recommended for Gaussian filtering of images in image processing?
a = [1 2 1; 2 1 2; 1 2 1];
% imgaussfilt函数滤波对于边界像素的处理
b = imgaussfilt(a, 1.6);
disp(b);
1.3271 1.3532 1.3271 1.3532 1.3754 1.3532 1.3271 1.3532 1.3271
% 使用same约束矩阵大小,对边界像素的处理
sigma = 1.6;
size = 9;
gaussian_kernel = fspecial('gaussian', size, sigma);
% disp(gaussian_kernel);
c = conv2(a, gaussian_kernel, 'same');
disp(c);
0.4765 0.5545 0.4765 0.5545 0.6450 0.5545 0.4765 0.5545 0.4765
  4 个评论
DGM
DGM 2024-7-24
编辑:DGM 2024-7-24
@Umar is correct. The big advantage to imgaussfilt() is that it handles boundary regions sensibly and appropriately scales the kernel support by default.
FWIW, this is roughly how one would configure a fspecial()/imfilter() process to match the behavior of imgaussfilt():
% parameters
a = [1 2 1; 2 1 2; 1 2 1];
sigma = 1.6;
% imgaussfilt函数滤波对于边界像素的处理
b = imgaussfilt(a, sigma); % it's concise and convenient
% 使用same约束矩阵大小,对边界像素的处理
fsize = 2*ceil(2*sigma) + 1; % yes, that's 9 in this case.
gaussian_kernel = fspecial('gaussian', fsize, sigma); % filter with appropriate support
c = imfilter(a, gaussian_kernel,'replicate'); % specify the padding behavior
% just some negligible rounding error
immse(b,c)
ans = 2.1913e-32
Replicating the behavior with conv2() is more complicated, since the padding and cropping need to be done explicitly.

请先登录,再进行评论。

回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by