JavaScript API for face detection and face recognition in the browser and nodejs with tensorflow.js

Overview

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

Click me for Live Demos!

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:

git clone https://github.com/justadudewhohacks/face-api.js.git

Running the Browser Examples

cd face-api.js/examples/examples-browser
npm i
npm start

Browse to http://localhost:3000/.

Running the Nodejs Examples

cd face-api.js/examples/examples-nodejs
npm i

Now run one of the examples using ts-node:

ts-node faceDetection.ts

Or simply compile and run them with node:

tsc faceDetection.ts
node faceDetection.js

face-api.js for the Browser

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

Or install it via npm:

npm i face-api.js

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:

npm i face-api.js canvas @tensorflow/tfjs-node

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

// import nodejs bindings to native tensorflow,
// not required, but will speed up things drastically (python required)
import '@tensorflow/tfjs-node';

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

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

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

Getting Started

Loading the Models

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

console.log(faceapi.nets)
// ageGenderNet
// faceExpressionNet
// faceLandmark68Net
// faceLandmark68TinyNet
// faceRecognitionNet
// ssdMobilenetv1
// tinyFaceDetector
// tinyYolov2

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:

await faceapi.nets.ssdMobilenetv1.loadFromUri('/models')
// accordingly for the other models:
// await faceapi.nets.faceLandmark68Net.loadFromUri('/models')
// await faceapi.nets.faceRecognitionNet.loadFromUri('/models')
// ...

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

await faceapi.nets.ssdMobilenetv1.loadFromDisk('./models')

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

await faceapi.nets.ssdMobilenetv1.loadFromWeightMap(weightMap)

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

const net = new faceapi.SsdMobilenetv1()
await net.loadFromUri('/models')

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

// using fetch
net.load(await faceapi.fetchNetWeights('/models/face_detection_model.weights'))

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

High Level API

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

<img id="myImg" src="images/example.png" />
<video id="myVideo" src="media/example.mp4" />
<canvas id="myCanvas" />
const input = document.getElementById('myImg')
// const input = document.getElementById('myVideo')
// const input = document.getElementById('myCanvas')
// or simply:
// const input = 'myImg'

Detecting Faces

Detect all faces in an image. Returns Array<FaceDetection>:

const detections = await faceapi.detectAllFaces(input)

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

const detection = await faceapi.detectSingleFace(input)

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

const detections1 = await faceapi.detectAllFaces(input, new faceapi.SsdMobilenetv1Options())
const detections2 = await faceapi.detectAllFaces(input, new faceapi.TinyFaceDetectorOptions())

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<WithFaceDetection<{}>>>:

const detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks()

Detect the face with the highest confidence score in an image + computes 68 Point Face Landmarks for that face. Returns WithFaceLandmarks<WithFaceDetection<{}>> | undefined:

const detectionWithLandmarks = await faceapi.detectSingleFace(input).withFaceLandmarks()

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

const useTinyModel = true
const detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks(useTinyModel)

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<WithFaceLandmarks<WithFaceDetection<{}>>>>:

const results = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()

Detect the face with the highest confidence score in an image + compute 68 Point Face Landmarks and face descriptor for that face. Returns WithFaceDescriptor<WithFaceLandmarks<WithFaceDetection<{}>>> | undefined:

const result = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceDescriptor()

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<WithFaceLandmarks<WithFaceDetection<{}>>>>:

const detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()

Detect the face with the highest confidence score in an image + recognize the face expressions for that face. Returns WithFaceExpressions<WithFaceLandmarks<WithFaceDetection<{}>>> | undefined:

const detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()

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<WithFaceDetection<{}>>>:

const detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceExpressions()

Detect the face with the highest confidence score without face alignment + recognize the face expression for that face. Returns WithFaceExpressions<WithFaceDetection<{}>> | undefined:

const detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceExpressions()

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<WithGender<WithFaceLandmarks<WithFaceDetection<{}>>>>>:

const detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender()

Detect the face with the highest confidence score in an image + estimate age and recognize gender for that face. Returns WithAge<WithGender<WithFaceLandmarks<WithFaceDetection<{}>>>> | undefined:

const detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender()

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<WithGender<WithFaceDetection<{}>>>>:

const detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withAgeAndGender()

Detect the face with the highest confidence score without face alignment + estimate age and recognize gender for that face. Returns WithAge<WithGender<WithFaceDetection<{}>>> | undefined:

const detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withAgeAndGender()

Composition of Tasks

Tasks can be composed as follows:

// all faces
await faceapi.detectAllFaces(input)
await faceapi.detectAllFaces(input).withFaceExpressions()
await faceapi.detectAllFaces(input).withFaceLandmarks()
await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()
await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptors()
await faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptors()
await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptors()

// single face
await faceapi.detectSingleFace(input)
await faceapi.detectSingleFace(input).withFaceExpressions()
await faceapi.detectSingleFace(input).withFaceLandmarks()
await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()
await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptor()
await faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptor()
await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptor()

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:

const results = await faceapi
  .detectAllFaces(referenceImage)
  .withFaceLandmarks()
  .withFaceDescriptors()

if (!results.length) {
  return
}

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

Now we can recognize a persons face shown in queryImage1:

const singleResult = await faceapi
  .detectSingleFace(queryImage1)
  .withFaceLandmarks()
  .withFaceDescriptor()

if (singleResult) {
  const bestMatch = faceMatcher.findBestMatch(singleResult.descriptor)
  console.log(bestMatch.toString())
}

Or we can recognize all faces shown in queryImage2:

const results = await faceapi
  .detectAllFaces(queryImage2)
  .withFaceLandmarks()
  .withFaceDescriptors()

results.forEach(fd => {
  const bestMatch = faceMatcher.findBestMatch(fd.descriptor)
  console.log(bestMatch.toString())
})

You can also create labeled reference descriptors as follows:

const labeledDescriptors = [
  new faceapi.LabeledFaceDescriptors(
    'obama',
    [descriptorObama1, descriptorObama2]
  ),
  new faceapi.LabeledFaceDescriptors(
    'trump',
    [descriptorTrump]
  )
]

const faceMatcher = new faceapi.FaceMatcher(labeledDescriptors)

Displaying Detection Results

Preparing the overlay canvas:

const displaySize = { width: input.width, height: input.height }
// resize the overlay canvas to the input dimensions
const canvas = document.getElementById('overlay')
faceapi.matchDimensions(canvas, displaySize)

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

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

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


/* Display face expression results */
const detectionsWithExpressions = await faceapi
  .detectAllFaces(input)
  .withFaceLandmarks()
  .withFaceExpressions()
// resize the detected boxes and landmarks in case your displayed image has a different size than the original
const resizedResults = faceapi.resizeResults(detectionsWithExpressions, displaySize)
// draw detections into the canvas
faceapi.draw.drawDetections(canvas, resizedResults)
// draw a textbox displaying the face expressions with minimum probability into the canvas
const minProbability = 0.05
faceapi.draw.drawFaceExpressions(canvas, resizedResults, minProbability)

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

const box = { x: 50, y: 50, width: 100, height: 100 }
// see DrawBoxOptions below
const drawOptions = {
  label: 'Hello I am a box!',
  lineWidth: 2
}
const drawBox = new faceapi.draw.DrawBox(box, drawOptions)
drawBox.draw(document.getElementById('myCanvas'))

DrawBox drawing options:

export interface IDrawBoxOptions {
  boxColor?: string
  lineWidth?: number
  drawLabelOptions?: IDrawTextFieldOptions
  label?: string
}

Finally you can draw custom text fields (DrawTextField):

const text = [
  'This is a textline!',
  'This is another textline!'
]
const anchor = { x: 200, y: 200 }
// see DrawTextField below
const drawOptions = {
  anchorPosition: 'TOP_LEFT',
  backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
const drawBox = new faceapi.draw.DrawTextField(text, anchor, drawOptions)
drawBox.draw(document.getElementById('myCanvas'))

DrawTextField drawing options:

export interface IDrawTextFieldOptions {
  anchorPosition?: AnchorPosition
  backgroundColor?: string
  fontColor?: string
  fontSize?: number
  fontStyle?: string
  padding?: number
}

export enum AnchorPosition {
  TOP_LEFT = 'TOP_LEFT',
  TOP_RIGHT = 'TOP_RIGHT',
  BOTTOM_LEFT = 'BOTTOM_LEFT',
  BOTTOM_RIGHT = 'BOTTOM_RIGHT'
}

Face Detection Options

SsdMobilenetv1Options

export interface ISsdMobilenetv1Options {
  // minimum confidence threshold
  // default: 0.5
  minConfidence?: number

  // maximum number of faces to return
  // default: 100
  maxResults?: number
}

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

TinyFaceDetectorOptions

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

  // minimum confidence threshold
  // default: 0.5
  scoreThreshold?: number
}

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

Utility Classes

IBox

export interface IBox {
  x: number
  y: number
  width: number
  height: number
}

IFaceDetection

export interface IFaceDetection {
  score: number
  box: Box
}

IFaceLandmarks

export interface IFaceLandmarks {
  positions: Point[]
  shift: Point
}

WithFaceDetection

export type WithFaceDetection<TSource> = TSource & {
  detection: FaceDetection
}

WithFaceLandmarks

export type WithFaceLandmarks<TSource> = TSource & {
  unshiftedLandmarks: FaceLandmarks
  landmarks: FaceLandmarks
  alignedRect: FaceDetection
}

WithFaceDescriptor

export type WithFaceDescriptor<TSource> = TSource & {
  descriptor: Float32Array
}

WithFaceExpressions

export type WithFaceExpressions<TSource> = TSource & {
  expressions: FaceExpressions
}

WithAge

export type WithAge<TSource> = TSource & {
  age: number
}

WithGender

export type WithGender<TSource> = TSource & {
  gender: Gender
  genderProbability: number
}

export enum Gender {
  FEMALE = 'female',
  MALE = 'male'
}

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:

const detections1 = await faceapi.ssdMobilenetv1(input, options)
const detections2 = await faceapi.tinyFaceDetector(input, options)
const landmarks1 = await faceapi.detectFaceLandmarks(faceImage)
const landmarks2 = await faceapi.detectFaceLandmarksTiny(faceImage)
const descriptor = await faceapi.computeFaceDescriptor(alignedFaceImage)

Extracting a Canvas for an Image Region

const regionsToExtract = [
  new faceapi.Rect(0, 0, 100, 100)
]
// actually extractFaces is meant to extract face regions from bounding boxes
// but you can also use it to extract any other region
const canvases = await faceapi.extractFaces(input, regionsToExtract)

Euclidean Distance

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

Retrieve the Face Landmark Points and Contours

const landmarkPositions = landmarks.positions

// or get the positions of individual contours,
// only available for 68 point face ladnamrks (FaceLandmarks68)
const jawOutline = landmarks.getJawOutline()
const nose = landmarks.getNose()
const mouth = landmarks.getMouth()
const leftEye = landmarks.getLeftEye()
const rightEye = landmarks.getRightEye()
const leftEyeBbrow = landmarks.getLeftEyeBrow()
const rightEyeBrow = landmarks.getRightEyeBrow()

Fetch and Display Images from an URL

<img id="myImg" src="">
const image = await faceapi.fetchImage('/images/example.png')

console.log(image instanceof HTMLImageElement) // true

// displaying the fetched image content
const myImg = document.getElementById('myImg')
myImg.src = image.src

Fetching JSON

const json = await faceapi.fetchJson('/files/example.json')

Creating an Image Picker

<img id="myImg" src="">
<input id="myFileUpload" type="file" onchange="uploadImage()" accept=".jpg, .jpeg, .png">
async function uploadImage() {
  const imgFile = document.getElementById('myFileUpload').files[0]
  // create an HTMLImageElement from a Blob
  const img = await faceapi.bufferToImage(imgFile)
  document.getElementById('myImg').src = img.src
}

Creating a Canvas Element from an Image or Video Element

<img id="myImg" src="images/example.png" />
<video id="myVideo" src="media/example.mp4" />
const canvas1 = faceapi.createCanvasFromMedia(document.getElementById('myImg'))
const canvas2 = faceapi.createCanvasFromMedia(document.getElementById('myVideo'))

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
Comments
  • Load image take too much time

    Load image take too much time

    Hi, I used this face-api.js (https://github.com/justadudewhohacks/face-api.js) and I have to load 10000 images when the node server is loaded for future comparison operations. This the function that I load when server is loaded, it take 0.5 second to one picture, how can I improve it ?

    **// fetch first image of each class and compute their descriptors
    async function createBbtFaceMatcher() {
    
      await faceDetectionNet.loadFromDisk(path.join(__dirname, '../weights'))
      await faceapi.nets.faceLandmark68Net.loadFromDisk(path.join(__dirname, '../weights'))
      await faceapi.nets.faceRecognitionNet.loadFromDisk(path.join(__dirname, '../weights'))
    
    
      const labeledFaceDescriptors = await Promise.all(classes.map(
        async className => {
          let descriptors: any = [];
          let uri = getFaceImageUri(className, 1);
          const img = await canvas.loadImage(uri);
          if (img) {
            let descriptor = await faceapi.computeFaceDescriptor(img);
            if (descriptor) {
              descriptors.push(descriptor);
            }
          }
          return new faceapi.LabeledFaceDescriptors(
            className,
            descriptors
          )
        }
      )) 
    

    return new faceapi.FaceMatcher(labeledFaceDescriptors) }**

    opened by danies8 54
  • Issue loading: TypeError: Nt.makeTensor is not a function

    Issue loading: TypeError: Nt.makeTensor is not a function

    I just started and in the latest version I am getting the following error in the browser:

    tf-core.esm.js:17 Uncaught (in promise) TypeError: Nt.makeTensor is not a function
        at Sn (tf-core.esm.js:17)
        at kn (tf-core.esm.js:17)
        at o (tf-core.esm.js:17)
        at Fh (tf-core.esm.js:17)
        at tf-core.esm.js:17
        at Array.forEach (<anonymous>)
        at tf-core.esm.js:17
        at Array.forEach (<anonymous>)
        at tf-core.esm.js:17
        at tf-core.esm.js:17
    

    I installed face-api.js with npm install face-api.js. Now using it as follows:

    import * as faceapi from 'face-api.js';
    
    await faceapi.nets.tinyFaceDetector.loadFromUri('/models');
    

    As soon as I try to load the model, I get the type error above. Any idea's where it is going wrong? I saw this https://github.com/tensorflow/tfjs/issues/2194#issuecomment-546187719 but couldn't see a solution to that. Thanks!

    opened by luucv 25
  • Face detection don't work on AWS Lambda due to node-canvas not working on node 8.10

    Face detection don't work on AWS Lambda due to node-canvas not working on node 8.10

    Hi there!

    I am trying to get this up and running on AWS Lambda but are having trouble as it seem the 'canvas' package is broken on node 8.10. I am trying to get some face detection going.

    https://github.com/Automattic/node-canvas/issues/1252#issuecomment-437598572

    It looks like its kind of a pain to try and run any other version of node on AWS Lambda, so I started trying to use it without the canvas package. As you mention in the README and I also noticed that the faceapi.locateFaces() function also takes a Tensor4D class as input. I have never used Tensorflow and I am a little confused as how to turn a ArrayBuffer from axios into a correctly shaped Tensor4D object.

    I am fetching a jpeg image using axios.

    I found the tf.tensor4d function but not sure what shape and dtype it should be.

    Do you have any idea?

    My code so far:

    const { data: imageBuffer } = await axios.get(url, {
    	responseType: 'arraybuffer'
    })
    const imageTensor = tf.tensor4d(imageBuffer, [?, ?, ? ,?])
    const faces = await detector.locateFaces(imageTensor)
    

    Error messages look similar to this one:

    Error: Based on the provided shape, [1,2,3,4], and dtype float32, the tensor should have 24 values but has 68695

    Any help is greatly appreciated!

    opened by bobmoff 24
  • Error: Based on the provided shape, [1,1,16,32], and dtype float32, the tensor should have 512 values but has 93

    Error: Based on the provided shape, [1,1,16,32], and dtype float32, the tensor should have 512 values but has 93

    Hi! I'm having trouble making the library work on production. Everything works perfect locally. Using angular 4. Here is the code:

    const detections: Array<any> = await faceapi.detectAllFaces(this.video, new faceapi.TinyFaceDetectorOptions({ inputSize: 128, scoreThreshold: 0.4 }));

    ERROR Error: Uncaught (in promise): Error: Based on the provided shape, [1,1,16,32], and dtype float32, the tensor should have 512 values but has 93 Error: Based on the provided shape, [1,1,16,32], and dtype float32, the tensor should have 512 values but has 93 at c (scripts.208b17eda93ff84a86fa.bundle.js:1) at new t (scripts.208b17eda93ff84a86fa.bundle.js:1) at Function.t.make (scripts.208b17eda93ff84a86fa.bundle.js:1) at Ht (scripts.208b17eda93ff84a86fa.bundle.js:1) at o (scripts.208b17eda93ff84a86fa.bundle.js:1) at $a (scripts.208b17eda93ff84a86fa.bundle.js:1) at scripts.208b17eda93ff84a86fa.bundle.js:1 at Array.forEach () at scripts.208b17eda93ff84a86fa.bundle.js:1 at Array.forEach () at c (scripts.208b17eda93ff84a86fa.bundle.js:1) at new t (scripts.208b17eda93ff84a86fa.bundle.js:1) at Function.t.make (scripts.208b17eda93ff84a86fa.bundle.js:1) at Ht (scripts.208b17eda93ff84a86fa.bundle.js:1) at o (scripts.208b17eda93ff84a86fa.bundle.js:1) at $a (scripts.208b17eda93ff84a86fa.bundle.js:1) at scripts.208b17eda93ff84a86fa.bundle.js:1 at Array.forEach () at scripts.208b17eda93ff84a86fa.bundle.js:1 at Array.forEach () at S (polyfills.b05dc6a29a1cfeb080d6.bundle.js:1) at polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 at a (main.424b2f298a047510607b.bundle.js:1) at t.invoke (polyfills.b05dc6a29a1cfeb080d6.bundle.js:1) at Object.onInvoke (main.424b2f298a047510607b.bundle.js:1) at t.invoke (polyfills.b05dc6a29a1cfeb080d6.bundle.js:1) at e.run (polyfills.b05dc6a29a1cfeb080d6.bundle.js:1) at polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 at t.invokeTask (polyfills.b05dc6a29a1cfeb080d6.bundle.js:1) at Object.onInvokeTask (main.424b2f298a047510607b.bundle.js:1) $ @ main.424b2f298a047510607b.bundle.js:1 t.handleError @ main.424b2f298a047510607b.bundle.js:1 next @ main.424b2f298a047510607b.bundle.js:1 e.object.i @ main.424b2f298a047510607b.bundle.js:1 e.__tryOrUnsub @ main.424b2f298a047510607b.bundle.js:1 e.next @ main.424b2f298a047510607b.bundle.js:1 e._next @ main.424b2f298a047510607b.bundle.js:1 e.next @ main.424b2f298a047510607b.bundle.js:1 e.next @ main.424b2f298a047510607b.bundle.js:1 e.emit @ main.424b2f298a047510607b.bundle.js:1 (anonymous) @ main.424b2f298a047510607b.bundle.js:1 t.invoke @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 e.run @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 t.runOutsideAngular @ main.424b2f298a047510607b.bundle.js:1 onHandleError @ main.424b2f298a047510607b.bundle.js:1 t.handleError @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 e.runGuarded @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 t @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 n.microtaskDrainDone @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1 d @ polyfills.b05dc6a29a1cfeb080d6.bundle.js:1

    Also the video is 351x360 pixels

    opened by psiservices-azubizarreta 22
  • Bug-UnhandledPromiseRejectionWarning - OOM when allocating tensor with shape[1,256,256,64]

    Bug-UnhandledPromiseRejectionWarning - OOM when allocating tensor with shape[1,256,256,64]

    Hi, I tried to insert 10000 record to DB in loop using this link and got this error after 300 records. https://github.com/vladmandic/face-api/blob/master/demo/node-image.js

    2021-09-24 23:59:17.493963: W tensorflow/core/framework/op_kernel.cc:1767] OP_REQUIRES failed at cwise_ops_common.h:128 : Resource exhausted: OOM when allocating tensor with shape[1,256,256,64] and type float on /job:localhost/replica:0/task:0/device:CPU:0 by allocator cpu
    (node:21876) UnhandledPromiseRejectionWarning: Error: Invalid TF_Status: 8
    Message: OOM when allocating tensor with shape[1,256,256,64] and type float on /job:localhost/replica:0/task:0/device:CPU:0 by allocator cpu
        at Object.<anonymous> (<anonymous>)
    
    opened by danies8 21
  • How to speed it up after porting to node.js

    How to speed it up after porting to node.js

    I ported it to node.js to compare faces, but the operation was slow when extracting 128-dimensional feature vectors. I replaced the latest @ tensorflow/ tfjs and used require('@tensorflow/tfjs-node'), but it is not accelerated, it is still very slow, each method call below will wait 5-20 seconds, but in the browser can be faster, what can I do to speed it up?

            return tidy(function() {
                var batchTensor = input.toBatchTensor(150, true);
                var normalized = normalize(batchTensor);
                var out = convDown(normalized, params.conv32_down);
                out = maxPool(out, 3, 2, 'valid');
                out = residual(out, params.conv32_1);
                out = residual(out, params.conv32_2);
                out = residual(out, params.conv32_3);
                out = residualDown(out, params.conv64_down);
                out = residual(out, params.conv64_1);
                out = residual(out, params.conv64_2);
                out = residual(out, params.conv64_3);
                out = residualDown(out, params.conv128_down);
                out = residual(out, params.conv128_1);
                out = residual(out, params.conv128_2);
                out = residualDown(out, params.conv256_down);
                out = residual(out, params.conv256_1);
                out = residual(out, params.conv256_2);
                out = residualDown(out, params.conv256_down_out);
                var globalAvg = out.mean([1, 2]);
                var fullyConnected = matMul(globalAvg, params.fc);
                return fullyConnected;
            });
    
    opened by land007 14
  • Implementing mtcnn for face detection and 5 point landmarks

    Implementing mtcnn for face detection and 5 point landmarks

    The face detection and alignment approach of mtcnn from this paper seems to be a promising alternative for real time face detection + face alignment. Next thing on my TODO list.

    enhancement 
    opened by justadudewhohacks 13
  • Face detection stops when back/forwarding on video (React)

    Face detection stops when back/forwarding on video (React)

    Hi! I've written this piece of code to have a video player with some basic functions: go 5 seconds backward-forward, play/pause buttons, and a checkbox to show/hide the face-api canvas with its detections.

    import {React, useRef} from "react";
    import './App.css';
    import * as faceapi from "face-api.js/dist/face-api.min.js";
    
    function App() {
    
        let container = useRef();
        let video = useRef();
        let modelsLoaded = false;
        let checkboxChecked = false;
        let canvas;
        let displaySize;
    
        function backward(){
            video.current.currentTime -= 5;
        }
    
        function forward(){
            video.current.currentTime += 5;
        }
    
        function play(){
            video.current.play();
        }
    
        function pause(){
            video.current.pause();
        }
    
        function checkboxChanged() {
            checkboxChecked = !checkboxChecked;
            if(checkboxChecked === true)
                loadModels();
        }
    
    
        function loadModels(){
            if(modelsLoaded === false){
                console.log("Loading models...")
    
                Promise.all([
                    faceapi.nets.tinyFaceDetector.loadFromUri('./models'),
                    faceapi.nets.faceLandmark68Net.loadFromUri('./models'),
                    faceapi.nets.faceRecognitionNet.loadFromUri('./models'),
                    faceapi.nets.faceExpressionNet.loadFromUri('./models')
                ])
                    .then(() => {
                        console.log("Models loaded");
                        modelsLoaded = true;
                        createCanvas();
                        drawCanvas();
                    })
                    .catch((err) => console.log(err));
            }
            else{
                drawCanvas();
            }
        }
    
        function createCanvas(){
            canvas = faceapi.createCanvasFromMedia(video.current);
            canvas.style.position = "absolute";
            container.current.append(canvas);
            displaySize = { width: video.current.videoWidth, height: video.current.videoHeight };
            faceapi.matchDimensions(canvas, displaySize);
        }
    
        async function drawCanvas(){
            if(checkboxChecked){
                canvas.style.display = "block";
    
                const detections = await faceapi
                    .detectAllFaces(video.current, new faceapi.TinyFaceDetectorOptions())
                    .withFaceLandmarks()
                    .withFaceExpressions();
                const resizedDetections = faceapi.resizeResults(detections, displaySize);
                canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
                faceapi.draw.drawDetections(canvas, resizedDetections);
                faceapi.draw.drawFaceLandmarks(canvas, resizedDetections);
                faceapi.draw.drawFaceExpressions(canvas, resizedDetections);
    
                requestAnimationFrame(drawCanvas);
            }
            else{
                canvas.style.display = "none";
            }
    
    
        }
    
        return (
            <>
                <div ref={container} id={"face-api-container"} style={{display: "flex"}}>
                    <video ref={video} id={"video"} controls autoPlay={true} muted={true} src="sintel.mp4"></video>
                </div>
                <button id={"backward_btn"} onClick={backward}>Bwd 5s</button>
                <button id={"forward_btn"} onClick={forward}>Fwd 5s</button>
                <button id={"play_btn"} onClick={play}>Play</button>
                <button id={"pause_btn"} onClick={pause}>Pause</button>
                <br/>
                <input type={"checkbox"} onChange={checkboxChanged}
                />face-api
            </>
        );
    }
    
    export default App;
    

    This works fine, despite a slight framerate drop in the video while face-api is enabled. When I press the backward (or forward) button, though, the face detection stops: the canvas stops being updated. Curiously, this does not happen with the play and pause buttons.

    How should I change my code in order to prevent this behaviour and keep the face-api canvas updated?

    Thanks in advance.

    opened by MatteoBuffo 12
  • Improve accuracy and stabilization?

    Improve accuracy and stabilization?

    is there any easy way to improve to the accuracy and stabilize landmarks? trying with TINY_FACE_DETECTOR on mobile, sometimes landmarks go out of the face.

    opened by veetechh 11
  • Error at faceapi.drawDetection(canvas, boxesWithText).

    Error at faceapi.drawDetection(canvas, boxesWithText).

    I am trying to implement the use case list on below site

    https://itnext.io/realtime-javascript-face-tracking-and-face-recognition-using-face-api-js-mtcnn-face-detector-d924dd8b5740

    i am able to do face detection but getting issue in face recognition with some investigation it looks like boxesWithText is giving empty output which is causing drawDetection to fail.

    Error

    Uncaught (in promise) TypeError: Cannot read property ‘x’ of undefined at VM1409 face-api.min.js:1 at Array.forEach () at Object.t.drawDetection (VM1409 face-api.min.js:1) at run2 (VM1410 index.js:75)

    JS code

     $(document).ready(function() {
         
      run1()
    })
    
    async function run1() {
    
        const MODELS = "http://localhost:8000/Desktop/FaceID/Face%20Detection%20with%20webcam/models"; // Contains all the weights.
    
        await faceapi.loadSsdMobilenetv1Model(MODELS)
        await faceapi.loadFaceLandmarkModel(MODELS)
        await faceapi.loadFaceRecognitionModel(MODELS)
        
    
    // try to access users webcam and stream the images
      // to the video element
     const videoEl = document.getElementById('inputVideo')
      navigator.getUserMedia(
        { video: {} },
        stream => videoEl.srcObject = stream,
        err => console.error(err)
    )
    }
    
    async function run2() {
        
    const mtcnnResults = await faceapi.ssdMobilenetv1(document.getElementById('inputVideo'))
    
    overlay.width = 500
    overlay.height = 400
    const detectionsForSize = mtcnnResults.map(det => det.forSize(500, 400))
    
    faceapi.drawDetection(overlay, detectionsForSize, { withScore: true })    
    
    
    const input = document.getElementById('inputVideo')
    const fullFaceDescriptions = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()
        
        
    const labels = ['sheldon','ravish']
    
    const labeledFaceDescriptors = await Promise.all(
      labels.map(async label => {
        // fetch image data from urls and convert blob to HTMLImage element
        const imgUrl = `http://localhost:8000/Desktop/${label}.png`
        const img = await faceapi.fetchImage(imgUrl)
        
        // detect the face with the highest score in the image and compute it's landmarks and face descriptor
        const fullFaceDescription = await faceapi.detectSingleFace(img).withFaceLandmarks().withFaceDescriptor()
        
        if (!fullFaceDescription) {
          throw new Error(`no faces detected for ${label}`)
        }
        
        const faceDescriptors = [fullFaceDescription.descriptor]
       // console.log(label)
        return new faceapi.LabeledFaceDescriptors(label, faceDescriptors)
      })
    )
    
    // 0.6 is a good distance threshold value to judge
    // whether the descriptors match or not
    const maxDescriptorDistance = 0.6
    const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors, maxDescriptorDistance)
     //console.log("face matcher"+faceMatcher)
    const results = fullFaceDescriptions.map(fd => faceMatcher.findBestMatch(fd.descriptor))
    
    
    const boxesWithText = results.map((bestMatch, i) => {
      const box = fullFaceDescriptions[i].detection.box
      const text = bestMatch.toString()
      const boxWithText = new faceapi.BoxWithText(box, text)
    })
    
    faceapi.drawDetection(overlay, boxesWithText)
    
    
    }
    
    async function onPlay(videoEl) {
        run2()
        setTimeout(() => onPlay(videoEl))
    } 
    
    opened by techravish 11
  • External image sources

    External image sources

    Hi, First of all thank you for your work, it's excellent and very simple to use.

    I have a small problem, when I use the face recognition, the api doesn't seem to work with external image sources. I would like to work with a data base and I'm receiving this error message :

    "Failed to execute 'texImage2D' on 'WebGL2RenderingContext': Tainted canvases may not be loaded."

    Do you know how can I overcome this problem ?

    opened by ingalou 11
  • tiny face detector's been detecting emojis as happy face

    tiny face detector's been detecting emojis as happy face

    I'm able to detect this image as a happy person

    https://dg.imgix.net/do-you-think-you-re-happy-jgdbfiey-en/landscape/do-you-think-you-re-happy-jgdbfiey-9bb0198eeccd0a3c3c13aed064e2e2b3.jpg

    opened by dev-stupid-codes 0
  • Chrome extension manifest v3 error

    Chrome extension manifest v3 error

    Uncaught (in promise) Error: getEnv - environment is not defined, check isNodejs() and isBrowser()

    my code in extension background

    importScripts(
      'face-api.js'
    )
    

    It can be used normally in v2, but the v3 version cannot be used.

    opened by dev-coco 0
  • Is it possible to fine tune the face detection?

    Is it possible to fine tune the face detection?

    Hi guys and Merry Christmas,

    Q1: I am using the face-api.js with SsdMobilenetv1 model to detect faces in photos from aqua park slides. Although it works well for majority of the photos, it struggles with people not facing directly into the camera or with people wearing swimming googles or sun glasses. Is there a way to fine tune the model, to train a custom model based on SsdMobilenetv1 and use it with face-api?

    My ultimate goal is to be able to detect photos that have same people.

    Once the faces are detected, I use euclideanDistance to determine the similarity of the faces which also does not provide me with very reliable results. I've played a lot with the threshold and found that a distance value of less than 0.35 gives me best results, however it still has a lot of false guesses. If I lower the threshold distance, I stop seeing some of the true guesses.

    Q2: My assumption is that if I can extract more detailed face descriptors, the euclideanDistance will be more reliable. According to the docs, the face descriptors consists of 68 Point Face Landmarks. Is there a way to double it?

    Q3: Is there any difference between using directly the euclideanDistance vs FaceMatcher? Does the FaceMatcher do anything more advanced behind the curtains? I don't have labeled faces, I just need to group the photos with same people.

    opened by valchev 0
  • Bump qs and body-parser

    Bump qs and body-parser

    Bumps qs and body-parser. These dependencies needed to be updated together. Updates qs from 6.7.0 to 6.11.0

    Changelog

    Sourced from qs's changelog.

    6.11.0

    • [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option (#442)
    • [readme] fix version badge

    6.10.5

    • [Fix] stringify: with arrayFormat: comma, properly include an explicit [] on a single-item array (#434)

    6.10.4

    • [Fix] stringify: with arrayFormat: comma, include an explicit [] on a single-item array (#441)
    • [meta] use npmignore to autogenerate an npmignore file
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, object-inspect, tape

    6.10.3

    • [Fix] parse: ignore __proto__ keys (#428)
    • [Robustness] stringify: avoid relying on a global undefined (#427)
    • [actions] reuse common workflows
    • [Dev Deps] update eslint, @ljharb/eslint-config, object-inspect, tape

    6.10.2

    • [Fix] stringify: actually fix cyclic references (#426)
    • [Fix] stringify: avoid encoding arrayformat comma when encodeValuesOnly = true (#424)
    • [readme] remove travis badge; add github actions/codecov badges; update URLs
    • [Docs] add note and links for coercing primitive values (#408)
    • [actions] update codecov uploader
    • [actions] update workflows
    • [Tests] clean up stringify tests slightly
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, object-inspect, safe-publish-latest, tape

    6.10.1

    • [Fix] stringify: avoid exception on repeated object values (#402)

    6.10.0

    • [New] stringify: throw on cycles, instead of an infinite loop (#395, #394, #393)
    • [New] parse: add allowSparse option for collapsing arrays with missing indices (#312)
    • [meta] fix README.md (#399)
    • [meta] only run npm run dist in publish, not install
    • [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbols, tape
    • [Tests] fix tests on node v0.6
    • [Tests] use ljharb/actions/node/install instead of ljharb/actions/node/run
    • [Tests] Revert "[meta] ignore eclint transitive audit warning"

    6.9.7

    • [Fix] parse: ignore __proto__ keys (#428)
    • [Fix] stringify: avoid encoding arrayformat comma when encodeValuesOnly = true (#424)
    • [Robustness] stringify: avoid relying on a global undefined (#427)
    • [readme] remove travis badge; add github actions/codecov badges; update URLs
    • [Docs] add note and links for coercing primitive values (#408)
    • [Tests] clean up stringify tests slightly
    • [meta] fix README.md (#399)
    • Revert "[meta] ignore eclint transitive audit warning"

    ... (truncated)

    Commits
    • 56763c1 v6.11.0
    • ddd3e29 [readme] fix version badge
    • c313472 [New] [Fix] stringify: revert 0e903c0; add commaRoundTrip option
    • 95bc018 v6.10.5
    • 0e903c0 [Fix] stringify: with arrayFormat: comma, properly include an explicit `[...
    • ba9703c v6.10.4
    • 4e44019 [Fix] stringify: with arrayFormat: comma, include an explicit [] on a s...
    • 113b990 [Dev Deps] update object-inspect
    • c77f38f [Dev Deps] update eslint, @ljharb/eslint-config, aud, has-symbol, tape
    • 2cf45b2 [meta] use npmignore to autogenerate an npmignore file
    • Additional commits viewable in compare view

    Updates body-parser from 1.19.0 to 1.20.1

    Release notes

    Sourced from body-parser's releases.

    1.20.0

    1.19.2

    1.19.1

    Changelog

    Sourced from body-parser's changelog.

    1.20.1 / 2022-10-06

    1.20.0 / 2022-04-02

    1.19.2 / 2022-02-15

    1.19.1 / 2021-12-10

    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • Detect gender with face data only without image

    Detect gender with face data only without image

    Hi i have the following json data of a face below sent which is every frame generated from this library here https://github.com/rodgomesc/vision-camera-face-detector

    [
       {
          "pitchAngle":19.301362991333008,
          "yawAngle":-36.638710021972656,
          "bounds":{
             "boundingCenterY":980,
             "width":352,
             "x":89,
             "y":1045.75,
             "boundingExactCenterY":980.5,
             "boundingCenterX":178,
             "boundingExactCenterX":178,
             "height":425
          },
          "rollAngle":-32.498043060302734,
          "smilingProbability":0.008996601216495037,
          "leftEyeOpenProbability":0.9938164353370667,
          "contours":{
             "LEFT_CHEEK":[
                {
                   "x":40,
                   "y":956
                }
             ],
             "RIGHT_EYE":[
                {
                   "x":200,
                   "y":939
                },
                {
                   "x":203,
                   "y":938
                },
                {
                   "x":211,
                   "y":936
                },
                {
                   "x":220,
                   "y":936
                },
                {
                   "x":230,
                   "y":938
                },
                {
                   "x":240,
                   "y":944
                },
                {
                   "x":247,
                   "y":950
                },
                {
                   "x":251,
                   "y":956
                },
                {
                   "x":255,
                   "y":961
                },
                {
                   "x":249,
                   "y":961
                },
                {
                   "x":243,
                   "y":960
                },
                {
                   "x":234,
                   "y":958
                },
                {
                   "x":223,
                   "y":954
                },
                {
                   "x":214,
                   "y":950
                },
                {
                   "x":207,
                   "y":945
                },
                {
                   "x":202,
                   "y":942
                }
             ],
             "RIGHT_EYEBROW_TOP":[
                {
                   "x":302,
                   "y":946
                },
                {
                   "x":292,
                   "y":923
                },
                {
                   "x":272,
                   "y":904
                },
                {
                   "x":244,
                   "y":891
                },
                {
                   "x":213,
                   "y":883
                }
             ],
             "LOWER_LIP_BOTTOM":[
                {
                   "x":113,
                   "y":1047
                },
                {
                   "x":101,
                   "y":1043
                },
                {
                   "x":84,
                   "y":1040
                },
                {
                   "x":65,
                   "y":1035
                },
                {
                   "x":46,
                   "y":1028
                },
                {
                   "x":34,
                   "y":1023
                },
                {
                   "x":26,
                   "y":1017
                },
                {
                   "x":22,
                   "y":1012
                },
                {
                   "x":21,
                   "y":1009
                }
             ],
             "UPPER_LIP_TOP":[
                {
                   "x":22,
                   "y":1006
                },
                {
                   "x":26,
                   "y":999
                },
                {
                   "x":34,
                   "y":991
                },
                {
                   "x":45,
                   "y":983
                },
                {
                   "x":60,
                   "y":979
                },
                {
                   "x":73,
                   "y":984
                },
                {
                   "x":89,
                   "y":990
                },
                {
                   "x":105,
                   "y":1007
                },
                {
                   "x":113,
                   "y":1022
                },
                {
                   "x":119,
                   "y":1037
                },
                {
                   "x":120,
                   "y":1047
                }
             ],
             "UPPER_LIP_BOTTOM":[
                {
                   "x":31,
                   "y":1008
                },
                {
                   "x":43,
                   "y":1002
                },
                {
                   "x":49,
                   "y":1000
                },
                {
                   "x":57,
                   "y":1001
                },
                {
                   "x":66,
                   "y":1003
                },
                {
                   "x":78,
                   "y":1009
                },
                {
                   "x":90,
                   "y":1018
                },
                {
                   "x":101,
                   "y":1027
                },
                {
                   "x":115,
                   "y":1044
                }
             ],
             "LEFT_EYEBROW_BOTTOM":[
                {
                   "x":91,
                   "y":887
                },
                {
                   "x":104,
                   "y":878
                },
                {
                   "x":118,
                   "y":875
                },
                {
                   "x":133,
                   "y":875
                },
                {
                   "x":151,
                   "y":886
                }
             ],
             "LEFT_EYEBROW_TOP":[
                {
                   "x":91,
                   "y":885
                },
                {
                   "x":105,
                   "y":874
                },
                {
                   "x":121,
                   "y":868
                },
                {
                   "x":137,
                   "y":867
                },
                {
                   "x":158,
                   "y":872
                }
             ],
             "RIGHT_CHEEK":[
                {
                   "x":186,
                   "y":1009
                }
             ],
             "NOSE_BRIDGE":[
                {
                   "x":163,
                   "y":904
                },
                {
                   "x":98,
                   "y":934
                }
             ],
             "LOWER_LIP_TOP":[
                {
                   "x":106,
                   "y":1039
                },
                {
                   "x":99,
                   "y":1034
                },
                {
                   "x":87,
                   "y":1026
                },
                {
                   "x":73,
                   "y":1019
                },
                {
                   "x":59,
                   "y":1014
                },
                {
                   "x":49,
                   "y":1010
                },
                {
                   "x":42,
                   "y":1008
                },
                {
                   "x":37,
                   "y":1008
                },
                {
                   "x":34,
                   "y":1009
                }
             ],
             "RIGHT_EYEBROW_BOTTOM":[
                {
                   "x":289,
                   "y":942
                },
                {
                   "x":278,
                   "y":924
                },
                {
                   "x":261,
                   "y":909
                },
                {
                   "x":236,
                   "y":899
                },
                {
                   "x":200,
                   "y":896
                }
             ],
             "NOSE_BOTTOM":[
                {
                   "x":71,
                   "y":960
                },
                {
                   "x":95,
                   "y":962
                },
                {
                   "x":135,
                   "y":985
                }
             ],
             "FACE":[
                {
                   "x":220,
                   "y":846
                },
                {
                   "x":242,
                   "y":854
                },
                {
                   "x":285,
                   "y":875
                },
                {
                   "x":314,
                   "y":901
                },
                {
                   "x":331,
                   "y":931
                },
                {
                   "x":344,
                   "y":970
                },
                {
                   "x":343,
                   "y":1002
                },
                {
                   "x":332,
                   "y":1033
                },
                {
                   "x":316,
                   "y":1060
                },
                {
                   "x":297,
                   "y":1084
                },
                {
                   "x":271,
                   "y":1106
                },
                {
                   "x":238,
                   "y":1125
                },
                {
                   "x":199,
                   "y":1134
                },
                {
                   "x":163,
                   "y":1131
                },
                {
                   "x":129,
                   "y":1129
                },
                {
                   "x":99,
                   "y":1122
                },
                {
                   "x":68,
                   "y":1113
                },
                {
                   "x":35,
                   "y":1102
                },
                {
                   "x":13,
                   "y":1093
                },
                {
                   "x":-1,
                   "y":1085
                },
                {
                   "x":-14,
                   "y":1074
                },
                {
                   "x":-20,
                   "y":1066
                },
                {
                   "x":-23,
                   "y":1058
                },
                {
                   "x":-23,
                   "y":1048
                },
                {
                   "x":-21,
                   "y":1035
                },
                {
                   "x":-15,
                   "y":1013
                },
                {
                   "x":-2,
                   "y":985
                },
                {
                   "x":13,
                   "y":961
                },
                {
                   "x":32,
                   "y":940
                },
                {
                   "x":55,
                   "y":922
                },
                {
                   "x":76,
                   "y":898
                },
                {
                   "x":94,
                   "y":882
                },
                {
                   "x":116,
                   "y":866
                },
                {
                   "x":140,
                   "y":852
                },
                {
                   "x":166,
                   "y":844
                },
                {
                   "x":200,
                   "y":843
                }
             ],
             "LEFT_EYE":[
                {
                   "x":85,
                   "y":911
                },
                {
                   "x":89,
                   "y":909
                },
                {
                   "x":93,
                   "y":907
                },
                {
                   "x":99,
                   "y":905
                },
                {
                   "x":108,
                   "y":905
                },
                {
                   "x":116,
                   "y":908
                },
                {
                   "x":123,
                   "y":912
                },
                {
                   "x":127,
                   "y":917
                },
                {
                   "x":129,
                   "y":920
                },
                {
                   "x":124,
                   "y":920
                },
                {
                   "x":117,
                   "y":920
                },
                {
                   "x":107,
                   "y":919
                },
                {
                   "x":99,
                   "y":917
                },
                {
                   "x":92,
                   "y":915
                },
                {
                   "x":88,
                   "y":914
                },
                {
                   "x":86,
                   "y":913
                }
             ]
          },
          "rightEyeOpenProbability":0.9962117075920105
       }
    ]
    

    Is is possible to only use this data without the image?

    opened by GZLiew 1
Releases(0.22.2)
  • 0.22.2(Mar 22, 2020)

  • 0.22.1(Feb 7, 2020)

  • 0.22.0(Dec 15, 2019)

    • bumped tfjs-core to version 1.4.0
    • merged tfjs-image-recognition-base into face-api.js

    deprecations:

    • added deprecation warnigs for
      • allFaces*
      • mtcnn

    breaking changes:

    • moved utils to faceapi.utils
    Source code(tar.gz)
    Source code(zip)
  • 0.21.0(Sep 15, 2019)

    • bumped tfjs-core to version 1.2.9
    • added missing exports for WithAge/WithGender #339
    • JSON de/serialization for FaceMatcher and LabeledFaceDescriptors #397
    Source code(tar.gz)
    Source code(zip)
  • 0.20.1(Jun 28, 2019)

  • 0.20.0(May 7, 2019)

    features:

    • age and gender recognition (AgeGenderNet)
    • improved and more flexible drawing api accessible via faceapi.draw (see examples)
    • allow alignment via withFaceLandmarks before face classification (expression, age and gender prediction) for better accuracy
    • faceapi.matchDimensions helper function to resize media elements

    breaking API changes:

    1. FaceExpressionNet.predictExpressions returns FaceExpressions instance instead of array now

    2. withFaceLandmarks() has to come first after detectAllFaces, detectSingleFace now, since its possible now to use face alignment for face classifcation to achieve more stable prediction results for face classification (expression, age and gender prediction):

    await faceapi.detectAllFaces(input).withFaceExpressions().withFaceLandmarks()
    -> await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()
    
    await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptors()
    -> await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptors()
    
    await faceapi.detectSingleFace(input).withFaceExpressions().withFaceLandmarks()
    -> await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()
    
    await faceapi.detectSingleFace(input).withFaceExpressions().withFaceLandmarks().withFaceDescriptor()
    -> await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptor()
    
    1. removed internals and old drawing api that have been exported:
    • BoxWithText
    • getDefaultDrawOptions
    • drawBox (use faceapi.draw.DrawBox(box).draw(canvas) instead)
    • drawDetection (use faceapi.draw.drawDetections instead)
    • drawFaceLandmarks (use faceapi.draw.drawFaceLandmarks instead)
    • drawFaceExpressions (use faceapi.draw.drawFaceExpressions instead)
    • drawText (use faceapi.draw.DrawTextField(text).draw(canvas) instead)
    Source code(tar.gz)
    Source code(zip)
  • 0.19.0(Mar 27, 2019)

  • 0.18.0(Jan 28, 2019)

  • 0.17.1(Jan 4, 2019)

  • 0.17.0(Jan 2, 2019)

    Features:

    • face expression recognition

    Breaking Changes:

    The following two utility classes have been replaced: FaceDetectionWithLandmarks, FullFaceDescription. Now, plain objects are returned from the corresponding function calls instead of instances of abovementioned classes, which have to be resized by faceapi.resizeResults(results, { width: <width>, height: <height> }) instead of results.map(res => res.forSize(width, height)):

    export function resizeResults<T>(results: T, { width, height }: IDimensions): T
    
    Source code(tar.gz)
    Source code(zip)
  • 0.16.2(Dec 13, 2018)

    fixes:

    • fixed issue of incorrectly initializing nodejs environment in electron renderer thread #157

    other:

    • bumped tfjs-core version to 0.14.2
    Source code(tar.gz)
    Source code(zip)
  • 0.16.1(Nov 18, 2018)

  • 0.16.0(Nov 12, 2018)

  • 0.15.1(Oct 30, 2018)

  • 0.15.0(Oct 23, 2018)

    • new tiny face detection model for realtime face detection
    • simplified and easier to use API + more utility (Composable Tasks API, FaceMatcher)
    Source code(tar.gz)
    Source code(zip)
  • 0.14.3(Oct 3, 2018)

    fixes:

    • resolved broken dependency tree in package-lock.json, which caused tfjs-core to be bundled 3 times leading to ~3x bundle size + published fixed dist
    Source code(tar.gz)
    Source code(zip)
  • 0.14.2(Oct 2, 2018)

  • 0.14.1(Sep 30, 2018)

  • 0.14.0(Sep 26, 2018)

    • trained two 68 point face landmark detection models from scratch, which have higher accuracy and are much faster then previous model
    • furthermore the model sizes are much smaller (350kb and 80kb tiny model) compared to the old model (7MB)
    Source code(tar.gz)
    Source code(zip)
  • 0.13.0(Sep 16, 2018)

    • major performance improvements by resizing net input canvases instead of tensors, which is much more performant and circumvents issue mentioned here

    fixes:

    • fixed post processing of 68 point face landmarks, which caused distortion of points at axes of minor dimension

    breaking changes:

    • removed managed flag and method from NetInput and related flag in toNetInput
    • NetInput inputs are now left untouched, thus NetInput.inputs has been removed, NetInput.getInput(batchIdx) should be used instead
    • NetInput and toNetInput do not accept tf.Tensor4D input with batchSize > 1 anymore, unstack batches instead and pass individual tensors as an array to create an equivalent batch input
    Source code(tar.gz)
    Source code(zip)
  • 0.12.1(Sep 13, 2018)

  • 0.12.0(Aug 27, 2018)

  • 0.11.0(Aug 17, 2018)

    features:

    • implements tiny yolo v2 using separable convolutions for face detection in realtime and on mobile devices
    • allFacesTinyYolov2 shortcut function
    Source code(tar.gz)
    Source code(zip)
  • 0.10.1(Aug 13, 2018)

    fixes:

    • fixed exception in extractFaceTensors and extractFaces when rectangle overlaps image borders
    • allow loading of model files from external uris #69
    Source code(tar.gz)
    Source code(zip)
  • 0.10.0(Jul 31, 2018)

  • 0.9.2(Jul 26, 2018)

  • 0.9.1(Jul 24, 2018)

  • 0.9.0(Jul 16, 2018)

  • 0.8.0(Jul 14, 2018)

  • 0.7.0(Jul 6, 2018)

    features:

    • parameters of the neural nets can now be retrieved, manipulated and disposed
    • neural nets are now trainable, e.g. make params variable: net.variable(), freeze weights: net.freeze()

    fixes:

    • fixed minor memory leaks arising from loading the parameters
    Source code(tar.gz)
    Source code(zip)
Owner
Vincent Mühler
Just hacking stuff.
Vincent Mühler
A speech recognition library running in the browser thanks to a WebAssembly build of Vosk

A speech recognition library running in the browser thanks to a WebAssembly build of Vosk

Ciaran O'Reilly 207 Jan 3, 2023
A library for prototyping realtime hand detection (bounding box), directly in the browser.

Handtrack.js View a live demo in your browser here. Handtrack.js is a library for prototyping realtime hand detection (bounding box), directly in the

Victor Dibia 2.7k Jan 3, 2023
This Smart Brain will detect face in your Images, Give it a try ;-)

Smart-Brain ?? Click here to view this site in your browser. ?? Things you can do in this site are - 1. Create an account ?? 2. Signin using your exis

Archit Tripathi 4 Apr 14, 2022
Support Vector Machine (SVM) library for nodejs

node-svm Support Vector Machine (SVM) library for nodejs. Support Vector Machines Wikipedia : Support vector machines are supervised learning models t

Nicolas Panel 296 Nov 6, 2022
Simple Javascript implementation of the k-means algorithm, for node.js and the browser

#kMeans.js Simple Javascript implementation of the k-means algorithm, for node.js and the browser ##Installation npm install kmeans-js ##Example (JS)

Emil Bay 44 Aug 19, 2022
Clustering algorithms implemented in Javascript for Node.js and the browser

Clustering.js ####Clustering algorithms implemented in Javascript for Node.js and the browser Examples License Copyright (c) 2013 Emil Bay github@tixz

Emil Bay 29 Aug 19, 2022
Deep Learning in Javascript. Train Convolutional Neural Networks (or ordinary ones) in your browser.

ConvNetJS ConvNetJS is a Javascript implementation of Neural networks, together with nice browser-based demos. It currently supports: Common Neural Ne

Andrej 10.4k Dec 31, 2022
architecture-free neural network library for node.js and the browser

Synaptic Important: Synaptic 2.x is in stage of discussion now! Feel free to participate Synaptic is a javascript neural network library for node.js a

Juan Cazala 6.9k Dec 27, 2022
Train and test machine learning models for your Arduino Nano 33 BLE Sense in the browser.

Tiny Motion Trainer Train and test IMU based TFLite models on the Web Overview Since 2009, coders have created thousands of experiments using Chrome,

Google Creative Lab 59 Nov 21, 2022
Bayesian bandit implementation for Node and the browser.

#bayesian-bandit.js This is an adaptation of the Bayesian Bandit code from Probabilistic Programming and Bayesian Methods for Hackers, specifically d3

null 44 Aug 19, 2022
Run Keras models in the browser, with GPU support using WebGL

**This project is no longer active. Please check out TensorFlow.js.** The Keras.js demos still work but is no longer updated. Run Keras models in the

Leon Chen 4.9k Dec 29, 2022
The Fastest DNN Running Framework on Web Browser

WebDNN: Fastest DNN Execution Framework on Web Browser WebDNN is an open source software framework for executing deep neural network (DNN) pre-trained

Machine Intelligence Laboratory (The University of Tokyo) 1.9k Jan 1, 2023
This is a JS/TS library for accelerated tensor computation intended to be run in the browser.

TensorJS TensorJS How to use Tensors Tensor operations Reading values Data types Converting between backends Onnx model support Optimizations Running

Frithjof Winkelmann 32 Jun 26, 2022
A JavaScript deep learning and reinforcement learning library.

neurojs is a JavaScript framework for deep learning in the browser. It mainly focuses on reinforcement learning, but can be used for any neural networ

Jan 4.4k Jan 4, 2023
A WebGL accelerated JavaScript library for training and deploying ML models.

TensorFlow.js TensorFlow.js is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models. ⚠️ We recent

null 16.9k Jan 4, 2023
[UNMAINTAINED] Simple feed-forward neural network in JavaScript

This project has reached the end of its development as a simple neural network library. Feel free to browse the code, but please use other JavaScript

Heather 8k Dec 26, 2022
A neural network library built in JavaScript

A flexible neural network library for Node.js and the browser. Check out a live demo of a movie recommendation engine built with Mind. Features Vector

Steven Miller 1.5k Dec 31, 2022
Pure Javascript OCR for more than 100 Languages 📖🎉🖥

Version 2 is now available and under development in the master branch, read a story about v2: Why I refactor tesseract.js v2? Check the support/1.x br

Project Naptha 29.2k Dec 31, 2022
WebGL-accelerated ML // linear algebra // automatic differentiation for JavaScript.

This repository has been archived in favor of tensorflow/tfjs. This repo will remain around for some time to keep history but all future PRs should be

null 8.5k Dec 31, 2022