-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
81 lines (63 loc) · 2.82 KB
/
app.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
from flask import Flask, render_template, request,redirect
import cv2
import numpy as np
app = Flask(__name__)
@app.route("/",methods=['GET','POST'])
def detect_mask():
if request.method=='POST':
neural_net = cv2.dnn.readNet('yolov3_training_last.weights', 'yolov3_testing.cfg')
classes = []
with open("classes.txt", "r") as f:
classes = f.read().splitlines()
cap=cv2.VideoCapture(0)
if not cap.isOpened():
cap=cv2.VideoCapture(1)
if not cap.isOpened():
raise IOError("Cannot open webcam")
font = cv2.FONT_HERSHEY_PLAIN
while True:
_, img = cap.read()
height, width, _ = img.shape
treat_img= cv2.dnn.blobFromImage(img, 1/255, (416, 416), (0,0,0), swapRB=True, crop=False)
neural_net.setInput(treat_img)
output_layers_names = neural_net.getUnconnectedOutLayersNames()
layerOutputs = neural_net.forward(output_layers_names)
bounding_boxes = []
probabilities = []
class_labels = []
for output in layerOutputs:
for detection in output:
prob_values=detection[5:]
class_label=np.argmax(prob_values)
class_probabilitiy=prob_values[class_label]
if class_probabilitiy > 0.2:
center_x = int(detection[0]*width)
center_y = int(detection[1]*height)
w = int(detection[2]*width)
h = int(detection[3]*height)
x = int(center_x - w/2)
y = int(center_y - h/2)
bounding_boxes.append([x, y, w, h])
probabilities.append((float(class_probabilitiy)))
class_labels.append(class_label)
indexes = cv2.dnn.NMSBoxes(bounding_boxes, probabilities, 0.2, 0.4)
if len(indexes)>0:
for i in indexes.flatten():
x, y, w, h = bounding_boxes[i]
label = str(classes[class_labels[i]])
class_probabilitiy =str((round(probabilities[i],2))*100)
if class_labels[i]==0:
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.putText(img, label, (x, y+20), font, 1, (0,255,0), 1)
else:
cv2.rectangle(img, (x,y), (x+w, y+h), (0,0,255), 2)
cv2.putText(img, label, (x, y+20), font, 1, (0,0,255), 1)
cv2.imshow('Webcam For Face Mask Detection', img)
key = cv2.waitKey(1)
if key==27:
break
cap.release()
cv2.destroyAllWindows()
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True,port=8000)