%archana gupta
%hw 7   
%image processing -principal component analysis

%to run program at command line type 'pca(comp_no)' 
%where comp_no is no of principal components used for calculations

function error=pca(comp_no)

names={'ima11.jpg','ima12.jpg','ima21.jpg','ima22.jpg','ima31.jpg','ima32.jpg','ima41.jpg','ima42.jpg','ima51.jpg','ima52.jpg','ima61.jpg','ima62.jpg'};
%find no of images
imageno=numel(names);

%read first image to initialise imstack and imdat
imdat=double(imread('ima11.jpg'));
imstack=cat(3,imdat);

%add all the remaining images to the stack
for x=2:imageno
   imdat=double(imread(char(names(x))));
   imstack=cat(3,imstack,imdat);
end

%gives columnvector and their corresponding coordinates
[vect,coord]=imstack2vectors(imstack);

%find principal component
P=princomp(vect,comp_no);
error=P.ems;
%calculate euclidean distance between principal component images
%P.A contains the principal component transformation matrix (ix12)
%i is no of principal components
PCmat=P.A;
edist=[];

for i=1:imageno
    for j=1:imageno
        edist(i,j) = norm(PCmat(:,i)-PCmat(:,j));
    end
end

disp('   EUCLIDEAN DISTANCE BETWEEN PRINCIPAL COMPONENT IMAGES');
disp(edist);

%calculate cosine distance between principal component images
cosdist=[];

for i=1:imageno
    for j=1:imageno
        cosdist(i,j) =1-(dot(PCmat(:,i),PCmat(:,j)))/(norm(PCmat(:,i))*norm(PCmat(:,j)));
    end
end

disp('    COSINE DISTANCE BETWEEN PRINCIPAL COMPONENT IMAGES');
disp(cosdist);

%reconstruct original image
for j=1:12
    h1=P.X(:,j);
    h1=reshape(h1,100,100);
    figure;
    imshow(h1,[]);    
end

%calculate euclidean distance between actual and reconstructed image
%P.X contains the reconstructed vectors 

recvect=P.X;
edist1=[];

for i=1:imageno
    for j=1:imageno
        edist1(i,j) = norm(vect(:,i)-recvect(:,j));
    end
end

disp('   EUCLIDEAN DISTANCE BETWEEN ACTUAL & RECONSTRUCTED IMAGES');
disp(edist1);

%calculate cosine distance between principal component images
cosdist1=[];

for i=1:imageno
    for j=1:imageno
        cosdist1(i,j) =1-(dot(vect(:,i),recvect(:,j)))/(norm(vect(:,i))*norm(recvect(:,j)));
    end
end

disp('   COSINE DISTANCE BETWEEN ACTUAL & RECONSTRUCTED IMAGES');
disp(cosdist1);

return;
