ninjaEyeDetector.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import numpy as np
  2. import cv2
  3. # Load the Cascade Classifier Xml file
  4. face_cascade = cv2.CascadeClassifier("cascade/mallick_haarcascade_frontalface_default.xml")
  5. # Specifying minimum and maximum size parameters
  6. MIN_FACE_SIZE = 100
  7. MAX_FACE_SIZE = 300
  8. #Create a VideoCapture object
  9. cap = cv2.VideoCapture(0)
  10. # Check if camera opened successfully
  11. if (cap.isOpened() == False):
  12. print("Unable to read camera feed")
  13. while(True):
  14. # Reading each frame
  15. ret, frameBig = cap.read()
  16. # If frame opened successfully
  17. if ret == True:
  18. # Fixing the scaling factor
  19. scale = 640.0/frameBig.shape[1]
  20. # Resizing the image
  21. frame = cv2.resize(frameBig,None,fx = scale,fy = scale, interpolation = cv2.INTER_LINEAR)
  22. # Converting to grayscale
  23. frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  24. # Detect faces
  25. faces = face_cascade.detectMultiScale(frameGray, scaleFactor=1.1, minNeighbors=5,flags=0, minSize=(MIN_FACE_SIZE,MIN_FACE_SIZE),maxSize=(MAX_FACE_SIZE,MAX_FACE_SIZE))
  26. # Loop over each detected face
  27. for i in xrange (0,len(faces)):
  28. # Dimension parameters for bounding rectangle for face
  29. x,y,width,height = faces[i];
  30. # Calculating the dimension parameters for eyes from the dimensions parameters of the face
  31. ex,ey,ewidth,eheight = int(x + 0.125*width), int(y + 0.25 * height), int(0.75 * width), int(0.25 * height)
  32. # Drawing the bounding rectangle around the face
  33. cv2.rectangle(frame, (ex,ey),(ex+ewidth,ey+eheight),(128,255,0), 2)
  34. # Display the resulting frame
  35. cv2.imshow('Ninja Eye Detector',frame)
  36. # Press ESC on keyboard to stop tracking
  37. key = cv2.waitKey(1)
  38. if (key==27):
  39. break
  40. # Break the loop
  41. else:
  42. break
  43. # Release VideoCapture object
  44. cap.release()
  45. # Closes all the frames
  46. cv2.destroyAllWindows()