% Image conpression using singular value decomposition.
% A low-rank approximation is used to illustrate image compression.
% This examplle is used for illustrational purposes.
% Better image compression techniques are available.
% K. Ming Leung, 04/27/03, version 2: 11/19/04

clear all; bigscreen;
% load image data file:
% file contains indexed image 'X' and colormap 'map'
load durer.mat;
% need to convert to intensities (between 0 & 1).
T = map(X,1); X1 = reshape(T,size(X));

subplot(1,2,1);
image(255*X1); 
title('Original image');
colormap(gray(256)); axis image; axis off;

[U, S, V] = svd(X1);              % svd decomposition
dS = diag(S),                     % singular values

subplot(1,2,2);
% compose image incrementally: 
% starting first with 1 singular value and
% incrementally adding 50 more singular values
for kMax = 1:50:min(size(S));
    k = 1:kMax;
    M = U(:,k)*S(k,k)*V(:,k)';    
    image(255*M);                 % display image
    axis image; axis off;
    title(['First ',num2str(kMax),' singular values']);
    shg; pause(0.5);
end
% If we keep only the first 50 singular values and vectors,
% the compressed image has only 2% of the original size

% plot(log10(dS));  % plot the singular values on a log scale