% svd for image compression
clc;
k = 1;
choice = input('Choose image: 1 = Clown (200x320), 2 = Duerer (648x509) ');
if choice == 1
    load clown.mat;
else
    load durer.mat;
end
figure
colormap('gray');
image(X)
title('Original Image')
[m n] = size(X);
[u s v] = svd(X);
kmax = floor(min([m n])*100*(m+n+1)/(m*n));
fprintf('\n\n\n\n\n\n\n\n\n\nThe image has %d singular values\n', min(size(s)))
compression_ratio = input(sprintf('Input desired compression ratio (0=stop, %3d=max) ', kmax));
k = ceil(compression_ratio/100*m*n/(m+n+1));
while k ~= 0
    figure
    colormap('gray');
    if k+1 < min(size(s))
        relative_error = s(k+1,k+1)/s(1,1);
    else
        relative_error = 0;
    end
    image(u(:,1:k)*s(1:k,1:k)*v(:,1:k)');
    title(sprintf('Compression ratio %5.4f, relative error %5.4f, %d singular values used', ...
        compression_ratio/100, relative_error, k));
    compression_ratio = input(sprintf('Input desired compression ratio (0=stop, %3d=max) ', kmax));
    k = ceil(compression_ratio/100*m*n/(m+n+1));
end