How to Build a Facial Recognition Application with JavaScript

How to Build a Facial Recognition Application with JavaScript

Setting up the Environment

Let's start from creating JS file "recognition.js" with all functions that we will use during the process. First of all, we are adding API_TOKEN as a global variable. You can find your token in your Luxand.cloud dashboard and then just copy the code and paste into your file:

API_TOKEN = "your_token"

Adding People to the Database

Define a function to the person to the database:

function add_person(name, image, collections, callback){
    var myHeaders = new Headers();
    myHeaders.append("token", API_TOKEN);

    var formdata = new FormData();
    formdata.append("name", name);

    if ((typeof image == "string") && (image.indexOf("https://") == 0))
        formdata.append("photos", image);
    else
        formdata.append("photos", image, "file");

    formdata.append("store", "1");
    formdata.append("collections", collections);

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: formdata,
      redirect: 'follow'
    };

    fetch("https://api.luxand.cloud/v2/person", requestOptions)
      .then(response => response.json())
      .then(result => callback(result))
      .catch(error => console.log('error', error));
}

Improving Accuracy of Recognition

If you upload more than one image of a person, the face recognition engine will be able to recognize people with better accuracy. To do that, create a function that can add faces to a person.

function add_face(person_uuid, image, callback){
    var myHeaders = new Headers();
    myHeaders.append("token", API_TOKEN);

    var formdata = new FormData();

    if ((typeof image == "string") && (image.indexOf("https://") == 0))
        formdata.append("photos", image);
    else
        formdata.append("photos", image, "file");

    formdata.append("store", "1");

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: formdata,
      redirect: 'follow'
    };

    fetch("https://api.luxand.cloud/v2/person/" + person_uuid, requestOptions)
      .then(response => response.json())
      .then(result => callback(result))
      .catch(error => console.log('error', error));
}

Recognizing Faces

Define a function to recognize faces:

function recognize(image, callback){
    var myHeaders = new Headers();
    myHeaders.append("token", API_TOKEN);

    var formdata = new FormData();    

    if ((typeof image == "string") && (image.indexOf("https://") == 0))
        formdata.append("photo", image);
    else
        formdata.append("photo", image, "file");

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: formdata,
      redirect: 'follow'
    };

    fetch("https://api.luxand.cloud/photo/search/v2", requestOptions)
      .then(response => response.json())
      .then(result => callback(result))
      .catch(error => console.log('error', error)); 
}

Replace the path_to_image_for_recognition with the actual image file path for recognition.

Complete HTML File

Here you can find the HTML file that is using our "recognition.js" library. You can just copy and paste it into your file, replace parameters, and it will work.

<!DOCTYPE html> 
<html> 
<head>
    <title>Face recognition demo</title>
    <script src="recognition.js"></script>
</head>

<body>
    <div class="adding-person">
        <h2>Step 1: Adding a person</h2>

        <div style="padding-bottom: 20px;">Please choose the photo of any person</div>
        <input type="file" name="face" onchange="javascript:upload_person()"/>
        <div class="person-result" style="display: none; padding-top: 20px;">Person UUID is <span id="person_id"/></div>
    </div>

    <div class="recognition" style="display: none;"> 
        <h2>Step 2: Recognition</h2>
        <div style="padding-bottom: 20px;">Now choose the photo with the same person</div>
        <input type="file" name="photo" onchange="javascript:recognize_people()"/>

        <div class="recognize-result" style="display: none; padding-top: 20px;">Recognized people <span id="people_uuids"/></div>
    </div>
</body>

<script>
function upload_person(){
    var face = document.getElementsByName("face")[0].files[0];

    add_person("person name is here", face, "", function(result){
        if (result.status == "success"){
            document.getElementById("person_id").innerHTML = result["uuid"]

            // showing the result and the next step
            document.getElementsByClassName("person-result")[0]["style"]["display"] = "block"
            document.getElementsByClassName("recognition")[0]["style"]["display"] = "block"
        }

    });
}

function recognize_people(){
    var photo = document.getElementsByName("photo")[0].files[0];

    recognize(photo, function(result){
        document.getElementById("people_uuids").innerHTML = result.map(function(person){ return person["uuid"]}).join(", ")
        document.getElementsByClassName("recognize-result")[0]["style"]["display"] = "block"
    });
}
</script>

</html>