Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/FaceDetectionComparison/face_detection_dlib_hog.py
3118 views
1
import argparse
2
import os
3
import time
4
5
import cv2
6
import dlib
7
8
9
def detectFaceDlibHog(detector, frame, inHeight=300, inWidth=0):
10
11
frameDlibHog = frame.copy()
12
frameHeight = frameDlibHog.shape[0]
13
frameWidth = frameDlibHog.shape[1]
14
if not inWidth:
15
inWidth = int((frameWidth / frameHeight) * inHeight)
16
17
scaleHeight = frameHeight / inHeight
18
scaleWidth = frameWidth / inWidth
19
20
frameDlibHogSmall = cv2.resize(frameDlibHog, (inWidth, inHeight))
21
22
frameDlibHogSmall = cv2.cvtColor(frameDlibHogSmall, cv2.COLOR_BGR2RGB)
23
faceRects = detector(frameDlibHogSmall, 0)
24
print(frameWidth, frameHeight, inWidth, inHeight)
25
bboxes = []
26
for faceRect in faceRects:
27
28
cvRect = [
29
int(faceRect.left() * scaleWidth),
30
int(faceRect.top() * scaleHeight),
31
int(faceRect.right() * scaleWidth),
32
int(faceRect.bottom() * scaleHeight),
33
]
34
bboxes.append(cvRect)
35
cv2.rectangle(
36
frameDlibHog,
37
(cvRect[0], cvRect[1]),
38
(cvRect[2], cvRect[3]),
39
(0, 255, 0),
40
int(round(frameHeight / 150)),
41
4,
42
)
43
return frameDlibHog, 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
hogFaceDetector = dlib.get_frontal_face_detector()
54
55
outputFolder = "output-hog-videos"
56
if not os.path.exists(outputFolder):
57
os.makedirs(outputFolder)
58
59
if source:
60
cap = cv2.VideoCapture(source)
61
outputFile = os.path.basename(source)[:-4] + ".avi"
62
else:
63
cap = cv2.VideoCapture(0, cv2.CAP_V4L)
64
outputFile = "grabbed_from_camera.avi"
65
hasFrame, frame = cap.read()
66
67
vid_writer = cv2.VideoWriter(
68
os.path.join(outputFolder, outputFile),
69
cv2.VideoWriter_fourcc("M", "J", "P", "G"),
70
15,
71
(frame.shape[1], frame.shape[0]),
72
)
73
74
frame_count = 0
75
tt_dlibHog = 0
76
77
while True:
78
hasFrame, frame = cap.read()
79
if not hasFrame:
80
break
81
82
frame_count += 1
83
t = time.time()
84
85
outDlibHog, bboxes = detectFaceDlibHog(hogFaceDetector, frame)
86
tt_dlibHog += time.time() - t
87
fpsDlibHog = frame_count / tt_dlibHog
88
89
label = "DLIB HoG; FPS : {:.2f}".format(fpsDlibHog)
90
cv2.putText(
91
outDlibHog,
92
label,
93
(10, 50),
94
cv2.FONT_HERSHEY_SIMPLEX,
95
1.3,
96
(0, 0, 255),
97
3,
98
cv2.LINE_AA,
99
)
100
101
cv2.imshow("Face Detection Comparison", outDlibHog)
102
103
vid_writer.write(outDlibHog)
104
105
if frame_count == 1:
106
tt_dlibHog = 0
107
108
k = cv2.waitKey(5)
109
if k == 27:
110
break
111
112
cv2.destroyAllWindows()
113
vid_writer.release()
114
115