Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from utils import create_model, get_optimal_font_scale
|
2 |
+
from mtcnn import MTCNN
|
3 |
+
import cv2
|
4 |
+
import gradio as gr
|
5 |
+
from PIL import Image
|
6 |
+
import gradio
|
7 |
+
|
8 |
+
model = create_model()
|
9 |
+
checkpoint_path = "best_model_weights/checkpoint.ckpt"
|
10 |
+
model.load_weights(checkpoint_path)
|
11 |
+
|
12 |
+
detector = MTCNN()
|
13 |
+
|
14 |
+
def face_mask_detection(image):
|
15 |
+
img = image.copy()
|
16 |
+
(h,w) = img.shape[:2]
|
17 |
+
objects = detector.detect_faces(img) # https://github.com/ipazc/mtcnn/blob/master/example.ipynb
|
18 |
+
|
19 |
+
for obj in objects:
|
20 |
+
x, y, width, height = obj['box']
|
21 |
+
startX, startY, endX, endY = x, y, x+width, y+height
|
22 |
+
|
23 |
+
#ensure the bounding boxes fall within the dimensions of the frame
|
24 |
+
(startX,startY)=(max(0,startX),max(0,startY))
|
25 |
+
(endX,endY)=(min(w-1,endX), min(h-1,endY))
|
26 |
+
|
27 |
+
|
28 |
+
#extract the face ROI, convert it from BGR to RGB channel, resize it to 224,224 and preprocess it
|
29 |
+
face=img[startY:endY, startX:endX]
|
30 |
+
face=cv2.resize(face,(224,224))
|
31 |
+
|
32 |
+
|
33 |
+
|
34 |
+
probs = model.predict(face.reshape(1,224,224,3))[0][0] # example: result of model.predict: [[0.823] then < 0.5 -> mask, > 0.5 -> without mask
|
35 |
+
is_masked = probs < 0.5
|
36 |
+
|
37 |
+
#determine the class label and color we will use to draw the bounding box and text
|
38 |
+
label='Mask' if is_masked else 'No Mask'
|
39 |
+
color=(0,255,0) if label=='Mask' else (0,0,255)
|
40 |
+
|
41 |
+
#include the probability in the label
|
42 |
+
confidence = probs if probs > 0.5 else (1-probs)
|
43 |
+
label="{}: {:.2f}%".format(label,confidence*100)
|
44 |
+
|
45 |
+
#display the label and bounding boxes
|
46 |
+
fontScale = get_optimal_font_scale(label, endX-startX)
|
47 |
+
cv2.putText(img,label,(startX+5,startY+15),cv2.FONT_HERSHEY_SIMPLEX,fontScale,color,1)
|
48 |
+
cv2.rectangle(img,(startX,startY),(endX,endY),color,1)
|
49 |
+
|
50 |
+
return Image.fromarray(img)
|
51 |
+
|
52 |
+
gr.Interface(fn=face_mask_detection,
|
53 |
+
inputs=gr.Image(shape=(224, 224)),
|
54 |
+
outputs=gr.outputs.Image(type = "pil", label = "Output Image")).launch()
|