Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
hackassin
GitHub Repository: hackassin/learnopencv
Path: blob/master/FaceDetectionComparison/face_detection_opencv_haar.py
3118 views
1
import argparse
2
import os
3
import time
4
5
import cv2
6
7
8
def detectFaceOpenCVHaar(faceCascade, frame, inHeight=300, inWidth=0):
9
frameOpenCVHaar = frame.copy()
10
frameHeight = frameOpenCVHaar.shape[0]
11
frameWidth = frameOpenCVHaar.shape[1]
12
if not inWidth:
13
inWidth = int((frameWidth / frameHeight) * inHeight)
14
15
scaleHeight = frameHeight / inHeight
16
scaleWidth = frameWidth / inWidth
17
18
frameOpenCVHaarSmall = cv2.resize(frameOpenCVHaar, (inWidth, inHeight))
19
frameGray = cv2.cvtColor(frameOpenCVHaarSmall, cv2.COLOR_BGR2GRAY)
20
21
faces = faceCascade.detectMultiScale(frameGray)
22
bboxes = []
23
for (x, y, w, h) in faces:
24
x1 = x
25
y1 = y
26
x2 = x + w
27
y2 = y + h
28
cvRect = [
29
int(x1 * scaleWidth),
30
int(y1 * scaleHeight),
31
int(x2 * scaleWidth),
32
int(y2 * scaleHeight),
33
]
34
bboxes.append(cvRect)
35
cv2.rectangle(
36
frameOpenCVHaar,
37
(cvRect[0], cvRect[1]),
38
(cvRect[2], cvRect[3]),
39
(0, 255, 0),
40
int(round(frameHeight / 150)),
41
4,
42
)
43
return frameOpenCVHaar, bboxes
44
45
46
if __name__ == "__main__":
47
parser = argparse.ArgumentParser(description="Face detection")
48
parser.add_argument("--video", type=str, default="", help="Path to video file")
49
args = parser.parse_args()
50
51
source = args.video
52
53
faceCascade = cv2.CascadeClassifier("models/haarcascade_frontalface_default.xml")
54
55
outputFolder = "output-haar-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
66
hasFrame, frame = cap.read()
67
68
vid_writer = cv2.VideoWriter(
69
os.path.join(outputFolder, outputFile),
70
cv2.VideoWriter_fourcc("M", "J", "P", "G"),
71
25,
72
(frame.shape[1], frame.shape[0]),
73
)
74
75
frame_count = 0
76
tt_opencvHaar = 0
77
78
while True:
79
hasFrame, frame = cap.read()
80
if not hasFrame:
81
break
82
83
frame_count += 1
84
t = time.time()
85
86
outOpencvHaar, bboxes = detectFaceOpenCVHaar(faceCascade, frame)
87
tt_opencvHaar += time.time() - t
88
fpsOpencvHaar = frame_count / tt_opencvHaar
89
90
label = "OpenCV Haar; FPS : {:.2f}".format(fpsOpencvHaar)
91
cv2.putText(
92
outOpencvHaar,
93
label,
94
(10, 50),
95
cv2.FONT_HERSHEY_SIMPLEX,
96
1.3,
97
(0, 0, 255),
98
3,
99
cv2.LINE_AA,
100
)
101
102
cv2.imshow("Face Detection Comparison", outOpencvHaar)
103
104
vid_writer.write(outOpencvHaar)
105
if frame_count == 1:
106
tt_opencvHaar = 0
107
108
key = cv2.waitKey(5)
109
if key == 27:
110
break
111
112
cv2.destroyAllWindows()
113
vid_writer.release()
114
115