Last active
July 31, 2021 22:51
-
-
Save NickCrews/585a2e77e11770efe43e47e486f896e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function filtered = gaussianFilter(img, sigma, varargin) | |
% GAUSSIANFILTER Simplified open-source version of IMGAUSSFILT | |
% The IMGAUSSFILT function is part of the Image Processing Toolbox, | |
% but if you don't want to install that, then use this | |
% instead. I haven't actually tested this to ensure it gives the same result. | |
% Inspired by https://stackoverflow.com/questions/13193248/how-to-make-a-gaussian-filter-in-matlab | |
% | |
% Hardcodes in the default arguments of IMGAUSSFILT | |
% (per https://www.mathworks.com/help/images/ref/imgaussfilt.html) | |
sigma = .5; | |
% In our case this is 3 | |
filterSize = 2*ceil(2*sigma)+1; | |
% In our case this is 1 | |
radius = (filterSize-1) / 2; | |
% Pad the image so the edges are filtered properly | |
padded = padarray(args.img, [radius radius], args.Padding, 'both') | |
kernel = gaussianKernel(radius, args.sigma); | |
filtered = conv2(padded, kernel, 'full') | |
% Extract the center region to undo our padding | |
[H, W] = size(img) | |
filtered = filtered(radius+1:H-radius, radius+1:W-radius) | |
end | |
function kernel = gaussianKernel(radius, sigma) | |
[x y] = meshgrid(-radius:radius, -radius:radius); | |
kernel = exp(-x.^2/(2*sigma^2)-y.^2/(2*sigma^2)); | |
% Finally, normalize the kernel so that sum of weights is 1 | |
kernel = kernel./sum(kernel(:)); | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment