how to handle error in deepFace.analyze() when no face is found?

10.5k views Asked by At
img=cv2.imread(face.jpg)
predictions= DeepFace.analyze(img)

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

setting enforce_detection to False is causing it to read emotions even if there is no face in the image

how do we handle this error so that it tells us that there is no face?

4

There are 4 answers

3
jonas On
try:
  img=cv2.imread(face.jpg)
  predictions= DeepFace.analyze(img)
except:
  print("No face detected")

0
Davide Marengo On

Try this script here! Good luck!

from deepface import DeepFace
import os
file = open("path to file you want to save your results in", 'w')

# giving directory for your pictures
dirname = "the path of the directory"
  
for files in os.listdir(dirname):
    try:
        obj = DeepFace.analyze(img_path = ("the path of the directory" + files), actions = ['age', 'gender', 'race', 'emotion'])
        file.write(files)
        file.write(str(obj) + "\n")
    except Exception: 
        file.write(files)
        file.write("face_was not detected" + "\n")
file.close()
0
Greg W.F.R On

The best way of solving this problem is reading the error and it says: "consider to set enforce_detection param to False."

so you can simply solve this by not forcing a face detection.

return DeepFace.verify(img1, img2 , enforce_detection=False)['verified']

I had the error with that code for your code it will probably be

DeepFace.analyze(img1 , enforce_detection=False)

Response on edit:

This is a different problem, you could first try to detect if there is a face on the foto using this approach:

https://www.digitalocean.com/community/tutorials/how-to-detect-and-extract-faces-from-an-image-with-opencv-and-python

and only analyze for emotions, knowing there is a face!

2
Genoske On

Try try: except: block, it should work.