/
AFLWPATCHESsplit.py
218 lines (172 loc) · 6.46 KB
/
AFLWPATCHESsplit.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 10:25:06 2013
@author: attale00
"""
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 17:29:01 2013
@author: attale00
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 15:24:39 2013
This script classifies the multipie pictures with the random forest classifer learned on the aflw database pics
. It was trained on hog features only on the down scaled images. see the accompanying info file to the classfier for details
@author: attale00
"""
import utils
import featureGeneration as fg
import cv2
import numpy as np
import pickle
import sys
import plottingUtils
import classifierUtils
from sklearn import svm
from sklearn import linear_model
from sklearn.decomposition import FastICA
from scipy import linalg
import matplotlib.pyplot as plt
def main(mode):
path = '/local/attale00/AFLW_ALL/'
path_ea = '/local/attale00/AFLW_cropped/cropped3/'
#
fileNames = utils.getAllFiles(path_ea);
# minr = 10000;
# for f in fileNames:
# im = cv2.imread(path_ea+f,-1)
# if im.shape[0]!=40 or im.shape[1]!=120:
# print f
# print im.shape
# minr = minr if im.shape[0]>= minr else im.shape[0]
#
# print minr
#
labs=utils.parseLabelFiles(path+'/labels/labels','mouth_opening',fileNames,cutoffSeq='.png',suffix='_face0.labels')
testSet = fg.dataContainer(labs)
testSet.targetNum=map(utils.mapMouthLabels2Two,testSet.target)
roi=(0,37,0,115)
roi=None
#roi=(44,84,88,168)
# eM=np.load('/home/attale00/Desktop/mouthMask.npy')
# m=cv2.resize(np.uint8(eM),(256,256));
# strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
# dil = cv2.dilate(m,strel)
#
# m=dil>0;
#X=fg.getAllImagesFlat(path_ea,testSet.fileNames,(40,120),roi=roi)
# perform ICA
names_open = []
names_closed = []
for i,f in enumerate(testSet.fileNames):
if testSet.targetNum[i] == 0:
names_closed.append(f)
elif testSet.targetNum[i] == 1:
names_open.append(f)
Xopen = fg.getAllImagesFlat(path_ea,names_open,(40,120))
XClosed = fg.getAllImagesFlat(path_ea,names_closed,(40,120))
if mode not in ['s','v']:
icaopen = FastICA(n_components=100,whiten=True)
icaopen.fit(Xopen)
meanIopen=np.mean(Xopen,axis=0)
X1open=Xopen-meanIopen
dataopen=icaopen.transform(X1open)
filtersopen=icaopen.components_
plottingUtils.showICAComponents(filtersopen,(40,120),4,4)
icaclosed = FastICA(n_components=100,whiten=True)
icaclosed.fit(XClosed)
meanIclosed=np.mean(XClosed,axis=0)
X1closed=XClosed-meanIclosed
dataclosed=icaclosed.transform(X1closed)
filtersclosed=icaclosed.components_
plottingUtils.showICAComponents(filtersclosed,(40,120),4,4)
plt.show()
elif mode in ['s','v']:
W=np.load('/home/attale00/Desktop/classifiers/patches/filterMP1.npy')
m=np.load('/home/attale00/Desktop/classifiers/patches/meanIMP1.npy')
X1=X-m
data=np.dot(X1,W.T)
for i in range(len(fileNames)):
testSet.data[i].extend(data[i,:])
strel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))
#fg.getHogFeature(testSet,roi,path=path_ea,ending='.png',extraMask = None,orientations = 5, cells_per_block=(3,3),pixels_per_cell=(24,8),maskFromAlpha=False)
#fg.getColorHistogram(testSet,roi,path=path_ea,ending='.png',colorspace='lab',bins=20)
#pca
# n_samples, n_features = X.shape
#
# mean_ = np.mean(X, axis=0)
# X -= mean_
# U, S, V = linalg.svd(X)
# explained_variance_ = (S ** 2) / n_samples
# explained_variance_ratio_ = (explained_variance_ /explained_variance_.sum())
# K=V / S[:, np.newaxis] * np.sqrt(n_samples)
# filters=K[:100]
# data=np.dot(X,filters.T)
rf=classifierUtils.standardRF(max_features = 27,min_split=13,max_depth=40)
#rf = svm.NuSVC()
#rf = linear_model.SGDClassifier(loss='perceptron', eta0=1, learning_rate='constant', penalty=None)
if mode in ['s','v']:
print 'Classifying with loaded classifier'
_classifyWithOld(path,testSet,mode)
elif mode in ['c']:
print 'cross validation of data'
classifierUtils.dissectedCV(rf,testSet)
elif mode in ['save']:
print 'saving new classifier'
_saveRF(testSet,rf,filters=filters,meanI=meanI)
else:
print 'not doing anything'
def _saveRF(testSet,rf,filters=None,meanI=None):
rf.fit(testSet.data,testSet.targetNum)
root='/home/attale00/Desktop/classifiers/patches/'
pickle.dump(rf,open(root+'rfICAHogColor','w'))
f=open(root+'rficahogcolor.txt','w')
f.write('Source Images: AFLWALL')
f.write('attribute: Mouth')
f.write('Features: ICA HOg color')
f.write('100 comps \n')
f.write('20 color bins \n')
f.write('ppc 24,8, cpb 3,3 dir 5 \n')
f.write('ROI:(50,74,96,160)\n')
f.write('labels: none: 0, light,thick: 1\n')
f.close()
if filters is not None:
np.save(root+'filter1',filters)
np.save(root+'meanI1',meanI)
def _classifyWithOld(path,testSet,mode):
#f=file('/home/attale00/Desktop/classifiers/RandomForestMouthclassifier_1','r')
f=file('/home/attale00/Desktop/classifiers/patches/rfICAMultiPie','r')
clf = pickle.load(f)
testSet.classifiedAs=clf.predict(testSet.data)
testSet.hasBeenClassified = True
if mode =='s':
_score(clf,testSet)
else:
_view(clf,testSet,path+'Multi-PIE/extracted/')
_score(clf,testSet)
def _score(clf,testSet):
score = clf.score(testSet.data,testSet.targetNum)
testSet.hasBeenClassified = True
classifierUtils.evaluateClassification(testSet,{0:'closed or narrow',1:'open or wide open'})
print 'Overall Score: {:.3f}'.format(score)
return
def _view(clf,testSet,path):
viewer = plottingUtils.ClassifiedImViewer(path,testSet)
viewer.view(comparer=plottingUtils.MouthTwo2FourComparer)
if __name__=='__main__':
if len(sys.argv)==2:
if sys.argv[1] in ['s','Score']:
m = 's'
elif sys.argv[1] in ['v','View']:
m='v'
elif sys.argv[1] in ['c']:
m='c'
elif sys.argv[1] in ['save']:
m='save'
else:
print 'Option not supported, valid options are s,v. Now just scoring'
m='s'
else:
m='s'
main(m)