Skip to content

Instantly share code, notes, and snippets.

@caiogondim
Last active January 15, 2020 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caiogondim/a8dd6947db5bae398bd4ac8abb823221 to your computer and use it in GitHub Desktop.
Save caiogondim/a8dd6947db5bae398bd4ac8abb823221 to your computer and use it in GitHub Desktop.
JavaScript native face detection
async function draw (canvas, video, overlay) {
window.requestAnimationFrame(() => draw(canvas, video, overlay))
const context = canvas.getContext('2d')
const videoCompStyle = window.getComputedStyle(video)
const videoWidth = videoCompStyle.width.replace('px', '')
const videoHeight = videoCompStyle.height.replace('px', '')
context.drawImage(video, 0, 0, videoWidth, videoHeight)
clearTimeout(hideTimeout)
if (faces.length) {
const face = faces[0].boundingBox
overlay.style.display = 'block'
overlay.style.left = `${face.left - (face.width * 0.5)}px`
overlay.style.top = `${face.top - (face.height * 0.75)}px`
overlay.style.width = `${face.width * 2}px`
overlay.style.height = `${face.height * 2}px`
} else {
hideTimeout = hideOverlay(overlay)
}
if (isDetectingFaces) return
isDetectingFaces = true
faces = await faceDetector.detect(canvas)
isDetectingFaces = false
}
const faceDetector = new window.FaceDetector()
const img = document.querySelector('img')
try {
const faces = faceDetector.detect(img)
console.log('Faces detected: ', faces)
} catch (error) {
console.error('Error on face detection', error)
}
@ocdejong
Copy link

Before you can use the FaceDetector API in Chrome visit URL: chrome://flags/#enable-experimental-web-platform-features
-Enable the Experimental Web Platform features section.
-You should see a Relaunch Now button on the bottom of the screen.
-After relaunching you should be able to access the FaceDetector API from a console window for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment