Basic Face Detection

In this tutorial we will learn to write a simple python application to perform face detection.

Python code

Create a file facedet.py with the following code in it.

import requests
import argparse

parser = argparse.ArgumentParser(description='Face Detector')
parser.add_argument('--det', action='store', default="mmod", nargs='?', help='Detector `mmod` or `yolo` or `hog` ')
parser.add_argument('--src', action='store', default=0, nargs='?', help='Set source image')
args = parser.parse_args()

face_api="http://localhost:5000/inferImage?detector=%s"%(args.det)

files = {'pic':open(args.src,'rb')}
r = requests.post(face_api,files=files)
result = r.json()

# The result is a list as follows 
# [{face1},
#  ...
# {faceN},
# {diagnostics}]
if len(result) < 2:
    print("No detections! Try image with larger face! or try next tutorial with advanced request params")

for i,face in enumerate(result[:-1]):
    print("Face %d  "%i, face)

Download any jpeg/png file from the internet and save it in the current folder. Then run the script as follows

$ python3 facedet.py --det yolohd --src group7.jpg 
Face 0   {'faceRectangle': {'confidence': 0.863022923469543, 'left': 417, 'height': 91, 'top': 25, 'width': 96}}
Face 1   {'faceRectangle': {'confidence': 0.870513558387756, 'left': 332, 'height': 83, 'top': 64, 'width': 92}}
Face 2   {'faceRectangle': {'confidence': 0.777787268161774, 'left': 62, 'height': 83, 'top': 119, 'width': 93}}
Face 3   {'faceRectangle': {'confidence': 0.856383681297302, 'left': 234, 'height': 90, 'top': 120, 'width': 96}}
Face 4   {'faceRectangle': {'confidence': 0.857118904590607, 'left': 402, 'height': 79, 'top': 170, 'width': 95}}
Face 5   {'faceRectangle': {'confidence': 0.634900808334351, 'left': 456, 'height': 79, 'top': 270, 'width': 90}}

$ python3 facedet.py --det hog --src group7.jpg 
Face 0   {'faceRectangle': {'width': 95, 'confidence': 2.34097129483355, 'left': 329, 'height': 95, 'top': 70}}
Face 1   {'faceRectangle': {'width': 95, 'confidence': 0.357257191134822, 'left': 233, 'height': 96, 'top': 117}}
Face 2   {'faceRectangle': {'width': 79, 'confidence': 0.0830764924354974, 'left': 394, 'height': 79, 'top': 170}}
  • There are 4 detectors bundled in deepsight - mmod, yolo, yolohd and hog. Each uses a different algorithm
  • Vary the --det param and try each detector. yolo is fast. mmod gives extremely low false positives. yolohd finds smaller faces. hog is traditional detector.

Congratulations on performing your first face detection Magic!