Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/python/test/test_facedetect.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
face detection using haar cascades
5
'''
6
7
# Python 2/3 compatibility
8
from __future__ import print_function
9
10
import numpy as np
11
import cv2 as cv
12
13
def detect(img, cascade):
14
rects = cascade.detectMultiScale(img, scaleFactor=1.275, minNeighbors=4, minSize=(30, 30),
15
flags=cv.CASCADE_SCALE_IMAGE)
16
if len(rects) == 0:
17
return []
18
rects[:,2:] += rects[:,:2]
19
return rects
20
21
from tests_common import NewOpenCVTests, intersectionRate
22
23
class facedetect_test(NewOpenCVTests):
24
25
def test_facedetect(self):
26
cascade_fn = self.repoPath + '/data/haarcascades/haarcascade_frontalface_alt.xml'
27
nested_fn = self.repoPath + '/data/haarcascades/haarcascade_eye.xml'
28
29
cascade = cv.CascadeClassifier(cascade_fn)
30
nested = cv.CascadeClassifier(nested_fn)
31
32
samples = ['samples/data/lena.jpg', 'cv/cascadeandhog/images/mona-lisa.png']
33
34
faces = []
35
eyes = []
36
37
testFaces = [
38
#lena
39
[[218, 200, 389, 371],
40
[ 244, 240, 294, 290],
41
[ 309, 246, 352, 289]],
42
43
#lisa
44
[[167, 119, 307, 259],
45
[188, 153, 229, 194],
46
[236, 153, 277, 194]]
47
]
48
49
for sample in samples:
50
51
img = self.get_sample( sample)
52
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
53
gray = cv.GaussianBlur(gray, (5, 5), 5.1)
54
55
rects = detect(gray, cascade)
56
faces.append(rects)
57
58
if not nested.empty():
59
for x1, y1, x2, y2 in rects:
60
roi = gray[y1:y2, x1:x2]
61
subrects = detect(roi.copy(), nested)
62
63
for rect in subrects:
64
rect[0] += x1
65
rect[2] += x1
66
rect[1] += y1
67
rect[3] += y1
68
69
eyes.append(subrects)
70
71
faces_matches = 0
72
eyes_matches = 0
73
74
eps = 0.8
75
76
for i in range(len(faces)):
77
for j in range(len(testFaces)):
78
if intersectionRate(faces[i][0], testFaces[j][0]) > eps:
79
faces_matches += 1
80
#check eyes
81
if len(eyes[i]) == 2:
82
if intersectionRate(eyes[i][0], testFaces[j][1]) > eps and intersectionRate(eyes[i][1] , testFaces[j][2]) > eps:
83
eyes_matches += 1
84
elif intersectionRate(eyes[i][1], testFaces[j][1]) > eps and intersectionRate(eyes[i][0], testFaces[j][2]) > eps:
85
eyes_matches += 1
86
87
self.assertEqual(faces_matches, 2)
88
self.assertEqual(eyes_matches, 2)
89
90
91
if __name__ == '__main__':
92
NewOpenCVTests.bootstrap()
93
94