-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFaceRecg.py
228 lines (165 loc) · 8.99 KB
/
FaceRecg.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
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 3 15:17:31 2020
@author: K B PRANAV
"""
import numpy as np # linear algebra
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense,Dropout
from keras.preprocessing.image import ImageDataGenerator, img_to_array,load_img,array_to_img
from keras.callbacks import ModelCheckpoint
import time
import cv2
import tkinter as tk
class FaceRecg:
def __init__(self):
self.init_gui()
def Load_model_arch(self):
# Initialising the CNN
self.classifier = Sequential()
# Step 1 - Convolution
self.classifier.add(Conv2D(32, (2, 2), input_shape = (150, 150, 3), activation = 'relu'))
# Step 2 - Pooling
self.classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
self.classifier.add(Conv2D(64, (2, 2), activation = 'relu'))
self.classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a third convolutional layer
self.classifier.add(Conv2D(128, (2, 2), activation = 'relu'))
self.classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a fourth convolutional layer
self.classifier.add(Conv2D(128, (2, 2), activation = 'relu'))
self.classifier.add(MaxPooling2D(pool_size = (2, 2)))
self.classifier.add(Flatten())
self.classifier.add(Dense(units = 64, activation = 'relu'))
self.classifier.add(Dropout(0.5))
self.classifier.add(Dense(units = 4, activation = 'softmax'))
# Compiling the CNN
self.classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
print("\n[INFO]Architecture Loaded...")
def detect_face(self):
cap1 = cv2.VideoCapture(0)
time.sleep(2)
print("\n Starting face detection...")
while(True):
#name+=1
ret1,frame1 = cap1.read()
frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
original_image = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
##cv.imshow('gIMG',grayscale_image)
# Load the classifier and create a cascade object for face detection
# Paste the destination of 'haarcascade_frontalface_alt.xml' available in opencv folder on your pc
face_cascade = cv2.CascadeClassifier('C:\opencv\sources\samples\winrt\FaceDetection\FaceDetection\Assets\haarcascade_frontalface_alt.xml')
detected_faces = face_cascade.detectMultiScale(original_image)
for (column, row, width, height) in detected_faces:
cv2.rectangle(
original_image,
(column, row),
(column + width, row + height),
(255, 0, 0),
2
)
print("Number of faces detected:",len(detected_faces))
print("press 'q' to exit")
cv2.imshow('Frame',original_image)
key = cv2.waitKey(1)&0xFF
if(key==ord('q')):
break
cap1.release()
cv2.destroyAllWindows()
def preview_ImageDataGen():
datagen = ImageDataGenerator(
rotation_range=40,width_shift_range=0.2,
height_shift_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
img= load_img('img.jpg')
x=img_to_array(img)
x=x.reshape((1,)+ x.shape)
i=0
for batch in datagen.flow(x,batch_size=1, save_to_dir='\preview', save_prefix='face', save_format='jpg'):
i+=1
if(i>10):
break
def train_model(self):
batch_size=32
train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2, zoom_range = 0.2,horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory(r"\dataset\train",target_size = (150, 150), batch_size = 32,class_mode='categorical')
test_set = test_datagen.flow_from_directory(r"\dataset\test" ,target_size = (150, 150), batch_size = 32,class_mode = 'categorical')
#filepath = "Trained_Weights.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
start=time.time()
print("\n Training started.....")
self.classifier.fit_generator(training_set,
steps_per_epoch = 798//batch_size,
epochs = 10,
validation_data = test_set,
validation_steps = 204//batch_size,
callbacks = [checkpoint])
end=time.time()
self.classifier.save("Trained_model")
print("\n[INFO]Trained Successfully...")
print('Time to train:',(end-start)," seconds.")
def load_trained_model(self):
self.classifier.load_weights('Trained_model')
print("\n[INFO]Model Loaded Successfully...")
def recognize(self):
#Initiate the camera
cap1 = cv2.VideoCapture(0)
print("Starting Camera...")
# Paste the destination of 'haarcascade_frontalface_alt.xml' available in opencv folder on your pc
face_cascade = cv2.CascadeClassifier('C:\opencv\sources\samples\winrt\FaceDetection\FaceDetection\Assets\haarcascade_frontalface_alt.xml')
time.sleep(2)
while(True):
ret1,frame1 = cap1.read()
frame1 = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
original_image = cv2.cvtColor(frame1, cv2.COLOR_BGR2RGB)
detected_faces = face_cascade.detectMultiScale(original_image)
faces=[]
for (column, row, width, height) in detected_faces:
cv2.rectangle(original_image,(column, row),(column + width, row + height),(255, 0, 0),2)
crop_img = original_image[row-3:row + height+3,column-3:column+width+3]
crop_img=cv2.resize(crop_img,(150,150))
faces.append(crop_img)
for i in range(len(faces)):
(column, row, width, height)=detected_faces[i]
test_image = np.expand_dims(faces[i], axis = 0)
result = self.classifier.predict(test_image)
if(result[0][0]==1):
text="class 1"
elif(result[0][1]==1):
text="class 2"
elif(result[0][2]==1):
text="class 3"
else:
text="class 4"
#original_image = cv2.putText(original_image,result,(row,column))
print("Detected class",text,result[0])
cv2.putText(original_image,text,(column-5,row-5),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,0,0),1)
cv2.imshow('Face Recognition', original_image)
key = cv2.waitKey(1)&0xFF
if(key==ord('q')):
break
cap1.release()
cv2.destroyAllWindows()
def init_gui(self):
window= tk.Tk()
self.btn_arch = tk.Button(window, text="Load Architecture", width=50, command=lambda:self.Load_model_arch())
self.btn_arch.pack(anchor=tk.CENTER, expand=True)
self.btn_arch = tk.Button(window, text="Check Face Detection", width=50, command=lambda:self.detect_face())
self.btn_arch.pack(anchor=tk.CENTER, expand=True)
#self.btn_arch = tk.Button(window, text="Image Data gen", width=50, command=lambda:self.preview_ImageDataGen())
#self.btn_arch.pack(anchor=tk.CENTER, expand=True)
self.btn_train = tk.Button(window ,text="Train Model", width=50, command=lambda: self.train_model())
self.btn_train.pack(anchor=tk.CENTER, expand=True)
self.btn_load = tk.Button(window,text="Load Trained Model", width=50, command=lambda: self.load_trained_model())
self.btn_load.pack(anchor=tk.CENTER, expand=True)
self.btn_detect = tk.Button(window,text="Recognize faces", width=50, command=lambda: self.recognize())
self.btn_detect.pack(anchor=tk.CENTER, expand=True)
window.mainloop()
FaceRecg()