%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%    Hw7: classify textures by PCA                  %
%    Student: Bo Han                                %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%result: pic2 and pic4 are grouped into one class.
%        pic1, pic3, pic5 and pic6 are grouped into another class, in which
%        pic5 and pic6 may be grouped into a subclass

clear
% read in each image and compute the moment invarients
img=[];
imgvec=[];

sample_size=45;
figure;
for i=1:6
    tem=sprintf('%1d',i);
    filename=['hw7_' tem '.jpg'];
    img=imread(filename);
    [h,w]=size(img);
    %extract the sample regions
    imgt1=img(h-90+1:h, 1:90);
    imgt2=img(1:90, w-90+1:w);
    imgt1=imresize(imgt1,0.5,'bilinear');
    imgt2=imresize(imgt2,0.5,'bilinear');
    %reshape the sample region into vector
    imgvec((i-1)*2+1,:)=reshape(imgt1, 1, sample_size*sample_size);
    imgvec((i-1)*2+2,:)=reshape(imgt2, 1, sample_size*sample_size);
    subplot(6,2, (i-1)*2+1);
    imshow(imgt1);
    tem1=sprintf('%2d',(i-1)*2+1);
    title(tem1);
    
    subplot(6,2, (i-1)*2+2);    
    imshow(imgt2);
    tem2=sprintf('%2d',(i-1)*2+2);
    title(tem2);
end
% 
%standarize the vectors
for j=1:sample_size*sample_size
    tem=imgvec(:,j);
    stdt=std(tem);
    meant=mean(tem);
    stdvec(:,j)=(tem-meant)./stdt;
end

retvar=[];
for dim=1:1:12
    [pcavec,proj,retvar(dim)] = pca_an(stdvec,dim,0);
    %compare the Euclidean Distance
    edist=[];
    for i=1:12
        for j=1:12
          edist(dim,i,j) = vectorComp(pcavec(i,:),pcavec(j,:), 2);
      end
    end

    %compare the Cosine Distance
    cosdist=[];
    for i=1:12
        for j=1:12
          cosdist(dim,i,j) = vectorComp(pcavec(i,:),pcavec(j,:), 1);
        end
    end

end
