%% Exercise 4, Image compression with svd
% HA 3.12.2018
close all;format compact;clear
img=imread('Seurasaari.jpg');
[M,N]=size(img)
%%
% imshow(img)
%% Convert to double
dimg=im2double(img);  % dimg is 3-dim array. 
size(dimg)
%%
imshow(dimg)
title('Original image');
%% Take svd of all 3 layers.
% Here semicolons are important, extremely!
tic
[u1,s1,v1]=svd(dimg(:,:,1));   % Layer 1, Red
[u2,s2,v2]=svd(dimg(:,:,2));   % Layer 2, Green
[u3,s3,v3]=svd(dimg(:,:,3));   % Layer 3, Blue
T=toc
%{
T =
   52.6644
%}
%% Let's have a look at the singular values:
D1=diag(s1);D2=diag(s2);D3=diag(s3);
[D1(1:20) D2(1:20) D3(1:20)]
[D1(1:20) D2(1:20) D3(1:20)]./[D1(1) D2(1) D3(1)]  %This works in new versions
% The first few seem to dominate.
%% Show images in separate windows
close all
for k=[1:5 10 100];
   M1=u1(:,1:k)*s1(1:k,1:k)*v1(:,1:k)';
   M2=u2(:,1:k)*s2(1:k,1:k)*v2(:,1:k)';
   M3=u3(:,1:k)*s3(1:k,1:k)*v3(:,1:k)';
   kfig=k;
   if k==10
       kfig=6;
   elseif k==100
       kfig=7;
   end        
   figure(kfig)
   imshow(cat(3,M1,M2,M3))
   title(['First ',num2str(k),' singular values']) 
end   
%% Use "matrix of windows" with subplot
close all
for k=1:8
   M1=u1(:,1:k)*s1(1:k,1:k)*v1(:,1:k)';
   M2=u2(:,1:k)*s2(1:k,1:k)*v2(:,1:k)';
   M3=u3(:,1:k)*s3(1:k,1:k)*v3(:,1:k)';
   subplot(4,2,k)
   imshow(cat(3,M1,M2,M3))
   title(['First ',num2str(k),' singular values']) 
end 
%% Is this useful?
%
% Example: If you send a camera to Jupiter, you can do the svd's 
% there and only need to send back to earth the n most significant 
% singular values along with the corresponding columns of U and V.
% The value of n is of course "picture-dependent".

