Face detection is a computer technology being used in a variety of applications that identifies human faces in digital images. Face detection also refers to the psychological process by which humans locate and attend to faces in a visual scene. Face detection can be applied for various fields from proctoring online exams to personal safety.
In this blog post, we will implement how to detect face from a image on client side using face-api.js. We will use vanilla JS to integrate face-api.js in our web app.
Folder Structure
Here,
models
folder contain the models downloaded from face-api.js library.face-api.min.js
from the face-api.js library's dist folder.index.html
script.js
contains the script to detect the face and draw the image in a new element- And a sample image with face
Include Libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script defer src="face-api.min.js"></script>
<script defer src="script.js"></script>
Setting up HTML
<div id="main-image">
<div style="width: 50%">
<img src="Shadman.png" alt="" id="img1" width="500">
</div>
<div style="width: 50%">
<img id="cropped-img1" src="" alt="">
</div>
</div>
Here, first image is the test image with a face, and the second image for the cropped image after the face detection is done.
Loading the model for face detection
// Load the model.
Promise.all([
faceapi.nets.ssdMobilenetv1.loadFromUri('/models'),
]).then(() => {
image1 = detectface(input1, croppedImage1);
}
)
Only one model for detecting the face is loaded here.
Detecting the face
// Function to detect the face.
var detectface = async function (input, croppedImage){
const output = await faceapi.detectAllFaces(input);
detections = output[0].box;
let res = extractFaceFromBox(input, detections, croppedImage);
return res;
}
Drawing an image with data found after detecting face
// Function to draw image from the box data.
async function extractFaceFromBox(imageRef, box, croppedImage) {
const regionsToExtract = [
new faceapi.Rect(box.x, box.y, box.width, box.height)
];
let faceImages = await faceapi.extractFaces(imageRef, regionsToExtract);
if (faceImages.length === 0) {
console.log("No face found");
} else {
faceImages.forEach((cnv) => {
croppedImage.src = cnv.toDataURL();
});
console.log(croppedImage.src);
return croppedImage.src;
}
}
That's it. We have already detected face from a given image. The output should be something like this:
The code repository for this simple implementation of face-api.js can be found here.
Thanks for reading!