%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all
close all
clc
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Model Reduction of Dynamical Systems %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%% Summer Semester 2019 %%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Exercise 1, Problem 1 : Singular Value Decomposition, Image compression
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Step 1 : Load the image and save it as a matrix
A = (imread('cameraman.tif'));
imshow(A);
original_memory = ( size(A,1) * size(A,2) * 1 ) / 1000 ; % kB
% 1Byte for uint8
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Step 2 : Compute the SVD of the image matrix
% - Use the svd command in MATLAB
% For details on how to call it use the help command
% >> help svd
A = im2double(A); % Convert to double datatype to apply SVD
[???] = svd(??);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Step 3: Plot the relative singular values, see their decay
% - Use the plot() command in MATLAB to visualise the decay of the
% singular values
figure; plot(??,'-*'); % S contains the sigular values from Step 2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Step 4: Low rank approximation
% - Fix the rank of the approximation as r
% - Form Ared = Ur * Sr * Vr' , where
% Ur, Vr contain only the first r columns and Sr has the first r
% singular values
r = ??; % Low rank
Ared = ??; % Reconstruced image matrix based on the SVD
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Step 5: Display the compressed image
figure;
Ared = im2uint8(Ared);
imshow(Ared);
svd_memory = ( ?? ) / 1000 ; % kB
% 1Byte for uint8
% Play around with the value of r, to see for which rank does the
% reconstructed image looks similar to the original
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Bonus
% 1. Use the help function to understand the 'economic SVD'. Is it
% beneficial to use it for the given test image?
% 2. Load other images of your choice and see if you can sufficiently
% compress them. Understand the functions of imread and imshow commands.