Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/FaceDetectionComparison/face_detection_opencv_dnn.py
3118 views
1
import argparse
2
import os
3
import time
4
5
import cv2
6
7
8
def detectFaceOpenCVDnn(net, frame, framework="caffe", conf_threshold=0.7):
9
frameOpencvDnn = frame.copy()
10
frameHeight = frameOpencvDnn.shape[0]
11
frameWidth = frameOpencvDnn.shape[1]
12
if framework == "caffe":
13
blob = cv2.dnn.blobFromImage(
14
frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False,
15
)
16
else:
17
blob = cv2.dnn.blobFromImage(
18
frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], True, False,
19
)
20
21
net.setInput(blob)
22
detections = net.forward()
23
bboxes = []
24
for i in range(detections.shape[2]):
25
confidence = detections[0, 0, i, 2]
26
if confidence > conf_threshold:
27
x1 = int(detections[0, 0, i, 3] * frameWidth)
28
y1 = int(detections[0, 0, i, 4] * frameHeight)
29
x2 = int(detections[0, 0, i, 5] * frameWidth)
30
y2 = int(detections[0, 0, i, 6] * frameHeight)
31
bboxes.append([x1, y1, x2, y2])
32
cv2.rectangle(
33
frameOpencvDnn,
34
(x1, y1),
35
(x2, y2),
36
(0, 255, 0),
37
int(round(frameHeight / 150)),
38
8,
39
)
40
return frameOpencvDnn, bboxes
41
42
43
if __name__ == "__main__":
44
45
parser = argparse.ArgumentParser(description="Face detection")
46
parser.add_argument("--video", type=str, default="", help="Path to video file")
47
parser.add_argument(
48
"--device",
49
type=str,
50
default="cpu",
51
choices=["cpu", "gpu"],
52
help="Device to use",
53
)
54
parser.add_argument(
55
"--framework",
56
type=str,
57
default="caffe",
58
choices=["caffe", "tf"],
59
help="Type of network to run",
60
)
61
args = parser.parse_args()
62
63
framework = args.framework
64
source = args.video
65
device = args.device
66
67
# OpenCV DNN supports 2 networks.
68
# 1. FP16 version of the original Caffe implementation ( 5.4 MB )
69
# 2. 8 bit Quantized version using TensorFlow ( 2.7 MB )
70
71
if framework == "caffe":
72
modelFile = "models/res10_300x300_ssd_iter_140000_fp16.caffemodel"
73
configFile = "models/deploy.prototxt"
74
net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
75
else:
76
modelFile = "models/opencv_face_detector_uint8.pb"
77
configFile = "models/opencv_face_detector.pbtxt"
78
net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
79
80
if device == "cpu":
81
net.setPreferableBackend(cv2.dnn.DNN_TARGET_CPU)
82
else:
83
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
84
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
85
86
outputFolder = "output-dnn-videos"
87
if not os.path.exists(outputFolder):
88
os.makedirs(outputFolder)
89
90
if source:
91
cap = cv2.VideoCapture(source)
92
outputFile = os.path.basename(source)[:-4] + ".avi"
93
else:
94
cap = cv2.VideoCapture(0, cv2.CAP_V4L)
95
outputFile = "grabbed_from_camera.avi"
96
97
hasFrame, frame = cap.read()
98
99
vid_writer = cv2.VideoWriter(
100
os.path.join(outputFolder, outputFile),
101
cv2.VideoWriter_fourcc("M", "J", "P", "G"),
102
15,
103
(frame.shape[1], frame.shape[0]),
104
)
105
106
frame_count = 0
107
tt_opencvDnn = 0
108
109
while True:
110
hasFrame, frame = cap.read()
111
if not hasFrame:
112
break
113
114
frame_count += 1
115
t = time.time()
116
117
outOpencvDnn, bboxes = detectFaceOpenCVDnn(net, frame)
118
tt_opencvDnn += time.time() - t
119
fpsOpencvDnn = frame_count / tt_opencvDnn
120
121
label = "OpenCV DNN {} FPS : {:.2f}".format(device.upper(), fpsOpencvDnn)
122
cv2.putText(
123
outOpencvDnn,
124
label,
125
(10, 50),
126
cv2.FONT_HERSHEY_SIMPLEX,
127
1.3,
128
(0, 0, 255),
129
3,
130
cv2.LINE_AA,
131
)
132
133
cv2.imshow("Face Detection Comparison", outOpencvDnn)
134
135
vid_writer.write(outOpencvDnn)
136
137
if frame_count == 1:
138
tt_opencvDnn = 0
139
140
k = cv2.waitKey(5)
141
if k == 27:
142
break
143
144
cv2.destroyAllWindows()
145
vid_writer.release()
146
147