% Fig. 4.32
% Wraparound error due to periodicity implied by DFT

clear all;
close all;
f = imread('Fig0432(a)(square_original).tif');
imshow(f,'initialmagnification','fit');

[M, N] = size(f);
sigma = 30;

% Implementation with DFT not centered
F = fft2(f);
H = lpfilter('gaussian', M, N, sigma);
G = F .* H;
g = real(ifft2(G));
imshow(g, [], 'initialmagnification','fit');

% Implementation with DFT centered
F = fft2(f);
Fc = fftshift(F);
Hc = lpfilter_center('gauss', M, N, sigma);
Gc = Fc .* Hc;
G2 = ifftshift(Gc);
g2 = real(ifft2(G2));
imshow(g2, [], 'initialmagnification','fit');

% Obtained the same result
isequal(g, g2)

% With zero padding
PQ = paddedsize(size(f));
Fp = fft2(f, PQ(1), PQ(2));
Hp = lpfilter('gaussian', PQ(1), PQ(2), 2*sigma);
Gp = Hp .* Fp;
gp = real(ifft2(Gp));
gpc = gp(1:size(f,1), 1:size(f,2));
figure; imshow(gp, [], 'initialmagnification','fit');
figure; imshow(gpc, [], 'initialmagnification','fit');