forked from jakobkarlstrand/tnm034-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute_eigenFace.m
78 lines (59 loc) · 1.93 KB
/
compute_eigenFace.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
%%This function uses PCA to reduce the dimensionality of the dataset
function [I,weight, averageFace, u, index] = compute_eigenFace(allFaces)
M = length(allFaces);
N = size(allFaces{1});
%%allocate space.
x = cell(1, M);
averageFace = zeros(N(1)*N(2),1);
figure;
%%For each face, reshape into NxN vetor and calculate average.
for i = 1:M
x{i} = rgb2gray(allFaces{i}); %%Convert to gray scale.
x{i} = reshape(x{i},[],1); %%Reshape into NxN vector.
averageFace = averageFace + (1/M) * x{i}; %%Calculate average face vector.
end
%%allocate space.
phi = cell(1,M);
A = zeros(N(1)*N(2), M);
for i = 1:M
phi{i} = x{i} - averageFace; %%Subtract average face from each face vector.
A(:,i) = phi{i}; %%Store the image vector in A.
end
%%Compute covariance matrix of size MxM
C = A'*A;
[eigenVectors, eigenValues] = eig(C); %%calculates eigenvalues and eigenvectors of C.
v = eigenVectors; %%easier to read.
u = A*v; %%step 7 of PCA according to slides.
%%Display eigenfaces
% figure;
% for j = 1:M
% eigenFaces = reshape(u(:,j), N(1), N(2));
% subplot(4,4,j);
% imshow(eigenFaces);
% end
%%Sort the eigenvalues in descending order => Index = M, M-1, M-2...
eigenValues = diag(eigenValues);
[~, index] = sort(eigenValues, 'descend');
numberOfEigenVectors = 16;
weight = zeros(M, numberOfEigenVectors); %%Allocate space
%%calculate weights
for i = 1:M
for j = 1:numberOfEigenVectors
%%Only need to normalize once
if(i == 1)
u(:,index(j)) = u(:,index(j))/norm(u(:,index(j))); %%Normalize
end
weight(i,j) = u(:,index(j))'* phi{i};
end
end
I = cell(1, M); %%Allocate space
%%compute the linear combination of each original face
for i = 1:M
sum = 0;
for j = 1:numberOfEigenVectors
sum = sum + weight(i,j)*u(:,index(j));
end
I{i} = averageFace + sum;
I{i} = reshape(I{i}, N(1), N(2));
end
save('computedData.mat', 'weight', 'averageFace', 'u', 'index');