Python cv2.VideoCapture 与 face_recognition 库崩溃

Python cv2.VideoCapture crashes with face_recognition library

import face_recognition
import os
import cv2

video = cv2.VideoCapture(0)

KNOWN_FACES_DIR = "known_faces"
TOLERANCE = 0.6
FRAME_THICKNESS = 3
FONT_THICKNESS = 2
MODEL = "cnn" 
FONT = cv2.FONT_HERSHEY_SIMPLEX

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)

print("processing unknown faces...")

while True:
    ret, frame = video.read()

    locations = face_recognition.face_locations(frame, model=MODEL)
    encodings = face_recognition.face_encodings(frame, locations)

    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 found! = {match}")

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

            color = [0, 255, 0]
            cv2.rectangle(frame, top_left, bottom_right, color, FRAME_THICKNESS)

            top_left = (face_location[3], face_location[2])
            bottom_right = (face_location[1], face_location[2]+22)
            cv2.rectangle(frame, top_left, bottom_right, color, cv2.FILLED)
            cv2.putText(frame, match, (face_location[3]+10, face_location[2]+15), FONT, 0.5, (0, 0, 0), FONT_THICKNESS)

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

video.release()
cv2.destroyAllWindows()

当我执行此文件时,face_recognition 库正常工作并找到像这样的真正匹配项:

match found! = yusuf

并打印它,但视频捕获 window 没有响应并崩溃,所以我看不到结果。当我从任务管理器关闭 window 时,它给了我这个:

Process finished with exit code -805306369 (0xCFFFFFFF)

注意:cv2.VideoCapture 在没有 face_recognition 库的情况下正常工作。

您的 CPU 无法足够快地处理使用 CNN 模型进行实时人脸检测和识别的任务。每一帧都需要几秒钟的时间来处理,这就是为什么你能得到正确的识别,但是这太慢了,无法查看处理过的帧的结果。

CNN 模型比“HOG”更准确,但它需要更多适合 GPU 的计算能力。

然而,CPU 使用 HOG 模型你会得到很好的结果。

解决方法: 更改代码行 MODEL = "cnn"MODEL = "hog"