% SVD data compression example

clear all

nasacolor = imread('TarantulaNebula.jpg');  % 630x567 image
% image(nasacolor)
% title('Color NASA photo');
nasa = sum(nasacolor,3,'double');         % sum up red+green+blue
m = max(max(nasa));                       % find the max value
nasa = nasa*255/m;                        % make this be bright white
colormap(gray(256));

[U S V] = svd(nasa);                      % SVD of grayscale image

% nasa25 = U(:,1:25)*S(1:25,1:25)*V(:,1:25)';      % 1st 25 singular values
nasa50 = U(:,1:50)*S(1:50,1:50)*V(:,1:50)';      % 1st 50 singular values
nasa100 = U(:,1:100)*S(1:100,1:100)*V(:,1:100)'; % 1st 100 singular values
nasa150 = U(:,1:150)*S(1:150,1:150)*V(:,1:150)'; % 1st 150 singular values

figure(1)
semilogy(diag(S))                         % plot singular values with semilog scale
ylabel log(\sigma)
title('Singular values')

figure(2)
subplot(2,2,1)
image(nasa)
title('Grayscale NASA photo')
subplot(2,2,2)
image(nasa50)
title('Grayscale NASA photo with s=50')
subplot(2,2,3)
image(nasa150)
title('Grayscale NASA photo with s=150')
subplot(2,2,4)
image(nasa100)
title('Grayscale NASA photo with s=100')





