% parameter definition
% number of grey levels
% compression percentage  
cp = 50;


% get image from MATALAB image collection and show image
load('clown');
figure(1);
imshow(real(X),[]);
title('Original')
 
% calculate and show fft 
Z=fft2(X);
maz =  max(max(abs(Z)));
figure(2);
imshow(log(1+abs(fftshift(Z))),[]);
title('shifted log(1+|dft|)');
drawnow


% compress and reconstruct
% clear figure
sZ = sort(abs(Z(:)));
ci = round((1-cp/100)*length(sZ));
cutlev = sZ(ci);  
J = find(abs(Z) < cutlev);
cZ = Z;
cZ(J) = zeros(size(J));
cM = ones(size(Z));
cM(J) = zeros(size(J));

% reconstruct
cX = real(ifft2(cZ));
figure(3)
imshow(cX,[]);
title('Reconstruction');
drawnow;

figure(4)
imshow(fftshift(cM),[]);
title('Threshold Map');
drawnow;



% show compression
PercentRetainedCoefficients =100*(matsize(X)-matsize(J))/matsize(X)

% show distortion
DistortionPercent = mu(cX-X,cX-X)/mu(X,X)

% show cut off level (logaritmmic)
  logcutlev =-log10(cutlev/maz);
