[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-3791":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":20,"compositeScore":21,"rankGlobal":10,"rankLanguage":10,"license":22,"archived":23,"fork":23,"defaultBranch":24,"hasWiki":25,"hasPages":25,"topics":26,"createdAt":10,"pushedAt":10,"updatedAt":39,"readmeContent":40,"aiSummary":41,"trendingCount":16,"starSnapshotCount":16,"syncStatus":42,"lastSyncTime":43,"discoverSource":44},3791,"face-api.js","justadudewhohacks\u002Fface-api.js","justadudewhohacks","JavaScript API for face detection and face recognition in the browser and nodejs with tensorflow.js","",null,"TypeScript",17869,3896,348,452,0,3,6,31,9,45,"MIT License",false,"master",true,[27,28,29,30,31,32,33,34,35,36,37,38],"age-estimation","emotion-recognition","face-detection","face-landmarks","face-recognition","gender-recognition","javascript","js","nodejs","tensorflow","tensorflowjs","tfjs","2026-06-12 02:00:54","# face-api.js\n\n[![Build Status](https:\u002F\u002Ftravis-ci.org\u002Fjustadudewhohacks\u002Fface-api.js.svg?branch=master)](https:\u002F\u002Ftravis-ci.org\u002Fjustadudewhohacks\u002Fface-api.js)\n[![Slack](https:\u002F\u002Fslack.bri.im\u002Fbadge.svg)](https:\u002F\u002Fslack.bri.im)\n\n**JavaScript face recognition API for the browser and nodejs implemented on top of tensorflow.js core ([tensorflow\u002Ftfjs-core](https:\u002F\u002Fgithub.com\u002Ftensorflow\u002Ftfjs))**\n\n![faceapi](https:\u002F\u002Fuser-images.githubusercontent.com\u002F31125521\u002F57224752-ad3dc080-700a-11e9-85b9-1357b9f9bca4.gif)\n\n## **[Click me for Live Demos!](https:\u002F\u002Fjustadudewhohacks.github.io\u002Fface-api.js\u002F)**\n\n## Tutorials\n\n* **[face-api.js — JavaScript API for Face Recognition in the Browser with tensorflow.js](https:\u002F\u002Fitnext.io\u002Fface-api-js-javascript-api-for-face-recognition-in-the-browser-with-tensorflow-js-bcc2a6c4cf07)**\n* **[Realtime JavaScript Face Tracking and Face Recognition using face-api.js’ MTCNN Face Detector](https:\u002F\u002Fitnext.io\u002Frealtime-javascript-face-tracking-and-face-recognition-using-face-api-js-mtcnn-face-detector-d924dd8b5740)**\n* **[Realtime Webcam Face Detection And Emotion Recognition - Video](https:\u002F\u002Fyoutu.be\u002FCVClHLwv-4I)**\n* **[Easy Face Recognition Tutorial With JavaScript - Video](https:\u002F\u002Fyoutu.be\u002FAZ4PdALMqx0)**\n* **[Using face-api.js with Vue.js and Electron](https:\u002F\u002Fmedium.com\u002F@andreas.schallwig\u002Fdo-not-laugh-a-simple-ai-powered-game-3e22ad0f8166)**\n* **[Add Masks to People - Gant Laborde on Learn with Jason](https:\u002F\u002Fwww.learnwithjason.dev\u002Ffun-with-machine-learning-pt-2)**\n\n## Table of Contents\n\n* **[Features](#features)**\n* **[Running the Examples](#running-the-examples)**\n* **[face-api.js for the Browser](#face-api.js-for-the-browser)**\n* **[face-api.js for Nodejs](#face-api.js-for-nodejs)**\n* **[Usage](#getting-started)**\n  * **[Loading the Models](#getting-started-loading-models)**\n  * **[High Level API](#high-level-api)**\n  * **[Displaying Detection Results](#getting-started-displaying-detection-results)**\n  * **[Face Detection Options](#getting-started-face-detection-options)**\n  * **[Utility Classes](#getting-started-utility-classes)**\n  * **[Other Useful Utility](#other-useful-utility)**\n* **[Available Models](#models)**\n  * **[Face Detection](#models-face-detection)**\n  * **[Face Landmark Detection](#models-face-landmark-detection)**\n  * **[Face Recognition](#models-face-recognition)**\n  * **[Face Expression Recognition](#models-face-expression-recognition)**\n  * **[Age Estimation and Gender Recognition](#models-age-and-gender-recognition)**\n* **[API Documentation](https:\u002F\u002Fjustadudewhohacks.github.io\u002Fface-api.js\u002Fdocs\u002Fglobals.html)**\n\n# Features\n\n## Face Recognition\n\n![face-recognition](https:\u002F\u002Fuser-images.githubusercontent.com\u002F31125521\u002F57297377-bfcdfd80-70cf-11e9-8afa-2044cb167bff.gif)\n\n## Face Landmark Detection\n\n![face_landmark_detection](https:\u002F\u002Fuser-images.githubusercontent.com\u002F31125521\u002F57297731-b1ccac80-70d0-11e9-9bd7-59d77f180322.jpg)\n\n## Face Expression Recognition\n\n![preview_face-expression-recognition](https:\u002F\u002Fuser-images.githubusercontent.com\u002F31125521\u002F50575270-f501d080-0dfb-11e9-9676-8f419efdade4.png)\n\n## Age Estimation & Gender Recognition\n\n![age_gender_recognition](https:\u002F\u002Fuser-images.githubusercontent.com\u002F31125521\u002F57297736-b5603380-70d0-11e9-873d-8b6c7243eb64.jpg)\n\n\u003Ca name=\"running-the-examples\">\u003C\u002Fa>\n\n# Running the Examples\n\nClone the repository:\n\n``` bash\ngit clone https:\u002F\u002Fgithub.com\u002Fjustadudewhohacks\u002Fface-api.js.git\n```\n\n## Running the Browser Examples\n\n``` bash\ncd face-api.js\u002Fexamples\u002Fexamples-browser\nnpm i\nnpm start\n```\n\nBrowse to http:\u002F\u002Flocalhost:3000\u002F.\n\n## Running the Nodejs Examples\n\n``` bash\ncd face-api.js\u002Fexamples\u002Fexamples-nodejs\nnpm i\n```\n\nNow run one of the examples using ts-node:\n\n``` bash\nts-node faceDetection.ts\n```\n\nOr simply compile and run them with node:\n\n``` bash\ntsc faceDetection.ts\nnode faceDetection.js\n```\n\n\u003Ca name=\"face-api.js-for-the-browser\">\u003C\u002Fa>\n\n# face-api.js for the Browser\n\nSimply include the latest script from [dist\u002Fface-api.js](https:\u002F\u002Fgithub.com\u002Fjustadudewhohacks\u002Fface-api.js\u002Ftree\u002Fmaster\u002Fdist).\n\nOr install it via npm:\n\n``` bash\nnpm i face-api.js\n```\n\n\u003Ca name=\"face-api.js-for-nodejs\">\u003C\u002Fa>\n\n# face-api.js for Nodejs\n\nWe 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.\n\nAlternatively you can simply construct your own tensors from image data and pass tensors as inputs to the API.\n\nFurthermore you want to install @tensorflow\u002Ftfjs-node (not required, but highly recommended), which speeds things up drastically by compiling and binding to the native Tensorflow C++ library:\n\n``` bash\nnpm i face-api.js canvas @tensorflow\u002Ftfjs-node\n```\n\nNow we simply monkey patch the environment to use the polyfills:\n\n``` javascript\n\u002F\u002F import nodejs bindings to native tensorflow,\n\u002F\u002F not required, but will speed up things drastically (python required)\nimport '@tensorflow\u002Ftfjs-node';\n\n\u002F\u002F implements nodejs wrappers for HTMLCanvasElement, HTMLImageElement, ImageData\nimport * as canvas from 'canvas';\n\nimport * as faceapi from 'face-api.js';\n\n\u002F\u002F patch nodejs environment, we need to provide an implementation of\n\u002F\u002F HTMLCanvasElement and HTMLImageElement\nconst { Canvas, Image, ImageData } = canvas\nfaceapi.env.monkeyPatch({ Canvas, Image, ImageData })\n```\n\n\u003Ca name=\"getting-started\">\u003C\u002Fa>\n\n# Getting Started\n\n\u003Ca name=\"getting-started-loading-models\">\u003C\u002Fa>\n\n## Loading the Models\n\nAll global neural network instances are exported via faceapi.nets:\n\n``` javascript\nconsole.log(faceapi.nets)\n\u002F\u002F ageGenderNet\n\u002F\u002F faceExpressionNet\n\u002F\u002F faceLandmark68Net\n\u002F\u002F faceLandmark68TinyNet\n\u002F\u002F faceRecognitionNet\n\u002F\u002F ssdMobilenetv1\n\u002F\u002F tinyFaceDetector\n\u002F\u002F tinyYolov2\n```\n\nTo 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 \u002F accessible under the same route.\n\nAssuming the models reside in **public\u002Fmodels**:\n\n``` javascript\nawait faceapi.nets.ssdMobilenetv1.loadFromUri('\u002Fmodels')\n\u002F\u002F accordingly for the other models:\n\u002F\u002F await faceapi.nets.faceLandmark68Net.loadFromUri('\u002Fmodels')\n\u002F\u002F await faceapi.nets.faceRecognitionNet.loadFromUri('\u002Fmodels')\n\u002F\u002F ...\n```\n\nIn a nodejs environment you can furthermore load the models directly from disk:\n\n``` javascript\nawait faceapi.nets.ssdMobilenetv1.loadFromDisk('.\u002Fmodels')\n```\n\nYou can also load the model from a tf.NamedTensorMap:\n\n``` javascript\nawait faceapi.nets.ssdMobilenetv1.loadFromWeightMap(weightMap)\n```\n\nAlternatively, you can also create own instances of the neural nets:\n\n``` javascript\nconst net = new faceapi.SsdMobilenetv1()\nawait net.loadFromUri('\u002Fmodels')\n```\n\nYou can also load the weights as a Float32Array (in case you want to use the uncompressed models):\n\n``` javascript\n\u002F\u002F using fetch\nnet.load(await faceapi.fetchNetWeights('\u002Fmodels\u002Fface_detection_model.weights'))\n\n\u002F\u002F using axios\nconst res = await axios.get('\u002Fmodels\u002Fface_detection_model.weights', { responseType: 'arraybuffer' })\nconst weights = new Float32Array(res.data)\nnet.load(weights)\n```\n\n\u003Ca name=\"getting-high-level-api\">\u003C\u002Fa>\n\n## High Level API\n\nIn the following **input** can be an HTML img, video or canvas element or the id of that element.\n\n``` html\n\u003Cimg id=\"myImg\" src=\"images\u002Fexample.png\" \u002F>\n\u003Cvideo id=\"myVideo\" src=\"media\u002Fexample.mp4\" \u002F>\n\u003Ccanvas id=\"myCanvas\" \u002F>\n```\n\n``` javascript\nconst input = document.getElementById('myImg')\n\u002F\u002F const input = document.getElementById('myVideo')\n\u002F\u002F const input = document.getElementById('myCanvas')\n\u002F\u002F or simply:\n\u002F\u002F const input = 'myImg'\n```\n\n### Detecting Faces\n\nDetect all faces in an image. Returns **Array\u003C[FaceDetection](#interface-face-detection)>**:\n\n``` javascript\nconst detections = await faceapi.detectAllFaces(input)\n```\n\nDetect the face with the highest confidence score in an image. Returns **[FaceDetection](#interface-face-detection) | undefined**:\n\n``` javascript\nconst detection = await faceapi.detectSingleFace(input)\n```\n\nBy default **detectAllFaces** and **detectSingleFace** utilize the SSD Mobilenet V1 Face Detector. You can specify the face detector by passing the corresponding options object:\n\n``` javascript\nconst detections1 = await faceapi.detectAllFaces(input, new faceapi.SsdMobilenetv1Options())\nconst detections2 = await faceapi.detectAllFaces(input, new faceapi.TinyFaceDetectorOptions())\n```\n\nYou can tune the options of each face detector as shown [here](#getting-started-face-detection-options).\n\n### Detecting 68 Face Landmark Points\n\n**After face detection, we can furthermore predict the facial landmarks for each detected face as follows:**\n\nDetect all faces in an image + computes 68 Point Face Landmarks for each detected face. Returns **Array\u003C[WithFaceLandmarks\u003CWithFaceDetection\u003C{}>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks()\n```\n\nDetect the face with the highest confidence score in an image + computes 68 Point Face Landmarks for that face. Returns **[WithFaceLandmarks\u003CWithFaceDetection\u003C{}>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst detectionWithLandmarks = await faceapi.detectSingleFace(input).withFaceLandmarks()\n```\n\nYou can also specify to use the tiny model instead of the default model:\n\n``` javascript\nconst useTinyModel = true\nconst detectionsWithLandmarks = await faceapi.detectAllFaces(input).withFaceLandmarks(useTinyModel)\n```\n\n### Computing Face Descriptors\n\n**After face detection and facial landmark prediction the face descriptors for each face can be computed as follows:**\n\nDetect all faces in an image + compute 68 Point Face Landmarks for each detected face. Returns **Array\u003C[WithFaceDescriptor\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst results = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceDescriptors()\n```\n\nDetect the face with the highest confidence score in an image + compute 68 Point Face Landmarks and face descriptor for that face. Returns **[WithFaceDescriptor\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst result = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceDescriptor()\n```\n\n### Recognizing Face Expressions\n\n**Face expression recognition can be performed for detected faces as follows:**\n\nDetect all faces in an image + recognize face expressions of each face. Returns **Array\u003C[WithFaceExpressions\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()\n```\n\nDetect the face with the highest confidence score in an image + recognize the face expressions for that face. Returns **[WithFaceExpressions\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()\n```\n\n**You can also skip .withFaceLandmarks(), which will skip the face alignment step (less stable accuracy):**\n\nDetect all faces without face alignment + recognize face expressions of each face. Returns **Array\u003C[WithFaceExpressions\u003CWithFaceDetection\u003C{}>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst detectionsWithExpressions = await faceapi.detectAllFaces(input).withFaceExpressions()\n```\n\nDetect the face with the highest confidence score without face alignment + recognize the face expression for that face. Returns **[WithFaceExpressions\u003CWithFaceDetection\u003C{}>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst detectionWithExpressions = await faceapi.detectSingleFace(input).withFaceExpressions()\n```\n\n### Age Estimation and Gender Recognition\n\n**Age estimation and gender recognition from detected faces can be done as follows:**\n\nDetect all faces in an image + estimate age and recognize gender of each face. Returns **Array\u003C[WithAge\u003CWithGender\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender()\n```\n\nDetect the face with the highest confidence score in an image  + estimate age and recognize gender for that face. Returns **[WithAge\u003CWithGender\u003CWithFaceLandmarks\u003CWithFaceDetection\u003C{}>>>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender()\n```\n\n**You can also skip .withFaceLandmarks(), which will skip the face alignment step (less stable accuracy):**\n\nDetect all faces without face alignment + estimate age and recognize gender of each face. Returns **Array\u003C[WithAge\u003CWithGender\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes)>**:\n\n``` javascript\nconst detectionsWithAgeAndGender = await faceapi.detectAllFaces(input).withAgeAndGender()\n```\n\nDetect the face with the highest confidence score without face alignment + estimate age and recognize gender for that face. Returns **[WithAge\u003CWithGender\u003CWithFaceDetection\u003C{}>>>](#getting-started-utility-classes) | undefined**:\n\n``` javascript\nconst detectionWithAgeAndGender = await faceapi.detectSingleFace(input).withAgeAndGender()\n```\n\n### Composition of Tasks\n\n**Tasks can be composed as follows:**\n\n``` javascript\n\u002F\u002F all faces\nawait faceapi.detectAllFaces(input)\nawait faceapi.detectAllFaces(input).withFaceExpressions()\nawait faceapi.detectAllFaces(input).withFaceLandmarks()\nawait faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions()\nawait faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptors()\nawait faceapi.detectAllFaces(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptors()\nawait faceapi.detectAllFaces(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptors()\n\n\u002F\u002F single face\nawait faceapi.detectSingleFace(input)\nawait faceapi.detectSingleFace(input).withFaceExpressions()\nawait faceapi.detectSingleFace(input).withFaceLandmarks()\nawait faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions()\nawait faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withFaceDescriptor()\nawait faceapi.detectSingleFace(input).withFaceLandmarks().withAgeAndGender().withFaceDescriptor()\nawait faceapi.detectSingleFace(input).withFaceLandmarks().withFaceExpressions().withAgeAndGender().withFaceDescriptor()\n```\n\n### Face Recognition by Matching Descriptors\n\nTo perform face recognition, one can use faceapi.FaceMatcher to compare reference face descriptors to query face descriptors.\n\nFirst, 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:\n\n``` javascript\nconst results = await faceapi\n  .detectAllFaces(referenceImage)\n  .withFaceLandmarks()\n  .withFaceDescriptors()\n\nif (!results.length) {\n  return\n}\n\n\u002F\u002F create FaceMatcher with automatically assigned labels\n\u002F\u002F from the detection results for the reference image\nconst faceMatcher = new faceapi.FaceMatcher(results)\n```\n\nNow we can recognize a persons face shown in **queryImage1**:\n\n``` javascript\nconst singleResult = await faceapi\n  .detectSingleFace(queryImage1)\n  .withFaceLandmarks()\n  .withFaceDescriptor()\n\nif (singleResult) {\n  const bestMatch = faceMatcher.findBestMatch(singleResult.descriptor)\n  console.log(bestMatch.toString())\n}\n```\n\nOr we can recognize all faces shown in **queryImage2**:\n\n``` javascript\nconst results = await faceapi\n  .detectAllFaces(queryImage2)\n  .withFaceLandmarks()\n  .withFaceDescriptors()\n\nresults.forEach(fd => {\n  const bestMatch = faceMatcher.findBestMatch(fd.descriptor)\n  console.log(bestMatch.toString())\n})\n```\n\nYou can also create labeled reference descriptors as follows:\n\n``` javascript\nconst labeledDescriptors = [\n  new faceapi.LabeledFaceDescriptors(\n    'obama',\n    [descriptorObama1, descriptorObama2]\n  ),\n  new faceapi.LabeledFaceDescriptors(\n    'trump',\n    [descriptorTrump]\n  )\n]\n\nconst faceMatcher = new faceapi.FaceMatcher(labeledDescriptors)\n```\n\n\u003Ca name=\"getting-started-displaying-detection-results\">\u003C\u002Fa>\n\n## Displaying Detection Results\n\nPreparing the overlay canvas:\n\n``` javascript\nconst displaySize = { width: input.width, height: input.height }\n\u002F\u002F resize the overlay canvas to the input dimensions\nconst canvas = document.getElementById('overlay')\nfaceapi.matchDimensions(canvas, displaySize)\n```\n\nface-api.js predefines some highlevel drawing functions, which you can utilize:\n\n``` javascript\n\u002F* Display detected face bounding boxes *\u002F\nconst detections = await faceapi.detectAllFaces(input)\n\u002F\u002F resize the detected boxes in case your displayed image has a different size than the original\nconst resizedDetections = faceapi.resizeResults(detections, displaySize)\n\u002F\u002F draw detections into the canvas\nfaceapi.draw.drawDetections(canvas, resizedDetections)\n\n\u002F* Display face landmarks *\u002F\nconst detectionsWithLandmarks = await faceapi\n  .detectAllFaces(input)\n  .withFaceLandmarks()\n\u002F\u002F resize the detected boxes and landmarks in case your displayed image has a different size than the original\nconst resizedResults = faceapi.resizeResults(detectionsWithLandmarks, displaySize)\n\u002F\u002F draw detections into the canvas\nfaceapi.draw.drawDetections(canvas, resizedResults)\n\u002F\u002F draw the landmarks into the canvas\nfaceapi.draw.drawFaceLandmarks(canvas, resizedResults)\n\n\n\u002F* Display face expression results *\u002F\nconst detectionsWithExpressions = await faceapi\n  .detectAllFaces(input)\n  .withFaceLandmarks()\n  .withFaceExpressions()\n\u002F\u002F resize the detected boxes and landmarks in case your displayed image has a different size than the original\nconst resizedResults = faceapi.resizeResults(detectionsWithExpressions, displaySize)\n\u002F\u002F draw detections into the canvas\nfaceapi.draw.drawDetections(canvas, resizedResults)\n\u002F\u002F draw a textbox displaying the face expressions with minimum probability into the canvas\nconst minProbability = 0.05\nfaceapi.draw.drawFaceExpressions(canvas, resizedResults, minProbability)\n```\n\nYou can also draw boxes with custom text ([DrawBox](https:\u002F\u002Fgithub.com\u002Fjustadudewhohacks\u002Ftfjs-image-recognition-base\u002Fblob\u002Fmaster\u002Fsrc\u002Fdraw\u002FDrawBox.ts)):\n\n``` javascript\nconst box = { x: 50, y: 50, width: 100, height: 100 }\n\u002F\u002F see DrawBoxOptions below\nconst drawOptions = {\n  label: 'Hello I am a box!',\n  lineWidth: 2\n}\nconst drawBox = new faceapi.draw.DrawBox(box, drawOptions)\ndrawBox.draw(document.getElementById('myCanvas'))\n```\n\nDrawBox drawing options:\n\n``` javascript\nexport interface IDrawBoxOptions {\n  boxColor?: string\n  lineWidth?: number\n  drawLabelOptions?: IDrawTextFieldOptions\n  label?: string\n}\n```\n\nFinally you can draw custom text fields ([DrawTextField](https:\u002F\u002Fgithub.com\u002Fjustadudewhohacks\u002Ftfjs-image-recognition-base\u002Fblob\u002Fmaster\u002Fsrc\u002Fdraw\u002FDrawTextField.ts)):\n\n``` javascript\nconst text = [\n  'This is a textline!',\n  'This is another textline!'\n]\nconst anchor = { x: 200, y: 200 }\n\u002F\u002F see DrawTextField below\nconst drawOptions = {\n  anchorPosition: 'TOP_LEFT',\n  backgroundColor: 'rgba(0, 0, 0, 0.5)'\n}\nconst drawBox = new faceapi.draw.DrawTextField(text, anchor, drawOptions)\ndrawBox.draw(document.getElementById('myCanvas'))\n```\n\nDrawTextField drawing options:\n\n``` javascript\nexport interface IDrawTextFieldOptions {\n  anchorPosition?: AnchorPosition\n  backgroundColor?: string\n  fontColor?: string\n  fontSize?: number\n  fontStyle?: string\n  padding?: number\n}\n\nexport enum AnchorPosition {\n  TOP_LEFT = 'TOP_LEFT',\n  TOP_RIGHT = 'TOP_RIGHT',\n  BOTTOM_LEFT = 'BOTTOM_LEFT',\n  BOTTOM_RIGHT = 'BOTTOM_RIGHT'\n}\n```\n\n\u003Ca name=\"getting-started-face-detection-options\">\u003C\u002Fa>\n\n## Face Detection Options\n\n### SsdMobilenetv1Options\n\n``` javascript\nexport interface ISsdMobilenetv1Options {\n  \u002F\u002F minimum confidence threshold\n  \u002F\u002F default: 0.5\n  minConfidence?: number\n\n  \u002F\u002F maximum number of faces to return\n  \u002F\u002F default: 100\n  maxResults?: number\n}\n\n\u002F\u002F example\nconst options = new faceapi.SsdMobilenetv1Options({ minConfidence: 0.8 })\n```\n\n### TinyFaceDetectorOptions\n\n``` javascript\nexport interface ITinyFaceDetectorOptions {\n  \u002F\u002F size at which image is processed, the smaller the faster,\n  \u002F\u002F but less precise in detecting smaller faces, must be divisible\n  \u002F\u002F by 32, common sizes are 128, 160, 224, 320, 416, 512, 608,\n  \u002F\u002F for face tracking via webcam I would recommend using smaller sizes,\n  \u002F\u002F e.g. 128, 160, for detecting smaller faces use larger sizes, e.g. 512, 608\n  \u002F\u002F default: 416\n  inputSize?: number\n\n  \u002F\u002F minimum confidence threshold\n  \u002F\u002F default: 0.5\n  scoreThreshold?: number\n}\n\n\u002F\u002F example\nconst options = new faceapi.TinyFaceDetectorOptions({ inputSize: 320 })\n```\n\n\u003Ca name=\"getting-started-utility-classes\">\u003C\u002Fa>\n\n## Utility Classes\n\n### IBox\n\n``` javascript\nexport interface IBox {\n  x: number\n  y: number\n  width: number\n  height: number\n}\n```\n\n### IFaceDetection\n\n``` javascript\nexport interface IFaceDetection {\n  score: number\n  box: Box\n}\n```\n\n### IFaceLandmarks\n\n``` javascript\nexport interface IFaceLandmarks {\n  positions: Point[]\n  shift: Point\n}\n```\n\n### WithFaceDetection\n\n``` javascript\nexport type WithFaceDetection\u003CTSource> = TSource & {\n  detection: FaceDetection\n}\n```\n\n### WithFaceLandmarks\n\n``` javascript\nexport type WithFaceLandmarks\u003CTSource> = TSource & {\n  unshiftedLandmarks: FaceLandmarks\n  landmarks: FaceLandmarks\n  alignedRect: FaceDetection\n}\n```\n\n### WithFaceDescriptor\n\n``` javascript\nexport type WithFaceDescriptor\u003CTSource> = TSource & {\n  descriptor: Float32Array\n}\n```\n\n### WithFaceExpressions\n\n``` javascript\nexport type WithFaceExpressions\u003CTSource> = TSource & {\n  expressions: FaceExpressions\n}\n```\n\n### WithAge\n\n``` javascript\nexport type WithAge\u003CTSource> = TSource & {\n  age: number\n}\n```\n\n### WithGender\n\n``` javascript\nexport type WithGender\u003CTSource> = TSource & {\n  gender: Gender\n  genderProbability: number\n}\n\nexport enum Gender {\n  FEMALE = 'female',\n  MALE = 'male'\n}\n```\n\n\u003Ca name=\"getting-started-other-useful-utility\">\u003C\u002Fa>\n\n## Other Useful Utility\n\n### Using the Low Level API\n\nInstead of using the high level API, you can directly use the forward methods of each neural network:\n\n``` javascript\nconst detections1 = await faceapi.ssdMobilenetv1(input, options)\nconst detections2 = await faceapi.tinyFaceDetector(input, options)\nconst landmarks1 = await faceapi.detectFaceLandmarks(faceImage)\nconst landmarks2 = await faceapi.detectFaceLandmarksTiny(faceImage)\nconst descriptor = await faceapi.computeFaceDescriptor(alignedFaceImage)\n```\n\n### Extracting a Canvas for an Image Region\n\n``` javascript\nconst regionsToExtract = [\n  new faceapi.Rect(0, 0, 100, 100)\n]\n\u002F\u002F actually extractFaces is meant to extract face regions from bounding boxes\n\u002F\u002F but you can also use it to extract any other region\nconst canvases = await faceapi.extractFaces(input, regionsToExtract)\n```\n\n### Euclidean Distance\n\n``` javascript\n\u002F\u002F ment to be used for computing the euclidean distance between two face descriptors\nconst dist = faceapi.euclideanDistance([0, 0], [0, 10])\nconsole.log(dist) \u002F\u002F 10\n```\n\n### Retrieve the Face Landmark Points and Contours\n\n``` javascript\nconst landmarkPositions = landmarks.positions\n\n\u002F\u002F or get the positions of individual contours,\n\u002F\u002F only available for 68 point face ladnamrks (FaceLandmarks68)\nconst jawOutline = landmarks.getJawOutline()\nconst nose = landmarks.getNose()\nconst mouth = landmarks.getMouth()\nconst leftEye = landmarks.getLeftEye()\nconst rightEye = landmarks.getRightEye()\nconst leftEyeBbrow = landmarks.getLeftEyeBrow()\nconst rightEyeBrow = landmarks.getRightEyeBrow()\n```\n\n### Fetch and Display Images from an URL\n\n``` html\n\u003Cimg id=\"myImg\" src=\"\">\n```\n\n``` javascript\nconst image = await faceapi.fetchImage('\u002Fimages\u002Fexample.png')\n\nconsole.log(image instanceof HTMLImageElement) \u002F\u002F true\n\n\u002F\u002F displaying the fetched image content\nconst myImg = document.getElementById('myImg')\nmyImg.src = image.src\n```\n\n### Fetching JSON\n\n``` javascript\nconst json = await faceapi.fetchJson('\u002Ffiles\u002Fexample.json')\n```\n\n### Creating an Image Picker\n\n``` html\n\u003Cimg id=\"myImg\" src=\"\">\n\u003Cinput id=\"myFileUpload\" type=\"file\" onchange=\"uploadImage()\" accept=\".jpg, .jpeg, .png\">\n```\n\n``` javascript\nasync function uploadImage() {\n  const imgFile = document.getElementById('myFileUpload').files[0]\n  \u002F\u002F create an HTMLImageElement from a Blob\n  const img = await faceapi.bufferToImage(imgFile)\n  document.getElementById('myImg').src = img.src\n}\n```\n\n### Creating a Canvas Element from an Image or Video Element\n\n``` html\n\u003Cimg id=\"myImg\" src=\"images\u002Fexample.png\" \u002F>\n\u003Cvideo id=\"myVideo\" src=\"media\u002Fexample.mp4\" \u002F>\n```\n\n``` javascript\nconst canvas1 = faceapi.createCanvasFromMedia(document.getElementById('myImg'))\nconst canvas2 = faceapi.createCanvasFromMedia(document.getElementById('myVideo'))\n```\n\n\u003Ca name=\"models\">\u003C\u002Fa>\n\n# Available Models\n\n\u003Ca name=\"models-face-detection\">\u003C\u002Fa>\n\n## Face Detection Models\n\n### SSD Mobilenet V1\n\nFor 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**).\n\nThe face detection model has been trained on the [WIDERFACE dataset](http:\u002F\u002Fmmlab.ie.cuhk.edu.hk\u002Fprojects\u002FWIDERFace\u002F) and the weights are provided by [yeephycho](https:\u002F\u002Fgithub.com\u002Fyeephycho) in [this](https:\u002F\u002Fgithub.com\u002Fyeephycho\u002Ftensorflow-face-detection) repo.\n\n### Tiny Face Detector\n\nThe 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**).\n\nThe 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.\n\nThis 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).\n\n\u003Ca name=\"models-face-landmark-detection\">\u003C\u002Fa>\n\n## 68 Point Face Landmark Detection Models\n\nThis 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.\n\n\u003Ca name=\"models-face-recognition\">\u003C\u002Fa>\n\n## Face Recognition Model\n\nFor 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.\n\nThe neural net is equivalent to the **FaceRecognizerNet** used in [face-recognition.js](https:\u002F\u002Fgithub.com\u002Fjustadudewhohacks\u002Fface-recognition.js) and the net used in the [dlib](https:\u002F\u002Fgithub.com\u002Fdavisking\u002Fdlib\u002Fblob\u002Fmaster\u002Fexamples\u002Fdnn_face_recognition_ex.cpp) face recognition example. The weights have been trained by [davisking](https:\u002F\u002Fgithub.com\u002Fdavisking) and the model achieves a prediction accuracy of 99.38% on the LFW (Labeled Faces in the Wild) benchmark for face recognition.\n\nThe size of the quantized model is roughly 6.2 MB (**face_recognition_model**).\n\n\u003Ca name=\"models-face-expression-recognition\">\u003C\u002Fa>\n\n## Face Expression Recognition Model\n\nThe 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.\n\n\u003Ca name=\"models-age-and-gender-recognition\">\u003C\u002Fa>\n\n## Age and Gender Recognition Model\n\nThe 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.\n\nThis model has been trained and tested on the following databases with an 80\u002F20 train\u002Ftest 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.\n\n### Total Test Results\n\nTotal MAE (Mean Age Error): **4.54**\n\nTotal Gender Accuracy: **95%**\n\n### Test results for each database\n\nThe `-` indicates, that there are no gender labels available for these databases.\n\nDatabase        | UTK    | FGNET | Chalearn | Wiki | IMDB* | CACD* | MegaAge | MegaAge-Asian |\n----------------|-------:|------:|---------:|-----:|------:|------:|--------:|--------------:|\nMAE             | 5.25   | 4.23  | 6.24     | 6.54 | 3.63  | 3.20  | 6.23    | 4.21          |\nGender Accuracy | 0.93   | -     | 0.94     | 0.95 | -     | 0.97  | -       | -             |\n\n### Test results for different age category groups\n\nAge Range       | 0 - 3  | 4 - 8 | 9 - 18 | 19 - 28 | 29 - 40 | 41 - 60 | 60 - 80 | 80+     |\n----------------|-------:|------:|-------:|--------:|--------:|--------:|--------:|--------:|\nMAE             | 1.52   | 3.06  | 4.82   | 4.99    | 5.43    | 4.94    | 6.17    | 9.91    |\nGender Accuracy | 0.69   | 0.80  | 0.88   | 0.96    | 0.97    | 0.97    | 0.96    | 0.9     |\n","face-api.js 是一个基于 TensorFlow.js 的 JavaScript 库，用于在浏览器和 Node.js 环境中实现人脸检测和人脸识别。它支持多种核心功能，包括人脸检测、面部特征点定位、表情识别、年龄估计以及性别识别等。通过利用 TensorFlow.js 的强大计算能力，该库能够提供高效准确的人脸分析服务。适用于需要集成实时或离线人脸识别功能的应用场景，如安全监控、身份验证系统或者任何希望增强用户体验的网站与移动应用开发项目。",2,"2026-06-11 02:56:16","top_language"]