%% ACP section
% Here we redistribute data between images using the ACP algorithm

% Display graphs ?
display = 1;

test = ima2mat('19BASEIMAGES/BASEIMAGES/landsattarasconC1');
nrow = size(test, 1);
ncol = size(test, 2);

% Chargement de toutes les images
ims = zeros(8, nrow, ncol);
for i = 1 : 8
    ims(i,:,:) = ima2mat(strcat('19BASEIMAGES/BASEIMAGES/landsattarasconC', int2str(i)));
    if display
        figure();
        colormap(gray(256));
        image(reshape(ims(i,:,:), nrow, ncol));
    end;
end;

% Construction de la matrice M de l'ACP
mat = zeros(nrow * ncol, 8);
for i = 1 : nrow
    for j = 1 : ncol
        for k = 1 : 8
            mat(i * ncol + j, k) = ims(k, i, j);
        end;
    end;
end;

for k = 1 : 8
    mu_k = mean(mat(:, k));
    sigma_k = std(mat(:, k));
    mat(:, k) = (mat(:, k) - mu_k) / sigma_k;
end;

cov_mat = cov(mat);
[ u, lambda ]= eig(cov_mat);
lambda = max(lambda);

for i = 1 : nrow
    for j = 1 : ncol
        for k = 1 : 8
            mat(i * ncol + j, k) = mat(i * ncol + j, :) * u(:, k);
        end;
    end;
end;

tab = zeros(nrow, ncol);
for k = 1 : 8
    for i = 1 : nrow
        for j = 1 : ncol
            tab(i, j) = mat(i * ncol + j, k);
        end;
    end;
    tab = 255 * (tab - min(tab(:))) / (max(tab(:)) - min(tab(:)));
    if display
        figure();
        colormap(gray(256));
        image(tab);
    end;
end;
lambda
lambda = lambda / sum(lambda);
lambda * 100
cumsum(fliplr(lambda))
