%% dft2demo3
% low pass and high pass "brick wall" filtering of an image

% S. Allen Bbroughton

%% get image
%load clown
load chess
%load earth
%load mandrill

%% get 2D DFT and shifted 2D DFT of image
fX = fft2(X); 
sfX = fftshift(fX);

[m,n] = size(fX);
hm = floor(m/2);
hn = floor(n/2);

%% create low pass "brick wall" mask
lM = ones(size(fX));
% stop high frequencies
stop=20;  
lM(1:stop,1:stop)=0;
lM((m-stop):m,1:stop)=0;
lM(1:stop,(n-stop):n)=0;
lM((m-stop):m,(n-stop):n)=0;

%% create high pass "brick wall" mask
% mask is used with shifted DFT 
hM = ones(size(fX));
% stop low frequencies
hM((hm-stop):(hm+stop),(hn-stop):(hn+stop)) = 0;  

%% create filtered images  
mlsfX = lM.*sfX;
mhsfX = hM.*sfX;
mlX = real(ifft2(fftshift(mlsfX)));
mhX = real(ifft2(fftshift(mhsfX)));

%% display results - original and DFT 
figure(1)
subplot(2,1,1)
imagesc(X), colormap(gray), axis equal, axis tight 
title('original')
subplot(2,1,2)
imagesc(log(1+abs(sfX))), colormap(gray), axis equal, axis tight 
title('shifted log(1+|dft|)')

%% display results - masks and DFTs
figure(2)
subplot(2,2,1)
imagesc(lM), colormap(gray), axis equal, axis tight 
title('shifted low pass mask')
subplot(2,2,2)
imagesc(hM), colormap(gray), axis equal, axis tight 
title('shifted high pass mask')
subplot(2,2,3)
imagesc(log(eps+abs(mlsfX))), colormap(gray), axis equal, axis tight 
title('shifted low pass DFT')
subplot(2,2,4)
imagesc(log(eps+abs(mhsfX))), colormap(gray), axis equal, axis tight 
title('shifted high pass DFT')


%% display results - reconstucted images
figure(3)
subplot(3,2,1)
imagesc(X), colormap(gray), axis equal, axis tight 
title('original')
subplot(3,2,2)
imagesc(log(eps+abs(sfX))), colormap(gray), axis equal, axis tight 
title('shifted log(1+|dft|)')

subplot(3,2,3)
imagesc(log(eps+abs(mlsfX))), colormap(gray), axis equal, axis tight 
title('shifted low pass DFT')
subplot(3,2,4)
imagesc(log(eps+abs(mhsfX))), colormap(gray), axis equal, axis tight 
title('shifted high pass DFT')
subplot(3,2,5)
imagesc(mlX), colormap(gray), axis equal, axis tight 
title('low pass reconstructed image')
subplot(3,2,6)
imagesc(mhX), colormap(gray), axis equal, axis tight 
title('high pass reconstructed image')
