timesler / facenet-pytorch

Pretrained Pytorch face detection (MTCNN) and facial recognition (InceptionResnet) models
MIT License
4.43k stars 945 forks source link

How to handle no face in image #147

Open Joaquin-aliaga opened 3 years ago

Joaquin-aliaga commented 3 years ago

Hi, I'm developing a face verification system, so I'm using mtcnn to detect faces and then do the verification step.

The code I have is something like:

face_detect, prob = mtcnn.detect(img)
if (face_detect is not None):
    face_cropped = mtcnn(img)
   ...
else:
   return None

However, I'm wondering if there is a way to handle the "no face in image" case without use mtcnn twice, because I assume mtcnn.detect() and mtcnn() use almost the same code.

If I just use face_cropped = mtcnn(img) and img has no face, I get an error.

line 408, in select_boxes
    if len(boxes) == 0:
TypeError: len() of unsized object

Thanks in advance

Joaquin-aliaga commented 3 years ago

@Joaquin-aliaga I've already find a solution for not using mtccn twice and post here if anyone faces the same issue. Since mtcnn.detect() returns bounding boxes and probs, just use:

bbx, prob = mtcnn.detect(img)
if (bbx is not None):
    face_cropped = mtcnn.extract(img,bbx,None)
   ...
else:
   return None

In that way you don't have to pass your image twice through the CNN.

However it would be nice if mtcnn() returns None when no face was detected.

justDoIt1314 commented 3 years ago

The problem has been solved.

if type(boxes) == numpy.ndarray:
    for bbox in boxes: