-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain_desktop.py
243 lines (197 loc) · 8.28 KB
/
main_desktop.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
from imutils import face_utils #for resizing
import numpy as np
import argparse
import imutils
import dlib
import cv2
import time
from scipy.spatial import distance as dist #euclidian distance
import pandas as pd
import csv
from pathlib import Path
csv_columns = ['name', 'face_data']
csv_file = 'all_face_data.csv'
camera_id = 0
EAR_AR_THRESH = 0.3
CONSEC_FRAMES = 1
TOTAL = 0
COUNT = 0
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
print('App is preparing, please wait.')
detector = dlib.get_frontal_face_detector() # detect the faces in the image. How many faces are there
predictor = dlib.shape_predictor('./shape_predictor_68_face_landmarks.dat') # predict the face landmarks such as mouth or eyes
#(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
#(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
facerec = dlib.face_recognition_model_v1('./dlib_face_recognition_resnet_model_v1.dat') #pretrained model.
#we send the data to this function and it returns a 128D vector that described the faces.
def eye_aspect_ratio(eye):
#https://www.pyimagesearch.com/wp-content/uploads/2017/04/blink_detection_plot.jpg
a = dist.euclidean(eye[1], eye[5])
b = dist.euclidean(eye[2], eye[4])
c = dist.euclidean(eye[0], eye[3])
ear = (a+b) / (2.0 * c)
return ear
def write_dict_to_csv(csv_file, csv_columns, dict_data):
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
#writer.writeheader()
for key, value in dict_data.items():
writer.writerow({'name': key, 'face_data': value})
except IOError:
print("I/O error", csv_file)
return
def append_to_csv(csvfile, data):
with open(csvfile, 'a') as f:
writer = csv.writer(f)
for key, value in data.items():
writer.writerow([key,value])
return
def cvt_to_array(data, split_with=''):
if split_with == '':
return np.array(list(map(float, data)))
else:
return np.array(list(map(float, data.split(split_with))))
def menu():
print('Welcome to face recognition system. What do you want to do?\n')
action = 0
while action != 3:
print('1) Run the app\n')
print('2) Save new face to database\n')
print('3) Exit\n')
action = int(input('>>'))
if action == 1:
run_app()
elif action == 2:
save_face()
def run_app():
global COUNT, TOTAL
found_face = 0
cap = cv2.VideoCapture(camera_id)
while True:
ret, image = cap.read()
image = imutils.resize(image, width=300)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
if found_face % 5 == 0:
rects = detector(gray, 0)
for (i, rect) in enumerate(rects):
# determine the facial landmarks for the face region, then
# convert the landmark (x, y)-coordinates to a NumPy array
shape = predictor(gray, rect)
trying = np.array(facerec.compute_face_descriptor(image, shape))
#distance_faces = dist.euclidean(face_data, trying)
my_file = Path("./" + csv_file)
with open(my_file, 'r') as f:
reader = csv.reader(f)
for row in reader:
if row == [] or row[1] == "face_data":
continue
else:
#row[1] = np.array(list(map(float, row[1].split('\n'))))
row[1] = cvt_to_array(row[1], '\n')
trying = cvt_to_array(trying)
distance_faces = dist.euclidean(row[1], trying)
if distance_faces < 0.55:
content = row[0]
break
else:
content = "unknown"
cv2.putText(image,content, (10,40), cv2.FONT_HERSHEY_PLAIN, 1, (0,255,0), 2)
shape = face_utils.shape_to_np(shape)
for (x, y) in shape:
cv2.circle(image, (x, y), 1, (0, 0, 255), -1)
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
leftEyeHull = cv2.convexHull(leftEye)
rightEyeHull = cv2.convexHull(rightEye)
cv2.drawContours(image, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(image, [rightEyeHull], -1, (0, 255, 0), 1)
ear = (leftEAR + rightEAR) / 2.0
if ear < EAR_AR_THRESH:
COUNT += 1
else:
if COUNT >= CONSEC_FRAMES:
TOTAL += 1
COUNT = 0
cv2.putText(image, "Blinks: {}".format(TOTAL), (300, 40),cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
#break
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
#time.sleep(0.1)
cap.release()
cv2.destroyAllWindows()
def save_face():
#capture the person and save as the 128D vector
# this part captures only once
cap = cv2.VideoCapture(camera_id)
#while True:
face_data = []
labels = []
data = {}
face_number = 0
while face_number == 0:
print('Please show your whole face to camera. When the face is detected, you will be asked for the name.')
time.sleep(0.5)
ret, image = cap.read()
image = imutils.resize(image, width=500) #resizing
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #it should convert to gray in onder to improve resultt.
rects = detector(gray, 0) # detect how many faces in the image
for (i, rect) in enumerate(rects):
# for every faces
# determine the facial landmarks for the face region, then
# convert the landmark (x, y)-coordinates to a NumPy array
shape = predictor(gray, rect) # predict the face landmarks in image.
face_descriptor = facerec.compute_face_descriptor(image, shape) # send the shape data to resnet model. it returns a 128D vector
while face_descriptor == -1:
print('Face not found.')
else:
face_data.append(face_descriptor) # save the face data to array
shape = face_utils.shape_to_np(shape)
for (x, y) in shape:
cv2.circle(image, (x, y), 1, (0, 0, 255), -1)
name = str(input('Who is this : '))
while (not name.isalpha or name == ''):
print('Please enter a valid name.')
name = str(input('Who is this : '))
labels.append(name)
data[labels[0]] = face_data[0]
face_data=[]
labels=[]
my_file = Path("./" + csv_file)
if my_file.is_file():
append_to_csv(csv_file, data)
print('File already exist, data is appended to file')
else:
write_dict_to_csv(csv_file, csv_columns, data)
print('File has been created and data saved to file.')
face_number += 1
#print(face_descriptor)
'''
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
leftEyeHull = cv2.convexHull(leftEye)
rightEyeHull = cv2.convexHull(rightEye)
cv2.drawContours(image, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(image, [rightEyeHull], -1, (0, 255, 0), 1)
ear = (leftEAR + rightEAR) / 2.0
'''
cv2.imshow("Saved face", image)
cv2.waitKey(0)
#key = cv2.waitKey(1) & 0xFF
#break
# if the `q` key was pressed, break from the loop
#if key == ord("q"):
# break
#time.sleep(0.5)
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
menu()