forked from spmallick/learnopencv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreconstructFace.py
95 lines (71 loc) · 2.39 KB
/
reconstructFace.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Import necessary packages
import os
import sys
import cv2
import numpy as np
'''
Display result
Left = Original Image
Right = Reconstructed Face
'''
def displayResult(left, right) :
output = np.hstack((left,right))
output = cv2.resize(output, (0,0), fx=4, fy=4)
cv2.imshow("Result", output)
# Recontruct face using mean face and EigenFaces
def reconstructFace(*args):
# Start with the mean / average face
output = averageFace
for i in range(0,args[0]):
'''
The weight is the dot product of the mean subtracted
image vector with the EigenVector
'''
weight = np.dot(imVector, eigenVectors[i])
output = output + eigenFaces[i] * weight
displayResult(im, output)
if __name__ == '__main__':
# Read model file
modelFile = "pcaParams.yml"
print("Reading model file " + modelFile, end=" ... ", flush=True)
file = cv2.FileStorage(modelFile, cv2.FILE_STORAGE_READ)
# Extract mean vector
mean = file.getNode("mean").mat()
# Extract Eigen Vectors
eigenVectors = file.getNode("eigenVectors").mat()
# Extract size of the images used in training.
sz = file.getNode("size").mat()
sz = (int(sz[0,0]), int(sz[1,0]), int(sz[2,0]))
'''
Extract maximum number of EigenVectors.
This is the max(numImagesUsedInTraining, w * h * 3)
where w = width, h = height of the training images.
'''
numEigenFaces = eigenVectors.shape[0]
print("DONE")
# Extract mean vector and reshape it to obtain average face
averageFace = mean.reshape(sz)
# Reshape Eigenvectors to obtain EigenFaces
eigenFaces = []
for eigenVector in eigenVectors:
eigenFace = eigenVector.reshape(sz)
eigenFaces.append(eigenFace)
# Read new test image. This image was not used in traning.
imageFilename = "test/satya2.jpg"
print("Read image " + imageFilename + " and vectorize ", end=" ... ");
im = cv2.imread(imageFilename)
im = np.float32(im)/255.0
# Reshape image to one long vector and subtract the mean vector
imVector = im.flatten() - mean;
print("Done");
# Show mean face first
output = averageFace
# Create window for displaying result
cv2.namedWindow("Result", cv2.WINDOW_AUTOSIZE)
# Changing the slider value changes the number of EigenVectors
# used in reconstructFace.
cv2.createTrackbar( "No. of EigenFaces", "Result", 0, numEigenFaces, reconstructFace)
# Display original image and the reconstructed image size by side
displayResult(im, output)
cv2.waitKey(0)
cv2.destroyAllWindows()