-
Notifications
You must be signed in to change notification settings - Fork 0
/
imfilter2d.m
37 lines (28 loc) · 860 Bytes
/
imfilter2d.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function F = imfilter2d(I, K)
% imfilter3d: fast filtering for 2D images
% usage:
% F = imfilter3d(I,K)
% parameters:
% I 2D image volume (can be any size)
% K 2D kernel (dimensions must be odd!)
% result:
% F Convolution of I with K, computed using the fast
% Fourier transform
if ~ all(size(K) - 2 * floor(size(K)/2))
error('The size of the kernel must be odd!');
end
% Generate the size of the fft that we will be computing
szf = size(I) + size(K) - 1;
% Compute FFT of the image
fft_I = fftn(I, szf);
% Compute FFT of the kernel
fft_K = fftn(K, szf);
% Multiply
fft_I = fft_I .* fft_K;
% Save memory
clear('fft_K');
% Compute inverse
F = real(ifftn(fft_I));
% Take the central part
shift = floor(size(K)/2);
F = F(shift(1)+1:end-shift(1),shift(2)+1:end-shift(2));