首页 > 解决方案 > 使用 face_recognition 库时 Python 没有响应

问题描述

KNOWN_FACES_DIR = 'Known'
TOLERANCE = 0.6
FRAME_THICKNESS = 3
FONT_THICKNESS = 2
MODEL = 'cnn'

video=cv2.VideoCapture(0)

print('Loading known faces...')
known_faces = []
known_names = []

for name in os.listdir(KNOWN_FACES_DIR):
    for filename in os.listdir(f'{KNOWN_FACES_DIR}/{name}'):

        image = face_recognition.load_image_file(f'{KNOWN_FACES_DIR}/{name}/{filename}')
        encoding = face_recognition.face_encodings(image)[0]

        known_faces.append(encoding)
        known_names.append(name)

while True:

    ret,image=video.read()
    locations = face_recognition.face_locations(image, model=MODEL)
    encodings = face_recognition.face_encodings(image, locations)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

    print(f', found {len(encodings)} face(s)')
    for face_encoding, face_location in zip(encodings, locations):

        results = face_recognition.compare_faces(known_faces, face_encoding, TOLERANCE)


        match = None
        if True in results:  
            match = known_names[results.index(True)]
            print(f' - {match} from {results}')

            
            top_left = (face_location[3], face_location[0])
            bottom_right = (face_location[1], face_location[2])
            cv2.rectangle(image, top_left, bottom_right,FRAME_THICKNESS)

            top_left = (face_location[3], face_location[2])
            bottom_right = (face_location[1], face_location[2] + 22)

            cv2.rectangle(image, top_left, bottom_right,cv2.FILLED)
            cv2.putText(image, match, (face_location[3] + 10, face_location[2] + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (200, 200, 200), FONT_THICKNESS)

    cv2.imshow(filename, image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
video.release()
cv2.destroyAllWindows()

我正在将 face_recognition 库用于人脸识别项目。这给了我想要的结果,但它一直没有响应。在 20-30 秒无响应后,它会在单帧上显示结果。是因为我的笔记本电脑规格不好还是代码需要一些更改?

https://www.youtube.com/watch?v=PdkPI92KSIs&list=RDCMUCfzlCWGWYyyIQ0aLC5w48gBQ&index=2

这是关于结果应该是什么样子的 youtube 视频。

标签: pythonface-recognition

解决方案


为什么不用deepface?在这里,数据库路径是您存储面部图像的位置。

#!pip install deepface
from deepface import DeepFace
DeepFace.stream(db_path = "C:/my_db")

推荐阅读