|
| 1 | +import face_recognition |
| 2 | +import cv2 |
| 3 | + |
| 4 | +# This is a super simple demo of running face recognition on live video from your webcam. |
| 5 | + |
| 6 | +# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam. |
| 7 | +# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this |
| 8 | +# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead. |
| 9 | + |
| 10 | +# Get a reference to webcam #0 (the default one) |
| 11 | +video_capture = cv2.VideoCapture(0) |
| 12 | + |
| 13 | +# Load a sample picture and learn how to recognize it. |
| 14 | +obama_image = face_recognition.load_image_file("obama.jpg") |
| 15 | +obama_face_encoding = face_recognition.face_encodings(obama_image)[0] |
| 16 | + |
| 17 | +while True: |
| 18 | + # Grab a single frame of video |
| 19 | + ret, frame = video_capture.read() |
| 20 | + |
| 21 | + # Find all the faces and face enqcodings in the frame of video |
| 22 | + face_locations = face_recognition.face_locations(frame) |
| 23 | + face_encodings = face_recognition.face_encodings(frame, face_locations) |
| 24 | + |
| 25 | + # Loop through each face in this frame of video |
| 26 | + for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings): |
| 27 | + # See if the face is a match for the known face(s) |
| 28 | + match = face_recognition.compare_faces([obama_face_encoding], face_encoding) |
| 29 | + |
| 30 | + name = "Unknown" |
| 31 | + if match[0]: |
| 32 | + name = "Barack" |
| 33 | + |
| 34 | + # Draw a box around the face |
| 35 | + cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) |
| 36 | + |
| 37 | + # Draw a label with a name below the face |
| 38 | + cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) |
| 39 | + font = cv2.FONT_HERSHEY_DUPLEX |
| 40 | + cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) |
| 41 | + |
| 42 | + # Display the resulting image |
| 43 | + cv2.imshow('Video', frame) |
| 44 | + |
| 45 | + # Hit 'q' on the keyboard to quit! |
| 46 | + if cv2.waitKey(1) & 0xFF == ord('q'): |
| 47 | + break |
| 48 | + |
| 49 | +# Release handle to the webcam |
| 50 | +video_capture.release() |
| 51 | +cv2.destroyAllWindows() |
0 commit comments