% Illustrates the use of the SVD for image compression
clear all
close all
% Load your favorite image file
A = imread('greg','jpg');
[m n] = size(A(:,:,1));
% uncomment for image info
%imfinfo('greg.jpg')
X = double(A) + 1;
% Deal with all three color layers separately
[u1 s1 v1] = svd(X(:,:,1));
[u2 s2 v2] = svd(X(:,:,2));
[u3 s3 v3] = svd(X(:,:,3));
K = min(size(s3));
figure('Position', [50 10 50+n 10+m])
axis image
% Form sequence of low-rank approximations of the image
for k = 1:90 
    B1 = uint8(round(u1(:,1:k)*s1(1:k,1:k)*v1(:,1:k)') - 1);
    B2 = uint8(round(u2(:,1:k)*s2(1:k,1:k)*v2(:,1:k)') - 1);
    B3 = uint8(round(u3(:,1:k)*s3(1:k,1:k)*v3(:,1:k)') - 1);
    % put the layers back together
    B = cat(3,B1,B2,B3);
    image(B);
    set(gca,'XTick',[])
    set(gca,'YTick',[])
    % get movie frame
	M(k) = getframe;
end
% make MATLAB movie
movie(M,1,6);
% uncomment to create an AVI movie
%movie2avi(M,'greg.avi','fps',6)
