Easy Face Detection Using JQuery

Face detection is a computer technology being used in a variety of applications that identifies human faces in digital images.

There are a number of approaches and techniques to achieve face detection. In this post, we will be dealing with one of the easiest and simplest way of detecting face in an image, video or canvas using facedetect plugin.

Easy Face Detection with JQuery
Easy Face Detection with JQuery

First, you need to get the JQuery plugin facedetection.min.js from the url:
http://buzzocean.tk/files/facedetect.min.js

Include JQuery and facedetection plugin in the webpage.

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="facedetection.min.js"></script>

Source Code for Face Detection using JQuery Plugin

Use CSS as follows:

<style>
.face{
  position: absolute;
  border: 2px solid #009900;
}
#detect{
  margin-left: 15%;
  cursor: pointer;
  cursor: hand;
}
</style>

The HTML would be as follows:

<img src="images/2.jpg" class="pic" width="50%">
<h2 id="detect">Detect Face</h2>

The JavaScript code to detect the face:

$("#detect").click(function(){
  alert("Detecting Face ..............");
  $(".pic").faceDetection({
    complete:function(faces){
      alert("Detection Complete");
      for(var i=0;i<faces.length;i++){
        $('<div>',{
          'class':'face',
          'css':{
            'position':'absolute',
            'left':faces[i].x*faces[i].scaleX+'px',
            'top':faces[i].y*faces[i].scaleY+'px',
            'width':faces[i].width*faces[i].scaleX+'px',
            'height':faces[i].height*faces[i].scaleY+'px'
          }
        })
        .insertAfter(this);
      }
    },
    error:function(code,message){
      alert("Error: "+message);
    }
  });
});

 

The faceDetection method returns an array object and coords variables becomes an array. Following is the result of array elements.

x: Y coord of the face
y: Y coord of the face
width: Width of the face
height: Height of the face
positionX: X position relative to the document
positionY: Y position relative to the document
offsetX: X position relative to the offset parent
offsetY: Y position relative to the offset parent
confidence: Level of confidence

For visual guide, here is video for you.

Leave a Reply