% Image conpression using singular value decomposition.
% K. Ming Leung, 04/27/03

clear all; 
flowersTiff = imread('flowers.tif');    % read in color image
%imshow(flowersTiff); pause;
flowersGray = rgb2gray(flowersTiff);    % convert to grayscale
imshow(flowersGray); pause;        % show grayscale image
flowers = double(flowersGray);          % convert to numbers
%subplot(2,1,1);
image(flowers); %axis('equal');
pause;
title('Original image');
[U, S, V] = svd(flowers);               % svd decomposition
dS = diag(S),                           % singular values

M = zeros(size(flowers));
for k= 1:min(size(S))
    M = M+S(k,k)*U(:,k)*V(:,k)';    % compose image incrementally
 %   subplot(2,1,2);
    image(M); %axis('equal');                  % display image
    title(['First ',num2str(k),' singular values']);
    shg; pause(0.01);
end
% If we keep only the first 50 singular values and vectors,
% the compressed image has only 2% of the original size
