clear all;
clc;

lena = imread('lena.png');

window_size = 32;

width = size(lena, 2);
height = size(lena, 1);

windows_per_width = width / window_size;
windows_per_height = height / window_size;

output = zeros(height, width);

K = 16;

for i = 1:windows_per_height
    for j = 1:windows_per_width
        ind1 = ((i-1) * window_size + 1):(i * window_size);
        ind2 = ((j-1) * window_size + 1):(j * window_size);
        window = lena (ind1, ind2);
        [Y, W, R, R_hat, window_new] = pca_transform(double(window), K);
        
        output(ind1, ind2) = window_new;
    end
end

output = uint8(output);

figure;
imshow(output);
imwrite(output, ['lenak', num2str(K),'.png']);

mse = 1 / (width * height) * sum(sum((lena - output).^2))
psnr = 20 * log10(255) - 10 * log10(mse)