demo

import face_recognition
import cv2


# 获取面部 numpy 对象
image = face_recognition.load_image_file('9无.jpg')
# print(image)

# 对图片中的每一个面部进行编码
faces = face_recognition.face_encodings(image)
print('faces num: ', len(faces))

# image2 = face_recognition.load_image_file('7无.jpg')
# unknow_faces = face_recognition.face_encodings(image2)
# print('unknow_faces num: ', len(unknow_faces))
# 
# if len(unknow_faces) == 1:
#     # 对比
#     result = face_recognition.compare_faces(faces, unknow_faces[0])
#     print(result)
# else:
#     print(len(unknow_faces),' 张人脸')


video_capture = cv2.VideoCapture(0)

while True:
    ret, frame = video_capture.read()
    # print(frame)

    # 将 cv2 的 rgb image对象 转为 face_recognition 的 rgb image 对象
    rgb_frame = frame[:, :, ::-1]

    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        # See if the face is a match for the known face(s)
        matches = face_recognition.compare_faces(faces, face_encoding)

        name = "Unknown"

        # If a match was found in known_face_encodings, just use the first one.
        if True in matches:
            first_match_index = matches.index(True)
            name = "me"

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX

        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    #Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

你可能感兴趣的:(demo)