test_facedetect.py 2.7 KB

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