face-api.js

JavaScript API for face detection and face recognition in the browser and n...

README

face-api.js

Build Status Slack

JavaScript face recognition API for the browser and nodejs implemented on top of tensorflow.js core (tensorflow/tfjs-core)

faceapi


Tutorials



Table of Contents



Features


Face Recognition


face-recognition

Face Landmark Detection


face_landmark_detection

Face Expression Recognition


preview_face-expression-recognition

Age Estimation & Gender Recognition


age_gender_recognition


Running the Examples


Clone the repository:

  1. ``` bash
  2. git clone https://github.com/justadudewhohacks/face-api.js.git
  3. ```

Running the Browser Examples


  1. ``` bash
  2. cd face-api.js/examples/examples-browser
  3. npm i
  4. npm start
  5. ```

Browse to http://localhost:3000/.

Running the Nodejs Examples


  1. ``` bash
  2. cd face-api.js/examples/examples-nodejs
  3. npm i
  4. ```

Now run one of the examples using ts-node:

  1. ``` bash
  2. ts-node faceDetection.ts
  3. ```

Or simply compile and run them with node:

  1. ``` bash
  2. tsc faceDetection.ts
  3. node faceDetection.js
  4. ```


face-api.js for the Browser


Simply include the latest script from dist/face-api.js.

Or install it via npm:

  1. ``` bash
  2. npm i face-api.js
  3. ```


face-api.js for Nodejs


We can use the equivalent API in a nodejs environment by polyfilling some browser specifics, such as HTMLImageElement, HTMLCanvasElement and ImageData. The easiest way to do so is by installing the node-canvas package.

Alternatively you can simply construct your own tensors from image data and pass tensors as inputs to the API.

Furthermore you want to install @tensorflow/tfjs-node (not required, but highly recommended), which speeds things up drastically by compiling and binding to the native Tensorflow C++ library:

  1. ``` bash
  2. npm i face-api.js canvas @tensorflow/tfjs-node
  3. ```

Now we simply monkey patch the environment to use the polyfills:

  1. ``` javascript
  2. // import nodejs bindings to native tensorflow,
  3. // not required, but will speed up things drastically (python required)
  4. import '@tensorflow/tfjs-node';

  5. // implements nodejs wrappers for HTMLCanvasElement, HTMLImageElement, ImageData
  6. import * as canvas from 'canvas';

  7. import * as faceapi from 'face-api.js';

  8. // patch nodejs environment, we need to provide an implementation of
  9. // HTMLCanvasElement and HTMLImageElement
  10. const { Canvas, Image, ImageData } = canvas
  11. faceapi.env.monkeyPatch({ Canvas, Image, ImageData })
  12. ```


Getting Started



Loading the Models


All global neural network instances are exported via faceapi.nets:

  1. ``` javascript
  2. console.log(faceapi.nets)
  3. // ageGenderNet
  4. // faceExpressionNet
  5. // faceLandmark68Net
  6. // faceLandmark68TinyNet
  7. // faceRecognitionNet
  8. // ssdMobilenetv1
  9. // tinyFaceDetector
  10. // tinyYolov2
  11. ```

To load a model, you have to provide the corresponding manifest.json file as well as the model weight files (shards) as assets. Simply copy them to your public or assets folder. The manifest.json and shard files of a model have to be located in the same directory / accessible under the same route.

Assuming the models reside in public/models:

  1. ``` javascript
  2. await faceapi.nets.ssdMobilenetv1.loadFromUri('/models')
  3. // accordingly for the other models:
  4. // await faceapi.nets.faceLandmark68Net.loadFromUri('/models')
  5. // await faceapi.nets.faceRecognitionNet.loadFromUri('/models')
  6. // ...
  7. ```

In a nodejs environment you can furthermore load the models directly from disk:

  1. ``` javascript
  2. await faceapi.nets.ssdMobilenetv1.loadFromDisk('./models')
  3. ```

You can also load the model from a tf.NamedTensorMap:

  1. ``` javascript
  2. await faceapi.nets.ssdMobilenetv1.loadFromWeightMap(weightMap)
  3. ```

Alternatively, you can also create own instances of the neural nets:

  1. ``` javascript
  2. const net = new faceapi.SsdMobilenetv1()
  3. await net.loadFromUri('/models')
  4. ```

You can also load the weights as a Float32Array (in case you want to use the uncompressed models):

  1. ``` javascript
  2. // using fetch
  3. net.load(await faceapi.fetchNetWeights('/models/face_detection_model.weights'))

  4. // using axios
  5. const res = await axios.get('/models/face_detection_model.weights', { responseType: 'arraybuffer' })
  6. const weights = new Float32Array(res.data)
  7. net.load(weights)
  8. ```


High Level API


In the following input can be an HTML img, video or canvas element or the id of that element.

  1. ``` html
  2. <img id="myImg" src="images/example.png" />
  3. <video id="myVideo" src="media/example.mp4" />
  4. <canvas id="myCanvas" />
  5. ```

  1. ``` javascript
  2. const input = document.getElementById('myImg')
  3. // const input = document.getElementById('myVideo')
  4. // const input = document.getElementById('myCanvas')
  5. // or simply:
  6. // const input = 'myImg'
  7. ```

Detecting Faces


Detect all faces in an image. Returns **Array<[FaceDetection](#interface-face-detection)>**:

  1. ``` javascript
  2. const detections = await faceapi.detectAllFaces(input)
  3. ```

Detect the face with the highest confidence score in an image. Returns FaceDetection | undefined:

  1. ``` javascript
  2. const detection = await faceapi.detectSingleFace(input)
  3. ```

By default detectAllFaces and detectSingleFace utilize the SSD Mobilenet V1 Face Detector. You can specify the face detector by passing the corresponding options object:

  1. ``` javascript
  2. const detections1 = await faceapi.detectAllFaces(input, new faceapi.SsdMobilenetv1Options())
  3. const detections2 = await faceapi.detectAllFaces(input, new faceapi.TinyFaceDetectorOptions())
  4. ```

You can tune the options of each face detector as shown here.

Detecting 68 Face Landmark Points


After face detection, we can furthermore predict the facial landmarks for each detected face as follows:

Detect all faces in an image + computes 68 Point Face Landmarks for each detected face. Returns **Array<[WithFaceLandmarks>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks()
  3. ```

Detect the face with the highest confidence score in an image + computes 68 Point Face Landmarks for that face. Returns **[WithFaceLandmarks>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const detectionWithLandmarks = await faceapi.detectSingleFace(input).withFaceLandmarks()
  3. ```

You can also specify to use the tiny model instead of the default model:

  1. ``` javascript
  2. const useTinyModel = true
  3. const detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks(useTinyModel)
  4. ```

Computing Face Descriptors


After face detection and facial landmark prediction the face descriptors for each face can be computed as follows:

Detect all faces in an image + compute 68 Point Face Landmarks for each detected face. Returns **Array<[WithFaceDescriptor>>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const results = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()
  3. ```

Detect the face with the highest confidence score in an image + compute 68 Point Face Landmarks and face descriptor for that face. Returns **[WithFaceDescriptor>>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const result = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceDescriptor()
  3. ```

Recognizing Face Expressions


Face expression recognition can be performed for detected faces as follows:

Detect all faces in an image + recognize face expressions of each face. Returns **Array<[WithFaceExpressions>>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()
  3. ```

Detect the face with the highest confidence score in an image + recognize the face expressions for that face. Returns **[WithFaceExpressions>>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()
  3. ```

You can also skip .withFaceLandmarks(), which will skip the face alignment step (less stable accuracy):

Detect all faces without face alignment + recognize face expressions of each face. Returns **Array<[WithFaceExpressions>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceExpressions()
  3. ```

Detect the face with the highest confidence score without face alignment + recognize the face expression for that face. Returns **[WithFaceExpressions>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceExpressions()
  3. ```

Age Estimation and Gender Recognition


Age estimation and gender recognition from detected faces can be done as follows:

Detect all faces in an image + estimate age and recognize gender of each face. Returns **Array<[WithAge>>>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender()
  3. ```

Detect the face with the highest confidence score in an image + estimate age and recognize gender for that face. Returns **[WithAge>>>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender()
  3. ```

You can also skip .withFaceLandmarks(), which will skip the face alignment step (less stable accuracy):

Detect all faces without face alignment + estimate age and recognize gender of each face. Returns **Array<[WithAge>>](#getting-started-utility-classes)>**:

  1. ``` javascript
  2. const detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withAgeAndGender()
  3. ```

Detect the face with the highest confidence score without face alignment + estimate age and recognize gender for that face. Returns **[WithAge>>](#getting-started-utility-classes) | undefined**:

  1. ``` javascript
  2. const detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withAgeAndGender()
  3. ```

Composition of Tasks


Tasks can be composed as follows:

  1. ``` javascript
  2. // all faces
  3. await faceapi.detectAllFaces(input)
  4. await faceapi.detectAllFaces(input).withFaceExpressions()
  5. await faceapi.detectAllFaces(input).withFaceLandmarks()
  6. await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()
  7. await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptors()
  8. await faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptors()
  9. await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptors()

  10. // single face
  11. await faceapi.detectSingleFace(input)
  12. await faceapi.detectSingleFace(input).withFaceExpressions()
  13. await faceapi.detectSingleFace(input).withFaceLandmarks()
  14. await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()
  15. await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptor()
  16. await faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptor()
  17. await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptor()
  18. ```

Face Recognition by Matching Descriptors


To perform face recognition, one can use faceapi.FaceMatcher to compare reference face descriptors to query face descriptors.

First, we initialize the FaceMatcher with the reference data, for example we can simply detect faces in a referenceImage and match the descriptors of the detected faces to faces of subsequent images:

  1. ``` javascript
  2. const results = await faceapi
  3.   .detectAllFaces(referenceImage)
  4.   .withFaceLandmarks()
  5.   .withFaceDescriptors()

  6. if (!results.length) {
  7.   return
  8. }

  9. // create FaceMatcher with automatically assigned labels
  10. // from the detection results for the reference image
  11. const faceMatcher = new faceapi.FaceMatcher(results)
  12. ```

Now we can recognize a persons face shown in queryImage1:

  1. ``` javascript
  2. const singleResult = await faceapi
  3.   .detectSingleFace(queryImage1)
  4.   .withFaceLandmarks()
  5.   .withFaceDescriptor()

  6. if (singleResult) {
  7.   const bestMatch = faceMatcher.findBestMatch(singleResult.descriptor)
  8.   console.log(bestMatch.toString())
  9. }
  10. ```

Or we can recognize all faces shown in queryImage2:

  1. ``` javascript
  2. const results = await faceapi
  3.   .detectAllFaces(queryImage2)
  4.   .withFaceLandmarks()
  5.   .withFaceDescriptors()

  6. results.forEach(fd => {
  7.   const bestMatch = faceMatcher.findBestMatch(fd.descriptor)
  8.   console.log(bestMatch.toString())
  9. })
  10. ```

You can also create labeled reference descriptors as follows:

  1. ``` javascript
  2. const labeledDescriptors = [
  3.   new faceapi.LabeledFaceDescriptors(
  4.     'obama',
  5.     [descriptorObama1, descriptorObama2]
  6.   ),
  7.   new faceapi.LabeledFaceDescriptors(
  8.     'trump',
  9.     [descriptorTrump]
  10.   )
  11. ]

  12. const faceMatcher = new faceapi.FaceMatcher(labeledDescriptors)
  13. ```


Displaying Detection Results


Preparing the overlay canvas:

  1. ``` javascript
  2. const displaySize = { width: input.width, height: input.height }
  3. // resize the overlay canvas to the input dimensions
  4. const canvas = document.getElementById('overlay')
  5. faceapi.matchDimensions(canvas, displaySize)
  6. ```

face-api.js predefines some highlevel drawing functions, which you can utilize:

  1. ``` javascript
  2. /* Display detected face bounding boxes */
  3. const detections = await faceapi.detectAllFaces(input)
  4. // resize the detected boxes in case your displayed image has a different size than the original
  5. const resizedDetections = faceapi.resizeResults(detections, displaySize)
  6. // draw detections into the canvas
  7. faceapi.draw.drawDetections(canvas, resizedDetections)

  8. /* Display face landmarks */
  9. const detectionsWithLandmarks = await faceapi
  10.   .detectAllFaces(input)
  11.   .withFaceLandmarks()
  12. // resize the detected boxes and landmarks in case your displayed image has a different size than the original
  13. const resizedResults = faceapi.resizeResults(detectionsWithLandmarks, displaySize)
  14. // draw detections into the canvas
  15. faceapi.draw.drawDetections(canvas, resizedResults)
  16. // draw the landmarks into the canvas
  17. faceapi.draw.drawFaceLandmarks(canvas, resizedResults)


  18. /* Display face expression results */
  19. const detectionsWithExpressions = await faceapi
  20.   .detectAllFaces(input)
  21.   .withFaceLandmarks()
  22.   .withFaceExpressions()
  23. // resize the detected boxes and landmarks in case your displayed image has a different size than the original
  24. const resizedResults = faceapi.resizeResults(detectionsWithExpressions, displaySize)
  25. // draw detections into the canvas
  26. faceapi.draw.drawDetections(canvas, resizedResults)
  27. // draw a textbox displaying the face expressions with minimum probability into the canvas
  28. const minProbability = 0.05
  29. faceapi.draw.drawFaceExpressions(canvas, resizedResults, minProbability)
  30. ```

You can also draw boxes with custom text (DrawBox):

  1. ``` javascript
  2. const box = { x: 50, y: 50, width: 100, height: 100 }
  3. // see DrawBoxOptions below
  4. const drawOptions = {
  5.   label: 'Hello I am a box!',
  6.   lineWidth: 2
  7. }
  8. const drawBox = new faceapi.draw.DrawBox(box, drawOptions)
  9. drawBox.draw(document.getElementById('myCanvas'))
  10. ```

DrawBox drawing options:

  1. ``` javascript
  2. export interface IDrawBoxOptions {
  3.   boxColor?: string
  4.   lineWidth?: number
  5.   drawLabelOptions?: IDrawTextFieldOptions
  6.   label?: string
  7. }
  8. ```

Finally you can draw custom text fields (DrawTextField):

  1. ``` javascript
  2. const text = [
  3.   'This is a textline!',
  4.   'This is another textline!'
  5. ]
  6. const anchor = { x: 200, y: 200 }
  7. // see DrawTextField below
  8. const drawOptions = {
  9.   anchorPosition: 'TOP_LEFT',
  10.   backgroundColor: 'rgba(0, 0, 0, 0.5)'
  11. }
  12. const drawBox = new faceapi.draw.DrawTextField(text, anchor, drawOptions)
  13. drawBox.draw(document.getElementById('myCanvas'))
  14. ```

DrawTextField drawing options:

  1. ``` javascript
  2. export interface IDrawTextFieldOptions {
  3.   anchorPosition?: AnchorPosition
  4.   backgroundColor?: string
  5.   fontColor?: string
  6.   fontSize?: number
  7.   fontStyle?: string
  8.   padding?: number
  9. }

  10. export enum AnchorPosition {
  11.   TOP_LEFT = 'TOP_LEFT',
  12.   TOP_RIGHT = 'TOP_RIGHT',
  13.   BOTTOM_LEFT = 'BOTTOM_LEFT',
  14.   BOTTOM_RIGHT = 'BOTTOM_RIGHT'
  15. }
  16. ```


Face Detection Options


SsdMobilenetv1Options


  1. ``` javascript
  2. export interface ISsdMobilenetv1Options {
  3.   // minimum confidence threshold
  4.   // default: 0.5
  5.   minConfidence?: number

  6.   // maximum number of faces to return
  7.   // default: 100
  8.   maxResults?: number
  9. }

  10. // example
  11. const options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.8 })
  12. ```

TinyFaceDetectorOptions


  1. ``` javascript
  2. export interface ITinyFaceDetectorOptions {
  3.   // size at which image is processed, the smaller the faster,
  4.   // but less precise in detecting smaller faces, must be divisible
  5.   // by 32, common sizes are 128, 160, 224, 320, 416, 512, 608,
  6.   // for face tracking via webcam I would recommend using smaller sizes,
  7.   // e.g. 128, 160, for detecting smaller faces use larger sizes, e.g. 512, 608
  8.   // default: 416
  9.   inputSize?: number

  10.   // minimum confidence threshold
  11.   // default: 0.5
  12.   scoreThreshold?: number
  13. }

  14. // example
  15. const options = new faceapi.TinyFaceDetectorOptions({ inputSize: 320 })
  16. ```


Utility Classes


IBox


  1. ``` javascript
  2. export interface IBox {
  3.   x: number
  4.   y: number
  5.   width: number
  6.   height: number
  7. }
  8. ```

IFaceDetection


  1. ``` javascript
  2. export interface IFaceDetection {
  3.   score: number
  4.   box: Box
  5. }
  6. ```

IFaceLandmarks


  1. ``` javascript
  2. export interface IFaceLandmarks {
  3.   positions: Point[]
  4.   shift: Point
  5. }
  6. ```

WithFaceDetection


  1. ``` javascript
  2. export type WithFaceDetection<TSource> = TSource & {
  3.   detection: FaceDetection
  4. }
  5. ```

WithFaceLandmarks


  1. ``` javascript
  2. export type WithFaceLandmarks<TSource> = TSource & {
  3.   unshiftedLandmarks: FaceLandmarks
  4.   landmarks: FaceLandmarks
  5.   alignedRect: FaceDetection
  6. }
  7. ```

WithFaceDescriptor


  1. ``` javascript
  2. export type WithFaceDescriptor<TSource> = TSource & {
  3.   descriptor: Float32Array
  4. }
  5. ```

WithFaceExpressions


  1. ``` javascript
  2. export type WithFaceExpressions<TSource> = TSource & {
  3.   expressions: FaceExpressions
  4. }
  5. ```

WithAge


  1. ``` javascript
  2. export type WithAge<TSource> = TSource & {
  3.   age: number
  4. }
  5. ```

WithGender


  1. ``` javascript
  2. export type WithGender<TSource> = TSource & {
  3.   gender: Gender
  4.   genderProbability: number
  5. }

  6. export enum Gender {
  7.   FEMALE = 'female',
  8.   MALE = 'male'
  9. }
  10. ```


Other Useful Utility


Using the Low Level API


Instead of using the high level API, you can directly use the forward methods of each neural network:

  1. ``` javascript
  2. const detections1 = await faceapi.ssdMobilenetv1(input, options)
  3. const detections2 = await faceapi.tinyFaceDetector(input, options)
  4. const landmarks1 = await faceapi.detectFaceLandmarks(faceImage)
  5. const landmarks2 = await faceapi.detectFaceLandmarksTiny(faceImage)
  6. const descriptor = await faceapi.computeFaceDescriptor(alignedFaceImage)
  7. ```

Extracting a Canvas for an Image Region


  1. ``` javascript
  2. const regionsToExtract = [
  3.   new faceapi.Rect(0, 0, 100, 100)
  4. ]
  5. // actually extractFaces is meant to extract face regions from bounding boxes
  6. // but you can also use it to extract any other region
  7. const canvases = await faceapi.extractFaces(input, regionsToExtract)
  8. ```

Euclidean Distance


  1. ``` javascript
  2. // ment to be used for computing the euclidean distance between two face descriptors
  3. const dist = faceapi.euclideanDistance([0, 0], [0, 10])
  4. console.log(dist) // 10
  5. ```

Retrieve the Face Landmark Points and Contours


  1. ``` javascript
  2. const landmarkPositions = landmarks.positions

  3. // or get the positions of individual contours,
  4. // only available for 68 point face ladnamrks (FaceLandmarks68)
  5. const jawOutline = landmarks.getJawOutline()
  6. const nose = landmarks.getNose()
  7. const mouth = landmarks.getMouth()
  8. const leftEye = landmarks.getLeftEye()
  9. const rightEye = landmarks.getRightEye()
  10. const leftEyeBbrow = landmarks.getLeftEyeBrow()
  11. const rightEyeBrow = landmarks.getRightEyeBrow()
  12. ```

Fetch and Display Images from an URL


  1. ``` html
  2. <img id="myImg" src="">
  3. ```

  1. ``` javascript
  2. const image = await faceapi.fetchImage('/images/example.png')

  3. console.log(image instanceof HTMLImageElement) // true

  4. // displaying the fetched image content
  5. const myImg = document.getElementById('myImg')
  6. myImg.src = image.src
  7. ```

Fetching JSON


  1. ``` javascript
  2. const json = await faceapi.fetchJson('/files/example.json')
  3. ```

Creating an Image Picker


  1. ``` html
  2. <img id="myImg" src="">
  3. <input id="myFileUpload" type="file" onchange="uploadImage()" accept=".jpg, .jpeg, .png">
  4. ```

  1. ``` javascript
  2. async function uploadImage() {
  3.   const imgFile = document.getElementById('myFileUpload').files[0]
  4.   // create an HTMLImageElement from a Blob
  5.   const img = await faceapi.bufferToImage(imgFile)
  6.   document.getElementById('myImg').src = img.src
  7. }
  8. ```

Creating a Canvas Element from an Image or Video Element


  1. ``` html
  2. <img id="myImg" src="images/example.png" />
  3. <video id="myVideo" src="media/example.mp4" />
  4. ```

  1. ``` javascript
  2. const canvas1 = faceapi.createCanvasFromMedia(document.getElementById('myImg'))
  3. const canvas2 = faceapi.createCanvasFromMedia(document.getElementById('myVideo'))
  4. ```


Available Models



Face Detection Models


SSD Mobilenet V1


For face detection, this project implements a SSD (Single Shot Multibox Detector) based on MobileNetV1. The neural net will compute the locations of each face in an image and will return the bounding boxes together with it's probability for each face. This face detector is aiming towards obtaining high accuracy in detecting face bounding boxes instead of low inference time. The size of the quantized model is about 5.4 MB (ssd_mobilenetv1_model).

The face detection model has been trained on the WIDERFACE dataset and the weights are provided by yeephycho in this repo.

Tiny Face Detector


The Tiny Face Detector is a very performant, realtime face detector, which is much faster, smaller and less resource consuming compared to the SSD Mobilenet V1 face detector, in return it performs slightly less well on detecting small faces. This model is extremely mobile and web friendly, thus it should be your GO-TO face detector on mobile devices and resource limited clients. The size of the quantized model is only 190 KB (tiny_face_detector_model).

The face detector has been trained on a custom dataset of ~14K images labeled with bounding boxes. Furthermore the model has been trained to predict bounding boxes, which entirely cover facial feature points, thus it in general produces better results in combination with subsequent face landmark detection than SSD Mobilenet V1.

This model is basically an even tinier version of Tiny Yolo V2, replacing the regular convolutions of Yolo with depthwise separable convolutions. Yolo is fully convolutional, thus can easily adapt to different input image sizes to trade off accuracy for performance (inference time).


68 Point Face Landmark Detection Models


This package implements a very lightweight and fast, yet accurate 68 point face landmark detector. The default model has a size of only 350kb (face_landmark_68_model) and the tiny model is only 80kb (face_landmark_68_tiny_model). Both models employ the ideas of depthwise separable convolutions as well as densely connected blocks. The models have been trained on a dataset of ~35k face images labeled with 68 face landmark points.


Face Recognition Model


For face recognition, a ResNet-34 like architecture is implemented to compute a face descriptor (a feature vector with 128 values) from any given face image, which is used to describe the characteristics of a persons face. The model is not limited to the set of faces used for training, meaning you can use it for face recognition of any person, for example yourself. You can determine the similarity of two arbitrary faces by comparing their face descriptors, for example by computing the euclidean distance or using any other classifier of your choice.

The neural net is equivalent to the FaceRecognizerNet used in face-recognition.js and the net used in the dlib face recognition example. The weights have been trained by davisking and the model achieves a prediction accuracy of 99.38% on the LFW (Labeled Faces in the Wild) benchmark for face recognition.

The size of the quantized model is roughly 6.2 MB (face_recognition_model).


Face Expression Recognition Model


The face expression recognition model is lightweight, fast and provides reasonable accuracy. The model has a size of roughly 310kb and it employs depthwise separable convolutions and densely connected blocks. It has been trained on a variety of images from publicly available datasets as well as images scraped from the web. Note, that wearing glasses might decrease the accuracy of the prediction results.


Age and Gender Recognition Model


The age and gender recognition model is a multitask network, which employs a feature extraction layer, an age regression layer and a gender classifier. The model has a size of roughly 420kb and the feature extractor employs a tinier but very similar architecture to Xception.

This model has been trained and tested on the following databases with an 80/20 train/test split each: UTK, FGNET, Chalearn, Wiki, IMDB, CACD, MegaAge, MegaAge-Asian. The * indicates, that these databases have been algorithmically cleaned up, since the initial databases are very noisy.

Total Test Results


Total MAE (Mean Age Error): 4.54

Total Gender Accuracy: 95%

Test results for each database


The - indicates, that there are no gender labels available for these databases.

Database        | UTK    | FGNET | Chalearn | Wiki | IMDB | CACD | MegaAge | MegaAge-Asian |
MAE             | 5.25   | 4.23  | 6.24     | 6.54 | 3.63  | 3.20  | 6.23    | 4.21          |
Gender Accuracy | 0.93   | -     | 0.94     | 0.95 | -     | 0.97  | -       | -             |

Test results for different age category groups


Age Range       | 0 - 3  | 4 - 8 | 9 - 18 | 19 - 28 | 29 - 40 | 41 - 60 | 60 - 80 | 80+     |
MAE             | 1.52   | 3.06  | 4.82   | 4.99    | 5.43    | 4.94    | 6.17    | 9.91    |
Gender Accuracy | 0.69   | 0.80  | 0.88   | 0.96    | 0.97    | 0.97    | 0.96    | 0.9     |