Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/EigenFace/EigenFace.py
3118 views
1
# Import necessary packages.
2
from __future__ import print_function
3
import os
4
import sys
5
import cv2
6
import numpy as np
7
8
# Read images from the directory.
9
def readImages(path):
10
print("Reading images from " + path, end = "...")
11
12
# Create array of array of images.
13
images = []
14
# List all files in the directory and read points from text files one by one.
15
for filePath in sorted(os.listdir(path)):
16
fileExt = os.path.splitext(filePath)[1]
17
if fileExt in [".jpg", ".jpeg"]:
18
19
# Add to array of images.
20
imagePath = os.path.join(path, filePath)
21
im = cv2.imread(imagePath)
22
23
if im is None :
24
print("image:{} not read properly".format(imagePath))
25
else :
26
# Convert image to floating point.
27
im = np.float32(im)/255.0
28
# Add image to list.
29
images.append(im)
30
# Flip image.
31
imFlip = cv2.flip(im, 1);
32
# Append flipped image.
33
images.append(imFlip)
34
numImages = int(len(images) / 2)
35
# Exit if no image found.
36
if numImages == 0 :
37
print("No images found")
38
sys.exit(0)
39
40
print(str(numImages) + " files read.")
41
return images
42
43
# Create data matrix from a list of images.
44
def createDataMatrix(images):
45
print("Creating data matrix", end = " ... ")
46
'''
47
Allocate space for all images in one data matrix.
48
The size of the data matrix is
49
( w * h * 3, numImages )
50
where,
51
w = width of an image in the dataset.
52
h = height of an image in the dataset.
53
3 is for the 3 color channels.
54
'''
55
numImages = len(images)
56
sz = images[0].shape
57
# Data matrix.
58
data = np.zeros((numImages, sz[0] * sz[1] * sz[2]), dtype = np.float32)
59
for i in range(0, numImages):
60
image = images[i].flatten()
61
# Each row get replaced with one flattened image.
62
data[i,:] = image
63
64
print("DONE")
65
return data
66
67
# Generate new face.
68
def createNewFace(*args):
69
# Start with the mean image.
70
output = averageFace
71
72
# Add the eigen faces with the weights.
73
for i in range(0, NUM_EIGEN_FACES):
74
# Get trackbar position.
75
'''
76
OpenCV does not allow slider values to be negative.
77
So we use weight = sliderValue - MAX_SLIDER_VALUE / 2
78
'''
79
sliderValues[i] = cv2.getTrackbarPos("Weight" + str(i), "Trackbars");
80
weight = sliderValues[i] - MAX_SLIDER_VALUE/2
81
# Add the weighted eigen face to the mean face.
82
output = np.add(output, eigenFaces[i] * weight)
83
84
# Display Result at 2x size.
85
output = cv2.resize(output, (0,0), fx = 2, fy = 2)
86
cv2.imshow("Result", output)
87
88
# Reset sliders callback function.
89
def resetSliderValues(*args):
90
for i in range(0, NUM_EIGEN_FACES):
91
cv2.setTrackbarPos("Weight" + str(i), "Trackbars", int(MAX_SLIDER_VALUE/2));
92
createNewFace()
93
94
# Main function.
95
if __name__ == '__main__':
96
97
# Number of EigenFaces.
98
NUM_EIGEN_FACES = 10
99
100
# Maximum weight.
101
MAX_SLIDER_VALUE = 255
102
103
# Directory containing images.
104
dirName = "images"
105
106
# Read images.
107
images = readImages(dirName)
108
109
# Size of images.
110
sz = images[0].shape
111
112
# Create data matrix for PCA.
113
data = createDataMatrix(images)
114
115
# Compute the eigenvectors from the stack of images created.
116
print("Calculating PCA ", end = "...")
117
118
mean, eigenVectors = cv2.PCACompute(data, mean = None, maxComponents = NUM_EIGEN_FACES)
119
120
print ("DONE")
121
122
averageFace = mean.reshape(sz)
123
124
# Create a container to hold eigen faces.
125
eigenFaces = []
126
127
# Reshape eigen vectors to eigen faces.
128
for eigenVector in eigenVectors:
129
# REshape.
130
eigenFace = eigenVector.reshape(sz)
131
# Append eigen faces to the container.
132
eigenFaces.append(eigenFace)
133
134
# Create window for displaying result.
135
cv2.namedWindow("Result", cv2.WINDOW_NORMAL)
136
# Create window for displaying mean face.
137
cv2.namedWindow("Average", cv2.WINDOW_NORMAL)
138
139
# Upscale by a factor of two.
140
output = cv2.resize(averageFace, (0,0), fx = 2, fy = 2)
141
142
# Display.
143
cv2.imshow("Result", output)
144
cv2.imshow("Average", averageFace)
145
146
# Create Window for trackbars.
147
cv2.namedWindow("Trackbars", cv2.WINDOW_NORMAL)
148
149
# Create a list to contain slider values.
150
sliderValues = []
151
152
# Create Trackbars.
153
for i in range(0, NUM_EIGEN_FACES):
154
sliderValues.append(int(MAX_SLIDER_VALUE/2))
155
cv2.createTrackbar( "Weight" + str(i), "Trackbars", int(MAX_SLIDER_VALUE/2), MAX_SLIDER_VALUE, createNewFace)
156
157
# You can reset the sliders by clicking on the mean image.
158
cv2.setMouseCallback("Average", resetSliderValues);
159
160
print('''Usage:
161
Change the weights using the sliders.
162
Mouse hover on the result window to reset sliders.
163
Press q to terminate.''')
164
165
key = cv2.waitKey(0)
166
if key == ord('q'):
167
cv2.destroyAllWindows()
168
169