clc;
clear;
data = load('/Users/apple/Downloads/test.mat');
faces = data.FACES;
scale = 208/(max(max(faces)) - min(min(faces))); % normalize the image
faces = scale*(faces - min(min(faces)));
test = data.test;
figure;
imshow(test,[]);
[rows,cols] = size(test);
faces = faces';
[coeff,score,latent,tsquare] = princomp(faces);
k = 1;
vector = zeros(121*121,1600);
for i = 21 : rows - 19
for j = 21 : cols - 19
face_temp = test(i-20:i+19,j-20:j+19);
vector(k,:) = reshape(face_temp,1,1600);
k = k + 1;
end
end
F = mean(faces);
P = coeff(:,1:9);
x_tilde = zeros(14641,1600);
for i = 1 : 1600
for j = 1 : 14641
x_tilde(j,i) = vector(j,i) - F(1,i);
end
end
score = x_tilde * P;
distance = ones(14641,1);
lambda = (1/6) * (sum(latent(1:6,1)));
rho = (1/3) * (sum(latent(7:9,1)));
for i = 1 : 14641
distance(i,1) = sum(score(i,1:6).^2)/lambda ...
+ (sum(x_tilde(i,:).^2) - sum(score(i,1:6).^2))/rho;
end
b = reshape(distance,121,121);
figure;
imshow(b,[]);
title('distance', 'FontSize', 15);
Pos = zeros(3,9);
% show the location of the faces identified
figure;
for i = 1:9
[row,col,val] = findPos(b);
Pos(1,i) = row;
Pos(2,i) = col;
Pos(3,i) = val;
b = cleanNear(b,row,col);
subplot(3,3,i);
imshow(b,[]);
hold on;
plot(Pos(2,i),Pos(1,i),'rs','MarkerSize',2);
end
figure;
imshow(test,[]);
for i = 1 : 9
hold on;
plot(Pos(2,i)+20,Pos(1,i)+20,'rs','MarkerSize',2);
end
% calculate the weight of the identified faces.
a = zeros(9,9);
k = 1;
for i = 1 : 9
row = Pos(1,i);
col = Pos(2,i);
subimage = test(row-20:row+19,col-20:col+19);
subvector = reshape(subimage,1,1600) - F;
a(k,:) = subvector * coeff(:,1:9);
k = k + 1;
end
% calculate the weight of the original training image.
g = zeros(9,9);
g(1,:) = (faces(7,:) - F) * coeff(:,1:9);
g(2,:) = (faces(4,:) - F) * coeff(:,1:9);
g(3,:) = (faces(9,:) - F) * coeff(:,1:9);
g(4,:) = (faces(8,:) - F) * coeff(:,1:9);
g(5,:) = (faces(2,:) - F) * coeff(:,1:9);
g(6,:) = (faces(6,:) - F) * coeff(:,1:9);
g(7,:) = (faces(5,:) - F) * coeff(:,1:9);
g(8,:) = (faces(1,:) - F) * coeff(:,1:9);
g(9,:) = (faces(3,:) - F) * coeff(:,1:9);
% calculate the norm of the dfference between weights ai for each
% of the identified faces, and the corresponding weights for the
%original training faces.
l = zeros(9,1);
for i = 1:9
temp = a(i,:) - g(i,:);
s = sum(temp.^2);
l(i,1) = s^0.5;
end
% plot the distance vs.training face number
plot_dis = zeros(1,9);
plot_dis(1,1) = Pos(3,8);
plot_dis(1,2) = Pos(3,5);
plot_dis(1,3) = Pos(3,9);
plot_dis(1,4) = Pos(3,2);
plot_dis(1,5) = Pos(3,7);
plot_dis(1,6) = Pos(3,6);
plot_dis(1,7) = Pos(3,1);
plot_dis(1,8) = Pos(3,4);
plot_dis(1,9) = Pos(3,3);
figure;
plot(plot_dis);
title('distance vs training face number', 'FontSize', 15);