face-detectiondeepface

ValueError: Face could not be detected in DeepFace


I am implementing a code segment to detect video frames with faces and store them in an array. For this purpose I am using DeepFace library. (Go to deepface github repository).

Below is my code segment:

# Import Libraries
from deepface import DeepFace
import matplotlib.pyplot as plt
import cv2

# Path of the video
video_file_path = '/content/drive/My Drive/Colab Notebooks/FYP Project/Data Preprocessing/youtube_clip_001.mp4'

# Reading the video
vidcap = cv2.VideoCapture(video_file_path)

# Extracting the frames
frames = []
while True:
    ret, frame = vidcap.read()
    if not ret:
        break
    # Extracting the face from the frame
    faces = DeepFace.detectFace(frame)
    if len(faces) > 0:
        frames.append(frame)

Each and every frame in the video file I am using may not have human faces. That is why I need to extract only the frames with human faces. But it does give the following error:

ValueError: Face could not be detected. Please confirm that the picture is a face photo or consider to set enforce_detection param to False.

But when I make faces = DeepFace.detectFace(frame, enforce_detection=False) as suggested in the error, then it add not only the frames with human faces, but also all the frames in the video to the array including frames without faces.

Can somebody please help me to solve this issue?

Here is the link to the video file I am using: https://drive.google.com/file/d/1vAJyjbQYAYFJS4DVN0UWDYb21wf0r0TL/view?usp=sharing


Solution

  • In face detection by deepface, it checks for a face in the frame and if not throws an exception. As mentioned in this GitHub issue also, if I make enforce_detection=False then it reduces the accuracy. Therefore the best option available is to handle the exception without breaking the code.

    Therefore you can modify the above code snippet as follows:

    while True:
        ret, frame = vidcap.read()
        if not ret:
            break
        # Extracting the face from the frame
        try:
            faces = DeepFace.detectFace(frame)
            if len(faces) > 0:
                frames.append(frame)
        except:
            print('exception')
    

    Following is another example I tried with again:

    enter image description here