Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/FaceDetectionComparison/face_detection_dlib_mmod.py
3118 views
1
import argparse
2
import os
3
import time
4
5
import cv2
6
import dlib
7
8
9
def detectFaceDlibMMOD(detector, frame, inHeight=300, inWidth=0):
10
11
frameDlibMMOD = frame.copy()
12
frameHeight = frameDlibMMOD.shape[0]
13
frameWidth = frameDlibMMOD.shape[1]
14
if not inWidth:
15
inWidth = int((frameWidth / frameHeight) * inHeight)
16
17
scaleHeight = frameHeight / inHeight
18
scaleWidth = frameWidth / inWidth
19
20
frameDlibMMODSmall = cv2.resize(frameDlibMMOD, (inWidth, inHeight))
21
22
frameDlibMMODSmall = cv2.cvtColor(frameDlibMMODSmall, cv2.COLOR_BGR2RGB)
23
faceRects = detector(frameDlibMMODSmall, 0)
24
25
print(frameWidth, frameHeight, inWidth, inHeight)
26
bboxes = []
27
for faceRect in faceRects:
28
cvRect = [
29
int(faceRect.rect.left() * scaleWidth),
30
int(faceRect.rect.top() * scaleHeight),
31
int(faceRect.rect.right() * scaleWidth),
32
int(faceRect.rect.bottom() * scaleHeight),
33
]
34
bboxes.append(cvRect)
35
cv2.rectangle(
36
frameDlibMMOD,
37
(cvRect[0], cvRect[1]),
38
(cvRect[2], cvRect[3]),
39
(0, 255, 0),
40
int(round(frameHeight / 150)),
41
4,
42
)
43
return frameDlibMMOD, bboxes
44
45
46
if __name__ == "__main__":
47
48
parser = argparse.ArgumentParser(description="Face detection")
49
parser.add_argument("--video", type=str, default="", help="Path to video file")
50
args = parser.parse_args()
51
52
source = args.video
53
54
mmodFaceDetector = dlib.cnn_face_detection_model_v1(
55
"models/mmod_human_face_detector.dat",
56
)
57
58
outputFolder = "output-mmod-videos"
59
if not os.path.exists(outputFolder):
60
os.makedirs(outputFolder)
61
62
if source:
63
cap = cv2.VideoCapture(source)
64
outputFile = os.path.basename(source)[:-4] + ".avi"
65
else:
66
cap = cv2.VideoCapture(0, cv2.CAP_V4L)
67
outputFile = "grabbed_from_camera.avi"
68
69
hasFrame, frame = cap.read()
70
71
vid_writer = cv2.VideoWriter(
72
os.path.join(outputFolder, outputFile),
73
cv2.VideoWriter_fourcc("M", "J", "P", "G"),
74
15,
75
(frame.shape[1], frame.shape[0]),
76
)
77
78
frame_count = 0
79
tt_dlibMmod = 0
80
81
while True:
82
hasFrame, frame = cap.read()
83
if not hasFrame:
84
break
85
86
frame_count += 1
87
t = time.time()
88
89
outDlibMMOD, bboxes = detectFaceDlibMMOD(mmodFaceDetector, frame)
90
tt_dlibMmod += time.time() - t
91
fpsDlibMmod = frame_count / tt_dlibMmod
92
93
label = "DLIB MMOD; FPS : {:.2f}".format(fpsDlibMmod)
94
cv2.putText(
95
outDlibMMOD,
96
label,
97
(10, 50),
98
cv2.FONT_HERSHEY_SIMPLEX,
99
1.3,
100
(0, 0, 255),
101
3,
102
cv2.LINE_AA,
103
)
104
105
cv2.imshow("Face Detection Comparison", outDlibMMOD)
106
107
vid_writer.write(outDlibMMOD)
108
109
if frame_count == 1:
110
tt_dlibMmod = 0
111
112
k = cv2.waitKey(5)
113
if k == 27:
114
break
115
116
cv2.destroyAllWindows()
117
vid_writer.release()
118
119