clear all; close all; clc;
I = imread('face2.jpg');
I = imresize(I,[512 512], 'bicubic');
I = double(rgb2gray(I));


%%Part 1
subplot(3,3,1)
colormap(gray)
imagesc(I);
title('Q2-1')
axis off
K = [1; 5; 10; 20; 25; 30; 35; 40];
errors = zeros(size(K));
gain = zeros(size(K));
J = I';
for i=1:length(K)
    subplot(3,3,i+1)
    [X,Uk,Vk,Pk,errors(i),gain(i)] = PCA(J,K(i),1,0,0);
    imagesc(X');
    axis off
end
figure()
[AX,~,~] = plotyy(K,errors,K,gain);
title('Q2-1')
xlabel('K')
set(get(AX(1),'Ylabel'),'String','Reconstruction Error') 
set(get(AX(2),'Ylabel'),'String','Compression gain')


%%Part 2
figure()
subplot(3,3,1)
colormap(gray)
imagesc(I);
title('Q2-2')
axis off
K = 1:8;
errors = zeros(size(K));
gain = zeros(size(K));
J = im2col(I,[8,8],'distinct');
for i=1:length(K)
    subplot(3,3,i+1)
    [X,Uk,Vk,Pk,errors(i),gain(i)] = PCA(J,K(i),1,0,0);
    imagesc(col2im(X,[8 8],[512 512],'distinct'));
    axis off
end
figure()
[AX,~,~] = plotyy(K,errors,K,gain);
title('Q2-2')
xlabel('K')
set(get(AX(1),'Ylabel'),'String','Reconstruction Error') 
set(get(AX(2),'Ylabel'),'String','Compression gain')


%%Part 3
figure()
subplot(3,3,1)
colormap(gray)
imagesc(I);
title('Q2-3')
axis off
K = 1:8;
errors = zeros(size(K));
gain = zeros(size(K));
J = im2col(I,[64,64],'distinct');
for i=1:length(K)
    subplot(3,3,i+1)
    [X,Uk,Vk,Pk,errors(i),gain(i)] = PCA(J,K(i),1,0,1);
    imagesc(col2im(X,[64 64],[512 512],'distinct'));
    axis off
end
figure()
[AX,~,~] = plotyy(K,errors,K,gain);
title('Q2-3')
xlabel('K')
set(get(AX(1),'Ylabel'),'String','Reconstruction Error') 
set(get(AX(2),'Ylabel'),'String','Compression gain')
