-
Notifications
You must be signed in to change notification settings - Fork 3
/
eigenface.py
executable file
·171 lines (141 loc) · 5.89 KB
/
eigenface.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import PIL,os
from PIL import Image
import numpy as np
from scipy import linalg as LA
class PoolImages():
def __init__(self,directory):
#set of images to compare with the testimage
self.full_file_paths = self.get_filepaths(directory)#"./photos/training"
print 'number of training examples:', len(self.full_file_paths)
self.images = []
self.SetImagesFromFolder()
#determine size each vector
self.imsize = len(self.images[0])
#calculate the average
self.Nimages = len(self.images)
self.Avimage = []
self.CalcAverage()
#calculate diff
self.diffimages = [0 for i in range(self.Nimages)]
self.CalcDiffImagesAv()
#compute the eigenvectors of the C=L^T
self.uvecs = [[0.0 for j in range(self.imsize)] for i in range(self.Nimages)]
self.CalcEigenvectors()
#calc images projections:
self.projdiffimages = [[0 for j in range(self.Nimages)] for i in range(self.Nimages)]
self.CalcProjectionImages()
def get_filepaths(self,directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = [] # List which will store all of the full filepaths.
# Walk the tree.
for root, directories, files in os.walk(directory):
for filename in files:
# Join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath) # Add it to the list.
return file_paths # Self-explanatory.
def SetImagesFromFolder(self):
for f in self.full_file_paths:
im = Image.open(f).convert('L')
pix = im.load()
w=im.size[0]
h=im.size[1]
imagetmp = []
for i in range(w):
for j in range(h):
imagetmp.append(pix[i,j])
self.images.append(imagetmp)
def CalcAverage(self):
for i in range(self.imsize):
tmpvalue = sum(row[i] for row in self.images)
self.Avimage.append(tmpvalue/self.Nimages)
def DumpAverage(self):
#see the av output
img=Image.open(self.full_file_paths[0]).convert('L')# grayscale
pix=img.load()
k=0
for i in range(img.size[0]):
for j in range(img.size[1]):
pix[i,j] = self.Avimage[k]
k=k+1
img.save("average.jpg")
def CalcDiffImagesAv(self):
for i in range(self.Nimages):
tmpdiff = []
for j in range(self.imsize):
tmpdiff.append(float(-self.Avimage[j]+self.images[i][j]))
#diffimages.append(tmpdiff)
self.diffimages[i] = tmpdiff
def CalcEigenvectors(self):
#calculate transponse covariance matrix
L = [[0 for j in range(self.Nimages)] for i in range(self.Nimages)]
for i in range(self.Nimages):
for j in range(self.Nimages):
L[i][j] = np.dot(self.diffimages[i],self.diffimages[j])
#calc eigenvalues/vectors
evals, evecs = LA.eig(L)
for i in range(self.Nimages):
for j in range(self.Nimages):
self.uvecs[i] = map(lambda x,y:x+evecs[i][j]*y, self.uvecs[i],self.diffimages[j])
def CalcProjectionImages(self):
for i in range(self.Nimages):
for j in range(self.Nimages):
self.projdiffimages[i][j] = np.dot(self.uvecs[j],self.diffimages[i])
class CheckImage():
def __init__(self,FILENAME,directory):
self.imagetest = []
self.GetImage(FILENAME)
self.poolims= PoolImages(directory)
#calc diff and projection into subspace
self.utest = [0 for i in range(self.poolims.Nimages)]
self.uvecs = self.poolims.uvecs
self.Avim = self.poolims.Avimage
self.CalcProjectionIm()
self.projectionims = self.poolims.projdiffimages
#self.DeterminePoolImage
def GetImage(self,filename):
imtest=Image.open(filename).convert('L')# grayscale
pixtest = imtest.load()
w=imtest.size[0]
h=imtest.size[1]
for i in range(w):
for j in range(h):
self.imagetest.append(pixtest[i,j])
def CalcProjectionIm(self):
for i in range(self.poolims.Nimages):
self.utest[i] = sum(map(lambda x,y,z: x*(y-z),self.uvecs[i],self.imagetest,self.Avim))
def DeterminePoolImage(self):
#calc distances:
mindist = 1000
indx=0
for i in range(self.poolims.Nimages):
if i==0:
mindist= self.dist(self.utest,self.projectionims[i])
else:
if self.dist(self.utest,self.projectionims[i])<mindist:
mindist = self.dist(self.utest,self.projectionims[i])
indx =i
print 'index=',indx,'mindist=',mindist
#show closer image
imgresult=Image.open(self.poolims.full_file_paths[indx]).convert('L')
imgresult.save("result.jpg")
def dist(self,v1,v2):
'''
calculate the distance between 2 vectors
'''
d=0
for x in range(len(v1)):
d = d+(v1[x]-v2[x])*(v1[x]-v2[x])
return d
#pool images
folder = "./photos/training"
#test image here:
FILENAME='testimage.jpg' #image can be in gif jpeg or png format
#run script
test = CheckImage(FILENAME,folder)
test.DeterminePoolImage()