% Joe Jupin
% Homework 6
% Segmented pictures

%  clear all variables
clear all;

% read images
% names of images
fpics = {'carpet.bmp',
        'fur.bmp',
        'grass.bmp',
        'gravel.bmp',
        'knit.bmp',
        'tartan.bmp'};
% transpose gpics
fpics = fpics';
% get size of gpics
fnum = numel(fpics);
% read images into double matrix
for i=1:fnum
    f(:,:,i) = imread(char(fpics(i)));
end
% get gpics dimensions
[ipixs jpixs kpics] = size(f);

% obtain a stack of 24 subsize x subsize images from original images
subsize = 64;
for i=1:fnum
    f1(:,:,(i*4-1)) = f(1:subsize,1:subsize, i);
    f1(:,:,(i*4-2)) = f((ipixs-subsize+1):ipixs,1:subsize, i);
    f1(:,:,(i*4-3)) = f(1:subsize,(jpixs-subsize+1):jpixs, i);
    f1(:,:,(i*4)) = f((ipixs-subsize+1):ipixs,(jpixs-subsize+1):jpixs, i);
end
% obtain number and dimensions of images to be processed
[f1ipixs f1jpixs f1kpics] = size(f1);

% obtain principal component data
[X, R] = imstack2vectors(f1);
Q = f1kpics;
P = princomp(X, Q);

% obtain image variances
vX = var(double(X(:,:)));

% extract principal components images pY
for i=1:Q
    pv = P.Y(:,i);
    pv = reshape(pv, subsize, subsize);
    pY(:,:,i) = pv;
end
% extract reconstructed images pX
for i=1:Q
    pv = P.X(:,i);
    pv = reshape(pv, subsize, subsize);
    pX(:,:,i) = pv;
end
% extract the covariance matrix for X
pCx = P.Cx;
% extract the mean vector population for X
pmx = P.mx;
% extract the covariance matrix for Y
pCy = P.Cy;
% extract the eigenvalues
pev = diag(pCy);
% extract the mean squared error
pems = P.ems;
% extract the pc transformation matrix
pA = P.A;

% print original images
figure;
for i=1:f1kpics
    subplot(4,Q/4,i);
    imshow(f1(:,:,i));
end

% print eigenimages
figure;
for i=1:Q
    subplot(4,Q/4,i);
    imshow(pY(:,:,i),[]);
end

% calculate average image
for i=1:f1ipixs
    for j=1:f1jpixs
        m(i,j) = uint8(mean(f1(i,j,:)));
    end
end
% print average image
figure;
imshow(m);
vX(length(vX)+1) = var(double(m(:)));

% print graph of variances
figure;
bar(vX);

clear pv
clear i
clear j
clear ipixs
clear jpixs
clear kpics
clear subsize
clear fnum
clear fpics
%clear Q
clear X
clear R