-
Notifications
You must be signed in to change notification settings - Fork 0
/
FaceMaskDetector.py
245 lines (187 loc) · 8.34 KB
/
FaceMaskDetector.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
import os
import tensorflow as tf
from tensorflow import keras
import numpy as np
import cv2 as cv
import cv2
import video
import datetime
import time
from PIL import Image, ImageOps
import random
import string
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
print(CURRENT_DIR)
class FaceMask:
LABELS = []
cascade = None
model = None
size = (224, 224)
def __init__(self):
self.cascade = cv2.CascadeClassifier(
os.path.join(CURRENT_DIR, "cascade.xml"))
if(self.cascade.empty()):
print("cascade empty")
self.getLabels()
modelFile = os.path.join(CURRENT_DIR, "keras_model.h5")
if(os.path.exists(modelFile)):
self.model = tf.keras.models.load_model(modelFile)
#data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
np.set_printoptions(suppress=True)
####################################################################################################
def getLabels(self):
with open(os.path.join(CURRENT_DIR, "labels_facemask.txt"), 'r') as file:
for x in file:
self.LABELS.append(str(x).replace("\n", ""))
print(self.LABELS)
####################################################################################################
def TFpredictImgPath(self, imgePath):
pilImg = Image.load_img(imgePath)
return self.TFpredictPilImg(pilImg)
####################################################################################################
def TFpredictPilImg(self, pilImg):
if(self.model == None):
print("model is null")
return None
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
# resize the image to a 224x224 with the same strategy as in TM2:
# resizing the image to be at least 224x224 and then cropping from the center
image = ImageOps.fit(pilImg, self.size, Image.ANTIALIAS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
# Load the image into the array
data[0] = normalized_image_array
# run the inference
predictions = self.model.predict(data)
result = np.argmax(predictions)
return result, np.max(predictions)
####################################################################################################
def PredictMat(self, mat):
img = cv.cvtColor(mat, cv.COLOR_BGR2RGB)
img = cv.resize(img, self.size)
img_pil = Image.fromarray(img)
result, acc = self.TFpredictPilImg(img_pil)
return result, acc
####################################################################################################
def DetectFaceInFrame(self, frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#gray = cv2.equalizeHist(gray)
newWidth = int(gray.shape[1] / 2)
newHeight = int(gray.shape[0] / 2)
gray = cv2.resize(gray, (newWidth, newHeight))
rects = self.cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=3, flags=cv2.CASCADE_SCALE_IMAGE, minSize=(20, 20))
if(len(rects) > 0):
rects[:, 2:] += rects[:, :2]
for r in rects:
r[0] *= 2
r[1] *= 2
r[2] *= 2
r[3] *= 2
return rects
####################################################################################################
def CropMat(self, frame, rect):
x = rect[0]
y = rect[1]
w = rect[2] - x
h = rect[3] - y
frame = frame[y:h, x:w]
return frame
####################################################################################################
def GenerateRandomString(self):
return ''.join(random.choices(string.ascii_lowercase + "_" + string.ascii_uppercase + string.digits, k=10))
####################################################################################################
def DetectMask(self, frame):
startTime = time.time()
saveImage = False # to debug
result = ''
rects = self.DetectFaceInFrame(frame)
arr = []
if(len(rects) > 0):
rects[:, 2:] += rects[:, :2]
for rect in rects:
# print(rect)
matFace = self.CropMat(frame, rect)
predicted, acc = self.PredictMat(matFace)
result = self.LABELS[predicted]
color = (0, 0, 255)
x1 = rect[0]
y1 = rect[1]
x2 = rect[2] - x1
y2 = rect[3] - y1
elapsed = time.time() - startTime
if(saveImage):
cv2.imwrite(result + "\\" + datetime.datetime.utcnow().strftime(
"%Y-%m-%d_%H-%M-%S") + "_" + self.GenerateRandomString() + ".jpg", matFace)
arr.append(result)
if(result == "Mask"):
color = (0, 255, 0)
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
elif(result == "Hand" or result == "No mask" or result == "Wrong"):
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
if(result != "Nothing"):
cv.putText(frame, str(result), (10, 60),
cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
cv.putText(frame, str(round(acc, 2)) + '%', (400, 60),
cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
# cv.putText(frame, "{:10.2f} s".format(
# elapsed), (300, 60), cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
else:
if(saveImage):
cv2.imwrite("noface\\" + datetime.datetime.utcnow().strftime(
"%Y-%m-%d_%H-%M-%S") + "_" + self.GenerateRandomString() + ".jpg", frame)
return frame, arr, result
####################################################################################################
def detect_mask_no_return_frame(self,frame):
startTime = time.time()
saveImage = False # to debug
result = ''
rects = self.DetectFaceInFrame(frame)
if (len(rects) > 0):
rects[:, 2:] += rects[:, :2]
for rect in rects:
# print(rect)
matFace = self.CropMat(frame, rect)
predicted, acc = self.PredictMat(matFace)
result = self.LABELS[predicted]
color = (0, 0, 255)
x1 = rect[0]
y1 = rect[1]
x2 = rect[2] - x1
y2 = rect[3] - y1
elapsed = time.time() - startTime
# if (saveImage):
# cv2.imwrite(result + "\\" + datetime.datetime.utcnow().strftime(
# "%Y-%m-%d_%H-%M-%S") + "_" + self.GenerateRandomString() + ".jpg", matFace)
#
#
# if (result == "Mask"):
# color = (0, 255, 0)
# cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
# elif (result == "Hand" or result == "No mask" or result == "Wrong"):
# cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
#
# if (result != "Nothing"):
# cv.putText(frame, str(result), (10, 60),
# cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
# cv.putText(frame, str(round(acc, 2)) + '%', (400, 60),
# cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
# # cv.putText(frame, "{:10.2f} s".format(
# # elapsed), (300, 60), cv.FONT_HERSHEY_PLAIN, 3, color, thickness=2)
# else:
if (saveImage):
cv2.imwrite("noface\\" + datetime.datetime.utcnow().strftime(
"%Y-%m-%d_%H-%M-%S") + "_" + self.GenerateRandomString() + ".jpg", frame)
return result
# faceMask = FaceMask()
# if __name__ == '__main__':
# cap = video.create_capture(0)
# while True:
# _ret, frame = cap.read()
# frame, arr, result = faceMask.DetectMask(frame)
# cv.imshow('frame', frame)
# ch = cv.waitKey(20)
# if ch == 27:
# break