Home > Enterprise >  Python cv2.VideoCapture crashes with face_recognition library
Python cv2.VideoCapture crashes with face_recognition library

Time:09-22

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()

When i execute this file, face_recognition library is working properly and finding true matches like this:

match found! = yusuf

and printing it but video capture window is not responding and crashing so i cant see the result. When I close the window from task manager it gives me this:

Process finished with exit code -805306369 (0xCFFFFFFF)

NOTE : cv2.VideoCapture works normally without face_recognition library.

CodePudding user response:

Your CPU can't handle fast enough the task for real-time face detection and recognition using the CNN model. for every frame it takes several seconds to process it and that's why you get the correct recognition but that is too slow to view the results with the processed frames.

The CNN model has more accuracy than the "HOG" but it requires more computational power that suitable for GPU.

Yet, you will get very good results with CPU using the HOG model.

The solution: change the code line MODEL = "cnn" to MODEL = "hog"

  • Related