Last active
January 15, 2020 09:39
-
-
Save caiogondim/a8dd6947db5bae398bd4ac8abb823221 to your computer and use it in GitHub Desktop.
JavaScript native face detection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.