Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
vardanagarwal
GitHub Repository: vardanagarwal/Proctoring-AI
Path: blob/master/face_detector.py
453 views
1
# -*- coding: utf-8 -*-
2
"""
3
Created on Wed Jul 29 17:52:00 2020
4
5
@author: hp
6
"""
7
8
import cv2
9
import numpy as np
10
11
def get_face_detector(modelFile=None,
12
configFile=None,
13
quantized=False):
14
"""
15
Get the face detection caffe model of OpenCV's DNN module
16
17
Parameters
18
----------
19
modelFile : string, optional
20
Path to model file. The default is "models/res10_300x300_ssd_iter_140000.caffemodel" or models/opencv_face_detector_uint8.pb" based on quantization.
21
configFile : string, optional
22
Path to config file. The default is "models/deploy.prototxt" or "models/opencv_face_detector.pbtxt" based on quantization.
23
quantization: bool, optional
24
Determines whether to use quantized tf model or unquantized caffe model. The default is False.
25
26
Returns
27
-------
28
model : dnn_Net
29
30
"""
31
if quantized:
32
if modelFile == None:
33
modelFile = "models/opencv_face_detector_uint8.pb"
34
if configFile == None:
35
configFile = "models/opencv_face_detector.pbtxt"
36
model = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
37
38
else:
39
if modelFile == None:
40
modelFile = "models/res10_300x300_ssd_iter_140000.caffemodel"
41
if configFile == None:
42
configFile = "models/deploy.prototxt"
43
model = cv2.dnn.readNetFromCaffe(configFile, modelFile)
44
return model
45
46
def find_faces(img, model):
47
"""
48
Find the faces in an image
49
50
Parameters
51
----------
52
img : np.uint8
53
Image to find faces from
54
model : dnn_Net
55
Face detection model
56
57
Returns
58
-------
59
faces : list
60
List of coordinates of the faces detected in the image
61
62
"""
63
h, w = img.shape[:2]
64
blob = cv2.dnn.blobFromImage(cv2.resize(img, (300, 300)), 1.0,
65
(300, 300), (104.0, 177.0, 123.0))
66
model.setInput(blob)
67
res = model.forward()
68
faces = []
69
for i in range(res.shape[2]):
70
confidence = res[0, 0, i, 2]
71
if confidence > 0.5:
72
box = res[0, 0, i, 3:7] * np.array([w, h, w, h])
73
(x, y, x1, y1) = box.astype("int")
74
faces.append([x, y, x1, y1])
75
return faces
76
77
def draw_faces(img, faces):
78
"""
79
Draw faces on image
80
81
Parameters
82
----------
83
img : np.uint8
84
Image to draw faces on
85
faces : List of face coordinates
86
Coordinates of faces to draw
87
88
Returns
89
-------
90
None.
91
92
"""
93
for x, y, x1, y1 in faces:
94
cv2.rectangle(img, (x, y), (x1, y1), (0, 0, 255), 3)
95
96