paint-brush
How I Built a Facial Recognition Application Using JavaScript and the Luxand.cloud APIby@marklooook
146 reads

How I Built a Facial Recognition Application Using JavaScript and the Luxand.cloud API

by Mark LookAugust 27th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Building a facial recognition application with JavaScript is not a daunting task. In this blog post, we'll explore the key libraries and tools that made this project possible. We'll also delve into the core concepts behind facial recognition technology and share practical insights that can help you implement similar solutions in your own projects.
featured image - How I Built a Facial Recognition Application Using JavaScript and the Luxand.cloud API
Mark Look HackerNoon profile picture

Building a facial recognition application with JavaScript might seem like a daunting task, but it's more accessible than you might think. In this blog post, I'll walk you through the journey of developing a facial recognition app from scratch using JavaScript. We'll explore the key libraries and tools that made this project possible, delve into the core concepts behind facial recognition technology, and share practical insights that can help you implement similar solutions in your own projects. Whether you're a seasoned developer or just starting out, this guide will show you how to turn a complex idea into a functioning application.

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>

Conclusion

As you can see, to integrate the face recognition API and use it is really easy. If you have questions or I didn’t cover some topics, please, share your thoughts below in the comments section.