facedetect.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python
  2. '''
  3. face detection using haar cascades
  4. USAGE:
  5. facedetect.py [--cascade <cascade_fn>] [--nested-cascade <cascade_fn>] [<video_source>]
  6. '''
  7. # Python 2/3 compatibility
  8. from __future__ import print_function
  9. import numpy as np
  10. import cv2 as cv
  11. # local modules
  12. from video import create_capture
  13. from common import clock, draw_str
  14. def detect(img, cascade):
  15. rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
  16. flags=cv.CASCADE_SCALE_IMAGE)
  17. if len(rects) == 0:
  18. return []
  19. rects[:,2:] += rects[:,:2]
  20. return rects
  21. def draw_rects(img, rects, color):
  22. for x1, y1, x2, y2 in rects:
  23. cv.rectangle(img, (x1, y1), (x2, y2), color, 2)
  24. def main():
  25. import sys, getopt
  26. args, video_src = getopt.getopt(sys.argv[1:], '', ['cascade=', 'nested-cascade='])
  27. try:
  28. video_src = video_src[0]
  29. except:
  30. video_src = 0
  31. args = dict(args)
  32. cascade_fn = args.get('--cascade', "haarcascades/haarcascade_frontalface_alt.xml")
  33. nested_fn = args.get('--nested-cascade', "haarcascades/haarcascade_eye.xml")
  34. cascade = cv.CascadeClassifier(cv.samples.findFile(cascade_fn))
  35. nested = cv.CascadeClassifier(cv.samples.findFile(nested_fn))
  36. cam = create_capture(video_src, fallback='synth:bg={}:noise=0.05'.format(cv.samples.findFile('lena.jpg')))
  37. while True:
  38. _ret, img = cam.read()
  39. gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
  40. gray = cv.equalizeHist(gray)
  41. t = clock()
  42. rects = detect(gray, cascade)
  43. vis = img.copy()
  44. draw_rects(vis, rects, (0, 255, 0))
  45. if not nested.empty():
  46. for x1, y1, x2, y2 in rects:
  47. roi = gray[y1:y2, x1:x2]
  48. vis_roi = vis[y1:y2, x1:x2]
  49. subrects = detect(roi.copy(), nested)
  50. draw_rects(vis_roi, subrects, (255, 0, 0))
  51. dt = clock() - t
  52. draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000))
  53. cv.imshow('facedetect', vis)
  54. if cv.waitKey(5) == 27:
  55. break
  56. print('Done')
  57. if __name__ == '__main__':
  58. print(__doc__)
  59. main()
  60. cv.destroyAllWindows()