Deep Learning Face Recognition from Photo with a code example

This is an example of using the k-nearest-neighbors (KNN) algorithm for face recognition.

It's useful when you wish to recognize a large set of known people, and make a prediction for an unknown person in a feasible computation time

You can download project at github

We will use library

Face Recognition is built using dlib's state-of-the-art face recognition built with deep learning. The model has an accuracy of 99.38%

We will use a simple face_recognition command line tool that lets us do face recognition on a folder of images from the command line!

Project contains two examples:

  1. Face Recognition from PHOTO
  2. Face Recognition from WEBCAM

1. Face Recognition from PHOTO


In this example we will we will train our model to recognize 2 persons from images using a trained classifier model

Script will:

  • detect faces on image
  • compare face with known persons
  • draw rectangle around face with label

Folder structure:

Path: /images/

  • train
    • Person 1
      • image1.jpg
      • image2.jpg
    • Ivan
      • image1.jpg
      • image2.jpg
    • Person 3
      • image1.jpg
      • image2.jpg
  • test
    • image A.jpg
    • image B.jpg
  • results
    • image A.jpg
    • image B.jpg

Train model:

Prepare a set of images of the known people you want to recognize. Organize the images in a single directory with a sub-directory for each known person.

/images/train/{Person Name}/image.jpg

  • train
    • Ivan
      • image1.jpg
      • image2.jpg
    • John
      • image1.jpg

Image naming does not matter...

Folder name will be used as label

Train image example


Add new Person

  • Create new folder in train folder.
  • Rename folder to match person name (example "John", name of folder will be used as name)
  • Add images to folder.

Example: /images/train/John/image.jpg

Test folder (unknown images)

/images/test folder contain images of unknown persons.

Results folder

/images/results folder contains saved images.

Run face recognition

Using the trained classifier we will make predictions for all images in test folder


Test Image


Test image

Result Image ( test image after face recognition)


On this photo we recognitionized 1 person Ivan. We draw rectangle around face with label Ivan

Result image