verify_face.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import face_recognition
  2. import cv2
  3. import numpy as np
  4. import joblib
  5. import time
  6. # This is a super simple (but slow) example of running face recognition on live video from your webcam.
  7. # There's a second example that's a little more complicated but runs faster.
  8. # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
  9. # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
  10. # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
  11. # Get a reference to webcam #0 (the default one)
  12. video_capture = cv2.VideoCapture(0)
  13. clf = joblib.load('saved_model.pkl')
  14. classes = clf.classes_
  15. threshold = 0.65
  16. while True:
  17. # Grab a single frame of video
  18. ret, frame = video_capture.read()
  19. # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
  20. rgb_frame = frame[:, :, ::-1]
  21. # Find all the faces and face enqcodings in the frame of video
  22. face_locations = face_recognition.face_locations(rgb_frame)
  23. no = len(face_locations)
  24. print("Number of faces detected: ", no)
  25. face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
  26. # Loop through each face in this frame of video
  27. for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
  28. start_time = time.perf_counter_ns()
  29. proba_list = clf.predict_proba([face_encoding])
  30. end_time = time.perf_counter_ns()
  31. process_time = end_time - start_time
  32. i = np.argmax(proba_list)
  33. proba = list(*proba_list)[i]
  34. name = classes[i]
  35. print(name, "{:.2f}".format(proba), proba_list, process_time)
  36. # Draw a box around the face
  37. cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
  38. # Draw a label with a name below the face
  39. cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
  40. if(proba > threshold):
  41. font = cv2.FONT_HERSHEY_DUPLEX
  42. cv2.putText(frame, "{} {:.2f}".format(name, proba), (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
  43. # Display the resulting image
  44. cv2.imshow('Video', frame)
  45. # Hit 'q' on the keyboard to quit!
  46. if cv2.waitKey(1) & 0xFF == ord('q'):
  47. break
  48. # Release handle to the webcam
  49. video_capture.release()
  50. cv2.destroyAllWindows()