%% Image Data Compression
% Load a file that contains depth measurements of a mold used to mint a United States penny. The data, taken at the National Institute of Standards and Technology, are sampled on a 128-by-128 grid. Display the data.

load penny

surf(P)
view(2)
colormap copper
shading interp
axis ij square off

%
% Compute the discrete cosine transform of the image data. Operate first along the rows and then along the columns.

Q = dct(P,[],1);
R = dct(Q,[],2);

%
% Find what percentage of DCT coefficients contain 99.98% of the energy in the image.

X = R(:);

[~,ind] = sort(abs(R(:)),'descend');
coeffs = 1;
while norm(X(ind(1:coeffs)))/norm(X) < 0.9998
   coeffs = coeffs + 1;
end
fprintf('%3.1f%% of the coefficients are sufficient\n',coeffs/numel(R)*100)

%
% Reconstruct the image using only the necessary coefficients.

R(abs(R) < abs(X(ind(coeffs)))) = 0;

S = idct(R,[],2);
T = idct(S,[],1);

%
% Display the reconstructed image.

surf(T)
view(2)
shading interp
axis ij square off

% Copyright 2012 The MathWorks, Inc.