27 мар. 2024

How to Build a Facial Recognition Application with JavaScript

Luxand.cloud created a series of blog posts on how to integrate the face recognition API using different programming languages. From this blog post, you'll learn how to build a facial recognition application with JavaScript. If you're interested in Python, read this blog post: How to Build a Facial Recognition Application with Python.

Free Facial Recognition API

Luxand.cloud offers a free plan for the API that allows you to integrate it into your project and try out the service. Here's a breakdown of the free plan:

This plan is available for all API features:

  • Face recognition API

  • Face verification API

  • Emotion detection API

  • Face similarity API

  • Face cropping API

  • Facial landmark detection API

  • Age and gender detection API

The free plan is well-suited for those who are just getting started with face recognition or who have low usage needs. It's a good way to test the accuracy, speed, and ease of use of Luxand.cloud's API.

You can sign up for the free plan by creating an account - Sign Up for a Free Plan.

There are other benefits that comes with a free plan:

  • Secure cloud storage. This proves beneficial when there's a requirement for a facial database across diverse devices or services. We strictly refrain from storing any images; instead, we exclusively retain neural network templates, which are incapable of reconstructing photos. Hence, our approach ensures utmost safety in usage.

  • Cross-platform. You can our solution equally and easily into web apps, desktop apps, and mobile apps.

  • High performance. The robust CPU resources allocated to our cloud servers ensure optimal performance across all the functionalities we provide. For instance, our face recognition feature operates with an impressive speed, completing tasks in just 60 milliseconds.

Face Recognition API Use Cases

You can use Luxand.cloud face recognition API for various use cases:

  • Financial services. Cryptocurrency platforms leverage Luxand.cloud's face recognition for stricter ID verification (KYC/AML), reducing fraud, and securing access. This improves user experience and platform security overall.

  • Gambling. Facial recognition helps prevent cheating, unauthorized access, and account sharing on gambling platforms.

  • Transportation. Airports and other transportation hubs can use this technology to verify passenger identities and track vehicles.

  • Retail. Marketplaces use facial recognition for various purposes, including personalized advertising, targeted promotions, security measures like shoplifting prevention, and access control.

  • Entertainment. Face recognition APIs are utilized to craft special effects and filters for photos and videos, allowing for creative alterations like changing hair color or adding amusing accessories based on detected facial features.

Building Facial Recognition Application with JavaScript Using Luxand.cloud

Here we demonstrate the use of Luxand.cloud Face Recognition API in JavaScript by showing you how to add faces to a database and call the recognition method to identify them.

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

Congratulations! You've taken the first step towards building a powerful facial recognition application with JavaScript and Luxand.cloud. Remember, this is just the beginning. With the knowledge you've gained, you can explore more advanced features offered by Luxand.cloud's API, such as face tracking, emotion recognition, liveness detection and more. The possibilities are vast.

We encourage you to experiment, explore Luxand.cloud's resources, and keep building! Feel free to join pur Reddit community to ask questions on our facial recognition.