Path: blob/master/modules/python/test/test_facedetect.py
16337 views
#!/usr/bin/env python12'''3face detection using haar cascades4'''56# Python 2/3 compatibility7from __future__ import print_function89import numpy as np10import cv2 as cv1112def detect(img, cascade):13rects = cascade.detectMultiScale(img, scaleFactor=1.275, minNeighbors=4, minSize=(30, 30),14flags=cv.CASCADE_SCALE_IMAGE)15if len(rects) == 0:16return []17rects[:,2:] += rects[:,:2]18return rects1920from tests_common import NewOpenCVTests, intersectionRate2122class facedetect_test(NewOpenCVTests):2324def test_facedetect(self):25cascade_fn = self.repoPath + '/data/haarcascades/haarcascade_frontalface_alt.xml'26nested_fn = self.repoPath + '/data/haarcascades/haarcascade_eye.xml'2728cascade = cv.CascadeClassifier(cascade_fn)29nested = cv.CascadeClassifier(nested_fn)3031samples = ['samples/data/lena.jpg', 'cv/cascadeandhog/images/mona-lisa.png']3233faces = []34eyes = []3536testFaces = [37#lena38[[218, 200, 389, 371],39[ 244, 240, 294, 290],40[ 309, 246, 352, 289]],4142#lisa43[[167, 119, 307, 259],44[188, 153, 229, 194],45[236, 153, 277, 194]]46]4748for sample in samples:4950img = self.get_sample( sample)51gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)52gray = cv.GaussianBlur(gray, (5, 5), 5.1)5354rects = detect(gray, cascade)55faces.append(rects)5657if not nested.empty():58for x1, y1, x2, y2 in rects:59roi = gray[y1:y2, x1:x2]60subrects = detect(roi.copy(), nested)6162for rect in subrects:63rect[0] += x164rect[2] += x165rect[1] += y166rect[3] += y16768eyes.append(subrects)6970faces_matches = 071eyes_matches = 07273eps = 0.87475for i in range(len(faces)):76for j in range(len(testFaces)):77if intersectionRate(faces[i][0], testFaces[j][0]) > eps:78faces_matches += 179#check eyes80if len(eyes[i]) == 2:81if intersectionRate(eyes[i][0], testFaces[j][1]) > eps and intersectionRate(eyes[i][1] , testFaces[j][2]) > eps:82eyes_matches += 183elif intersectionRate(eyes[i][1], testFaces[j][1]) > eps and intersectionRate(eyes[i][0], testFaces[j][2]) > eps:84eyes_matches += 18586self.assertEqual(faces_matches, 2)87self.assertEqual(eyes_matches, 2)888990if __name__ == '__main__':91NewOpenCVTests.bootstrap()929394