Skip to content

Instantly share code, notes, and snippets.

@tonyfast
Created June 25, 2014 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyfast/02b468a54cc5d8ca92fd to your computer and use it in GitHub Desktop.
Save tonyfast/02b468a54cc5d8ca92fd to your computer and use it in GitHub Desktop.
Matlab N-D Simple Filtering Using Fourier Transforms
function convolved = simple_conv( Image, Filter )
% A simple Fourier Convolution Function written in matlab.
% It works on N-D arrays and N-D filters.
%%
% Dimensionality of input image
nDim = ndims( Image );
%% Make a filter the same size as the image
LargeFilter = zeros( size( Image ) );
expressionstart = 'LargeFilter(';
iterexp = '1:size(Filter,%i)';
for ii = 1 : nDim
expressionstart = ...
horzcat( expressionstart, ...
sprintf( iterexp, ii ) );
if ii ~= nDim
expressionstart = ...
horzcat( expressionstart, ...
',' );
end
end
expressionstart = ...
horzcat( expressionstart, ...
') = Filter;' );
eval( expressionstart );
LargeFilter(:) = circshift( LargeFilter, -1*floor(size( Filter )./2) );
%% FFT convolution
% Forward Fourier Transform
convolved = fftn( Image );
% Multiply in the Fourier Space
convolved(:) = convolved.* conj(fftn( LargeFilter ));
% Inverse Fourier Transform
convolved(:) = ifftn( convolved );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment