clear all; close all;

% read in MATLAB demo text image
image = imread('text.png');
[M N] = size(image)


% Show Image

figure(1);
imshow(image);
title('Original Image');

% compute fft and display its spectra

F=fft2(double(image));
figure(2);
imagesc((abs(fftshift(F))/(M*N)));
colormap(jet);
axis off;
title('FFT Image Spectra');

%compute Ideal Low Pass Filter

u0 = 50; % set cut off frequency


u=0:(M-1);
v=0:(N-1);
idx=find(u>M/2);
u(idx)=u(idx)-M;
idy=find(v>N/2);
v(idy)=v(idy)-N;
[V,U]=meshgrid(v,u);
D=sqrt(U.^2+V.^2);
H=double(D<=u0);

% display
figure(3);
imshow(fftshift(H));
title('Ideal Low Pass Filter');

% Apply filter and do inverse FFT
G=H.*F;
g=real(ifft2(double(G)));

% Show Result

figure(4);
imshow(g);
title('Low Pass Filtered Image');



%%% Demo now to show noisy filtering properties of the low pass filter

% now addnoise to the image

image_noisy = imnoise(double(image),'gaussian');

% show noisy im
figure(5)
imshow(image_noisy)
title('Image with Added Noise');
figure(5)

%%%% compute FFT of noisy image

F = fft2(double(image_noisy));



% Filter using low pass filter H as above

G_lowpass=H.*F;

% convert back to image spce with iFFT

g_lowpass = real(ifft2(double(G_lowpass)));

figure(6)
imshow(g_lowpass);
title('Low Pass Filtered Noisy Image');
figure(6)





%%%%% Now set Higher cut off frequency and repeat all above

%compute Ideal Low Pass Filter

u0 = 80; % set cut off frequency


u=0:(M-1);
v=0:(N-1);
idx=find(u>M/2);
u(idx)=u(idx)-M;
idy=find(v>N/2);
v(idy)=v(idy)-N;
[V,U]=meshgrid(v,u);
D=sqrt(U.^2+V.^2);
H=double(D<=u0);

% display
figure(7);
imshow(fftshift(H));
title('High Cut-off Frequency Low Pass Filter');

% Apply filter and do inverse FFT


% Filter using low pass filter H as above

G_lowpass=H.*F;

% convert back to image spce with iFFT 

g_lowpass = real(ifft2(double(G_lowpass)));

figure(8)
imshow(g_lowpass);
title('High Cut-off Frequency Low Pass Filtered Image');
figure(8)