Skip to content

Instantly share code, notes, and snippets.

@ArunMichaelDsouza
Last active January 30, 2021 21:22
Show Gist options
  • Save ArunMichaelDsouza/ffe8b8eedf5909732a22907283f86430 to your computer and use it in GitHub Desktop.
Save ArunMichaelDsouza/ffe8b8eedf5909732a22907283f86430 to your computer and use it in GitHub Desktop.
Face Detection using the Shape Detection API
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>Face Detection using the Shape Detection API</title>
<style>
body {
margin: 0;
font-family: sans-serif;
}
.marker {
position: absolute;
border: 2px solid red;
}
button {
display: block;
padding: 15px;
cursor: pointer;
margin-top: 10px;
}
#message {
margin-top: 10px;
}
</style>
</head>
<body>
<img id="image" src="image.jpg" />
<button id="button">Detect faces</button>
<div id="message"></div>
<script>
const image = document.getElementById('image');
const button = document.getElementById('button');
const message = document.getElementById('message');
const addFaceMarker = (boundingBox) => {
const { width, height, top, left } = boundingBox;
const marker = document.createElement('div');
marker.classList.add('marker');
marker.style.width = `${width}px`;
marker.style.height = `${height}px`;
marker.style.top = `${top}px`;
marker.style.left = `${left}px`;
document.body.appendChild(marker);
};
const detectFaces = () => {
if (!window.FaceDetector) {
message.innerText = 'Face Detection is not supported in your browser';
return;
}
const faceDetector = new FaceDetector();
faceDetector
.detect(image)
.then((faces) => {
console.log(faces);
faces.forEach((face) => {
const { boundingBox } = face;
addFaceMarker(boundingBox);
});
message.innerText = `Faces detected: ${faces.length}`;
})
.catch((e) => {
console.error(`Face Detection failed: ${e}`);
});
};
button.addEventListener('click', detectFaces);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment