objectDetection.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from __future__ import print_function
  2. import cv2 as cv
  3. import argparse
  4. def detectAndDisplay(frame):
  5. frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
  6. frame_gray = cv.equalizeHist(frame_gray)
  7. #-- Detect faces
  8. faces = face_cascade.detectMultiScale(frame_gray)
  9. for (x,y,w,h) in faces:
  10. center = (x + w//2, y + h//2)
  11. frame = cv.ellipse(frame, center, (w//2, h//2), 0, 0, 360, (255, 0, 255), 4)
  12. faceROI = frame_gray[y:y+h,x:x+w]
  13. #-- In each face, detect eyes
  14. eyes = eyes_cascade.detectMultiScale(faceROI)
  15. for (x2,y2,w2,h2) in eyes:
  16. eye_center = (x + x2 + w2//2, y + y2 + h2//2)
  17. radius = int(round((w2 + h2)*0.25))
  18. frame = cv.circle(frame, eye_center, radius, (255, 0, 0 ), 4)
  19. cv.imshow('Capture - Face detection', frame)
  20. parser = argparse.ArgumentParser(description='Code for Cascade Classifier tutorial.')
  21. parser.add_argument('--face_cascade', help='Path to face cascade.', default='data/haarcascades/haarcascade_frontalface_alt.xml')
  22. parser.add_argument('--eyes_cascade', help='Path to eyes cascade.', default='data/haarcascades/haarcascade_eye_tree_eyeglasses.xml')
  23. parser.add_argument('--camera', help='Camera divide number.', type=int, default=0)
  24. args = parser.parse_args()
  25. face_cascade_name = args.face_cascade
  26. eyes_cascade_name = args.eyes_cascade
  27. face_cascade = cv.CascadeClassifier()
  28. eyes_cascade = cv.CascadeClassifier()
  29. #-- 1. Load the cascades
  30. if not face_cascade.load(cv.samples.findFile(face_cascade_name)):
  31. print('--(!)Error loading face cascade')
  32. exit(0)
  33. if not eyes_cascade.load(cv.samples.findFile(eyes_cascade_name)):
  34. print('--(!)Error loading eyes cascade')
  35. exit(0)
  36. camera_device = args.camera
  37. #-- 2. Read the video stream
  38. cap = cv.VideoCapture(camera_device)
  39. if not cap.isOpened:
  40. print('--(!)Error opening video capture')
  41. exit(0)
  42. while True:
  43. ret, frame = cap.read()
  44. if frame is None:
  45. print('--(!) No captured frame -- Break!')
  46. break
  47. detectAndDisplay(frame)
  48. if cv.waitKey(10) == 27:
  49. break