-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.py
421 lines (349 loc) · 14.5 KB
/
main.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.19
# in conjunction with Tcl version 8.6
# Apr 22, 2019 03:43:23 PM PDT platform: Windows NT
import sys
import cv2
from PIL import Image, ImageTk
import pickle
import numpy as np
import tensorflow as tf
import matplotlib as plt
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
imageSource = ""
img_counter = 0
rio = ""
knn = None
svm = None
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
try:
import ttk
py3 = False
except ImportError:
import tkinter.ttk as ttk
py3 = True
n_classes = 5
batch_size = 1000
x = tf.placeholder('float', [None, 1600])
y = tf.placeholder('float')
keep_rate = 0.8
keep_prob = tf.placeholder(tf.float32)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def maxpool2d(x):
# size of window movement of window
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
def convolution_neural_network(x):
weights = {'W_conv1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
'W_conv2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
'W_fc': tf.Variable(tf.random_normal([10 * 10 * 64, 1024])),
'out': tf.Variable(tf.random_normal([1024, n_classes]))}
# weights = {'W_conv1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
# 'W_conv2': tf.Variable(tf.random_normal([5, 5, 32, 64])),
# 'W_conv3': tf.Variable(tf.random_normal([5, , 64, 128])),
# 'W_fc': tf.Variable(tf.random_normal([13 * 13 * 128, 128])),
# 'out': tf.Variable(tf.random_normal([128, n_classes]))}
biases = {'b_conv1': tf.Variable(tf.random_normal([32])),
'b_conv2': tf.Variable(tf.random_normal([64])),
# 'b_conv3': tf.Variable(tf.random_normal([128])),
'b_fc': tf.Variable(tf.random_normal([1024])),
'out': tf.Variable(tf.random_normal([n_classes]))}
x = tf.reshape(x, shape=[-1, 40, 40, 1])
conv1 = tf.nn.relu(conv2d(x, weights['W_conv1']) + biases['b_conv1'])
conv1 = maxpool2d(conv1)
conv2 = tf.nn.relu(conv2d(conv1, weights['W_conv2']) + biases['b_conv2'])
conv2 = maxpool2d(conv2)
# conv3 = conv2d(conv2,weights['W_conv3']) + biases['b_conv3']
# conv3 = maxpool2d(conv3)
# fc = tf.reshape(conv2, [-1, 7*7*64])
fc = tf.reshape(conv2, [-1, 10 * 10 * 64])
fc = tf.nn.relu(tf.matmul(fc, weights['W_fc']) + biases['b_fc'])
output = tf.matmul(fc, weights['out']) + biases['out']
return output
# saver = tf.train.Saver()
def Cnn_predict(image):
img = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (40, 40))
# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
data = []
flat = img.flatten()
data.append(flat)
data = np.asarray(data)
prediction = convolution_neural_network(x)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
tf.train.Saver().restore(sess, "cnn/cnnmodel.ckpt")
result = sess.run(tf.argmax(prediction.eval(feed_dict={x: data}), 1))
print(result[0])
return result[0]
def onclick(btnNum,Label1,group):
global img_counter
if btnNum == 1:
temp = capture()
if temp is not None:
imageSource = temp
img = cv2.imread(imageSource)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
print(faces)
for (x, y, w, h) in faces:
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y - 30:y + 30 + h, x - 30:x + 30 + w]
img_name = "roi_{}.jpg".format(img_counter)
global rio
rio = img_name
cv2.imwrite(img_name, roi_color)
cv2.rectangle(img, (x-10, y-60), (x + w, y+10 + h), (255, 0, 0), 2)
img_name = "opencv_image_face_{}.jpg".format(img_counter)
cv2.imwrite(img_name, img)
imageToShow = Image.open(temp)
img3 = cv2.imread(temp)
dim = (320, 240)
imageToShow = cv2.resize(img, dim)
img_name = "opencv_image_face__rect_{}.jpg".format(img_counter)
cv2.imwrite(img_name, imageToShow)
imageToShow = Image.open(img_name)
img2 = ImageTk.PhotoImage(imageToShow)
Label1.configure(image=img2)
Label1.image = img2
img_counter += 1
#print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
# elif btnNum == 2:
elif btnNum == 3:
if group == 0:
# global rio
# path = rio
print(rio)
# img = cv2.cvtColor(cv2.UMat(rio), cv2.COLOR_BGR2GRAY,ranges=[])
img = cv2.imread(rio,cv2.IMREAD_GRAYSCALE)
# img1 = cv2.cvtColor(rio, cv2.COLOR_BGR2GRAY)
scale = 50
dim = (scale, scale)
img = cv2.resize(img, dim)
img = img.flatten()
img = np.asarray(img)
# plt.imshow(img, cmap='gray')
# plt.show
global knn
y_pred = knn.predict(img.reshape(1, -1))
print(y_pred)
if y_pred ==0:
Label1.configure(text="Knn estimate is from Age 1 to 14")
if y_pred ==1:
Label1.configure(text="Knn estimate is from Age 15 to 25")
if y_pred ==2:
Label1.configure(text="Knn estimate is from Age 26 to 40")
if y_pred ==3:
Label1.configure(text="Knn estimate is from Age 41 to 60")
if y_pred ==4:
Label1.configure(text="Knn estimate is from Age 61 to 100")
elif group == 1:
img = cv2.imread(rio, cv2.IMREAD_GRAYSCALE)
# img1 = cv2.cvtColor(rio, cv2.COLOR_BGR2GRAY)
scale = 100
dim = (scale, scale)
img = cv2.resize(img, dim)
img = img.flatten()
img = np.asarray(img)
# plt.imshow(img, cmap='gray')
# plt.show
global svm
y_pred = svm.predict(img.reshape(1, -1))
print(y_pred)
Label1.configure(text="SVM estimate is "+ str(y_pred[0]))
# if y_pred == 0:
# Label1.configure(text="Knn estimate is from Age 1 to 14")
# if y_pred == 1:
# Label1.configure(text="Knn estimate is from Age 15 to 25")
# if y_pred == 2:
# Label1.configure(text="Knn estimate is from Age 26 to 40")
# if y_pred == 3:
# Label1.configure(text="Knn estimate is from Age 41 to 60")
# if y_pred == 4:
# Label1.configure(text="Knn estimate is from Age 61 to 100")
elif group == 2:
# cnn predict
img = cv2.imread(rio)
y_pred=Cnn_predict(rio)
if y_pred ==0:
Label1.configure(text="Cnn estimate is from Age 1 to 14")
if y_pred ==1:
Label1.configure(text="Cnn estimate is from Age 15 to 25")
if y_pred ==2:
Label1.configure(text="Cnn estimate is from Age 26 to 40")
if y_pred ==3:
Label1.configure(text="Cnn estimate is from Age 41 to 60")
if y_pred ==4:
Label1.configure(text="Cnn estimate is from Age 61 to 100")
'''
conda remove opencv
conda install -c menpo opencv
pip install --upgrade pip
pip install opencv-contrib-python
'''
def capture():
cam = cv2.VideoCapture(0)
cv2.namedWindow("age estimation camera")
while True:
ret, image = cam.read()
cv2.imshow("age estimation camera", image)
if not ret:
break
k = cv2.waitKey(1)
global img_counter
if k % 256 == 27:
# ESC pressed
print("Escape hit, closing...")
cam.release()
cv2.destroyAllWindows()
return None
elif k % 256 == 32:
# SPACE pressed
img_name = "opencv_image_{}.jpg".format(img_counter)
cv2.imwrite(img_name, image)
img_source = "{}".format(img_name)
print(img_source)
cam.release()
cv2.destroyAllWindows()
return img_source
def vp_start_gui():
global knn
knn = getKnn().load()
global svm
svm = getsvm().load()
'''Starting point when module is the main routine.'''
global val, w, root
root = tk.Tk()
top = Toplevel1(root)
root.mainloop()
w = None
def create_Toplevel1(root, *args, **kwargs):
'''Starting point when module is imported by another program.'''
global w, w_win, rt
rt = root
w = tk.Toplevel (root)
top = Toplevel1 (w)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
'''This class configures and populates the toplevel window.
top is the toplevel containing window.'''
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
top.geometry("600x450+678+223")
top.title("New Toplevel")
top.configure(background="#d9d9d9")
group = tk.IntVar()
self.Label1 = tk.Label(top)
self.Label1.place(relx=0.233, rely=0.044, height=261, width=454)
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(foreground="#000000")
self.Label1.configure(text='''IMPORT YOUR IMAGE''')
self.Label1.configure(width=454)
self.Label2 = tk.Label(top)
self.Label2.place(relx=0.417, rely=0.778, height=51, width=254)
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(foreground="#000000")
self.Label2.configure(text='''YOUR PREDICT''')
self.Label2.configure(width=254)
# self.browse = tk.Button(top , command = lambda:onclick(2,self.Label1))
# self.browse.place(relx=0.033, rely=0.022, height=34, width=107)
# self.browse.configure(activebackground="#ececec")
# self.browse.configure(activeforeground="#000000")
# self.browse.configure(background="#d9d9d9")
# self.browse.configure(disabledforeground="#a3a3a3")
# self.browse.configure(foreground="#000000")
# self.browse.configure(highlightbackground="#d9d9d9")
# self.browse.configure(highlightcolor="black")
# self.browse.configure(pady="0")
# self.browse.configure(text='''Browse''')
# self.browse.configure(width=107)
self.capture = tk.Button(top , command = lambda:onclick(1,self.Label1,0))
self.capture.place(relx=0.033, rely=0.111, height=34, width=107)
self.capture.configure(activebackground="#ececec")
self.capture.configure(activeforeground="#000000")
self.capture.configure(background="#d9d9d9")
self.capture.configure(disabledforeground="#a3a3a3")
self.capture.configure(foreground="#000000")
self.capture.configure(highlightbackground="#d9d9d9")
self.capture.configure(highlightcolor="black")
self.capture.configure(pady="0")
self.capture.configure(text='''Capture''')
self.capture.configure(width=107)
self.knn = tk.Radiobutton(top)
self.knn.place(relx=0.05, rely=0.444, relheight=0.056, relwidth=0.08)
self.knn.configure(activebackground="#ececec")
self.knn.configure(activeforeground="#000000")
self.knn.configure(background="#d9d9d9")
self.knn.configure(disabledforeground="#a3a3a3")
self.knn.configure(foreground="#000000")
self.knn.configure(highlightbackground="#d9d9d9")
self.knn.configure(highlightcolor="black")
self.knn.configure(justify='left')
self.knn.configure(text='''knn''')
self.knn.configure(value="0")
self.knn.configure(variable=group)
self.svm = tk.Radiobutton(top)
self.svm.place(relx=0.05, rely=0.511, relheight=0.056, relwidth=0.083)
self.svm.configure(activebackground="#ececec")
self.svm.configure(activeforeground="#000000")
self.svm.configure(background="#d9d9d9")
self.svm.configure(disabledforeground="#a3a3a3")
self.svm.configure(foreground="#000000")
self.svm.configure(highlightbackground="#d9d9d9")
self.svm.configure(highlightcolor="black")
self.svm.configure(justify='left')
self.svm.configure(text='''svm''')
self.svm.configure(value="1")
self.svm.configure(variable=group)
self.cnn = tk.Radiobutton(top)
self.cnn.place(relx=0.05, rely=0.578, relheight=0.056, relwidth=0.08)
self.cnn.configure(activebackground="#ececec")
self.cnn.configure(activeforeground="#000000")
self.cnn.configure(background="#d9d9d9")
self.cnn.configure(disabledforeground="#a3a3a3")
self.cnn.configure(foreground="#000000")
self.cnn.configure(highlightbackground="#d9d9d9")
self.cnn.configure(highlightcolor="black")
self.cnn.configure(justify='left')
self.cnn.configure(text='''cnn''')
self.cnn.configure(value="2")
self.cnn.configure(variable=group)
self.predict = tk.Button(top,command = lambda:onclick(3,self.Label2,group.get()))
self.predict.place(relx=0.033, rely=0.8, height=34, width=107)
self.predict.configure(activebackground="#ececec")
self.predict.configure(activeforeground="#000000")
self.predict.configure(background="#d9d9d9")
self.predict.configure(disabledforeground="#a3a3a3")
self.predict.configure(foreground="#000000")
self.predict.configure(highlightbackground="#d9d9d9")
self.predict.configure(highlightcolor="black")
self.predict.configure(pady="0")
self.predict.configure(text='''Predict''')
self.predict.configure(width=107)
def getKnn():
# global knn
pk_out = open("Knn/Knn_model.pickle", "rb")
knn = pickle.Unpickler(pk_out)
return knn
def getsvm():
pk_out = open("svm/SVM_gamma=0.0000001,kernel='rbf',C=1000.pickle", "rb")
svm = pickle.Unpickler(pk_out)
return svm
if __name__ == '__main__':
img_counter = 0
vp_start_gui()