pca training

close all;
clear;
clc;
load training_data.mat;
//% a) reading images
NumOfSamples=2;
str_Path='/Users/nana/Desktop/matlab/PCA_Images/Testing/';

for i=1:NumOfSamples
    str_Load=strcat(str_Path,num2str(i),'.bmp');
    Image=imread(str_Load);
    TestingImage(:,i)=double(reshape(Image,[],1));
end
//% b) calculate demeaned face and coefficients
for i=1:NumOfSamples
    DemeanFace(:,i)=TestingImage(:,i)-MeanFace;
    //% DemeanFace means diff of each face from the average
end
for i=1:NumOfSamples
    D=DemeanFace(:,i);
    Display=reshape(D,[72 64]);
    figure(i),imagesc(Display),colorbar,colormap(gray),title('Demeaned Face');
end
N=19;

for i=1:NumOfSamples
    for j=1:N
        TCoef(i,j)=(DemeanFace(:,i)')*EV(:,order(j));
    end
end
ReconstImage_test=zeros(4608,NumOfSamples);
M=19;
for i=1:NumOfSamples
    for j=1:M
        ReconstImage_test(:,i)=ReconstImage_test(:,i)+TCoef(i,j)*EV(:,order(j));
    end
    ReconstImage_test(:,i)=MeanFace+ReconstImage_test(:,i);
end
//% c)calculate MSE
for i=1:NumOfSamples
    Difference(:,i)=TestingImage(:,i)-ReconstImage_test(:,i);
    SSE(:,i)=sum(sum(Difference(:,i).*Difference(:,i)));
end
n=size(MeanFace);
MSE=SSE/4608;
//%Dispaly ReconstImage
for i=1:NumOfSamples
    R=ReconstImage_test(:,i);
    show=reshape(R,[72 64]);
    figure(i+2),imagesc(show),colorbar,colormap(gray),title('ReconstImage Face');
end
//% d) using distances for face recognition
for i=1:2
    for j=1:20
    Difference=coef(j,:)-TCoef(i,:);
    Temp(i,j)=sum(Difference.*Difference,2);
    end
end
dist=sqrt(Temp);
[r1,order1]=sort(dist(1,:));
[r2,order2]=sort(dist(2,:));
for i=1:3
    re1(:,i)=TrainingImage(:,order1(i));
    show=reshape(re1(:,i),[72 64]);
    figure(i+4),imagesc(show),colorbar,colormap(gray),title('Recognition Face')
end
for i=1:3
    re2(:,i)=TrainingImage(:,order2(i));
    show=reshape(re2(:,i),[72 64]);
    figure(i+7),imagesc(show),colorbar,colormap(gray),title('Recognition Face')
end

你可能感兴趣的:(pca training)