Face_recognition与人脸识别解决方案

版权声明:未经博主允许请勿转载 https://blog.csdn.net/qq_39040135/article/details/82955402

Face_recognition 与人脸识别解决方案

很久之前做的,好像是从github上参考一老外的,用到了当前比较火的face_recognition第三方库,我在此基础上做了一些改进
现在可以在你的系统path下放一组样本照片,文件名为人名,可以通过import这个demo开始体验人脸识别的乐趣吧。

import cv2

import face_recognition

import os


path = "c:/Python36/Data/img/face_recognition"

cap = cv2.VideoCapture(0)

total_image_name = []

total_face_encoding = []


for fn in os.listdir(path):
    print(path + "/" + fn)

    total_face_encoding.append(

        face_recognition.face_encodings(

            face_recognition.load_image_file(path + "/" + fn))[0])

    fn = fn[:(len(fn) - 4)]

    total_image_name.append(fn)

face_locations = []

face_encodings = []

face_names = []

process_this_frame = True


while True:

    ret, frame = cap.read()

    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    rgb_small_frame = small_frame[:, :, ::-1]

    if process_this_frame:

        face_locations = face_recognition.face_locations(rgb_small_frame)

        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []

        for face_encoding in face_encodings:

            matches = face_recognition.compare_faces(total_face_encoding, face_encoding)
            name = "Unknown"

            # If a match was found in known_face_encodings, just use the first one.

                first_match_index = matches.index(True)
                name = total_image_name[first_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        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)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()

cv2.destroyAllWindows()

猜你喜欢

转载自blog.csdn.net/qq_39040135/article/details/82955402