% image compression with SVD
% read the image
a=imread('p8040001.jpg');
% a is a 3D array, RGB, uint8 (0-255)
size(a)
% let us look at the parts
figure(1), image(a);
figure(2), image(a(:,:,1));
figure(3), image(a(:,:,2));
figure(4), image(a(:,:,3));
% compute three SVDs
[ur,sr,vr]=svd(double(a(:,:,1)));
[ug,sg,vg]=svd(double(a(:,:,2)));
[ub,sb,vb]=svd(double(a(:,:,3)));
% let us look at singular values
% x-axis
x=1:min(size(a(:,:,1)));
figure(5), plot(x,diag(sr),x,diag(sg),x,diag(sb));

% let us try out different compressions
kk=1;
while kk~=0
    k=input(' k = (number of significant sinfgular values) ');
    b(:,:,1)=ur(:,1:k)*sr(1:k,1:k)*vr(:,1:k)';
    b(:,:,2)=ug(:,1:k)*sg(1:k,1:k)*vg(:,1:k)';
    b(:,:,3)=ub(:,1:k)*sb(1:k,1:k)*vb(:,1:k)';
    figure(6), image(uint8(b))
    kk=input(' continue 0/1 ');
end
