10 апр. 2024

How to Build a Face Verification Application with Python

A face verification API leverages the power of facial recognition technology, offering a secure and user-friendly approach to verification across various applications. And developers can easily build such face verification applications using ready-made face verification API or integrate into an already exisitng system or software. In this article we will demontrate how to build face verification with Python using Luxand.cloud face verification API.

What is Face Verification API?

A face verification API is a tool for developers designed to automate the process of verifying a person's identity using facial recognition technology. This technology verifies a person's identity by comparing a digital or live image of their face to a stored image. These types of APIs are frequently utilized in many different applications, such as access control, financial services, security systems, and any digital service that needs identity verification to improve security and user experience.

It's important to distinguish face verification from face recognition. Face verification works in a closed set, comparing a captured face to a specific enrolled image (like your driver's license photo) and confirms identity. Face recognition aims to identify someone, regardless of who they claim to be. It searches a large database of faces to find a match.

How Does Face Verification Work?

Here are the steps of face verification process and how a face verification application works:

  • Image capture. The API receives a live or uploaded image of a user's face. This can be done through cameras on smartphones, tablets, laptops, or other digital devices.

  • Face detection. One or more faces in the image are recognized and located by the system. This phase is essential to ensure that the verification process ignores unimportant portions of the image and concentrates on the face region.

  • Feature extraction. Once the face has been identified, the algorithm examines it to extract distinctive features and traits. This contains distinguishable features such as the separation between the eyes, nose, cheekbones, and jawline form.

  • Comparison. After that, the retrieved facial traits are compared to a specific image or a database containing one or more faces for confirmation. This database might consist of a group of previously saved photos or, for one-to-one verification, a single reference image per user.

  • Verification decision. The API assesses whether there is a match based on the comparison. Subsequently, it provides an answer showing the success of the verification, frequently accompanied by a probability or confidence score signifying the precision of the match.

Face Verification Use Cases

  • Financial transactions. Facial verification API can be used to authenticate users for online banking, mobile payments, and other financial transactions. Face verification guarantees that only those with permission can access private financial information or start transactions, it greatly improves security. By using biometric techniques, such facial recognition, to confirm the user's identification, the possibility of fraudulent activities, like identity theft or account takeover, is significantly decreased. Plus, facial verification makes the login process more convenient. Rather than depending on laborious verification techniques like passwords or security questions, users can authenticate themselves by merely glancing at the camera on their device.

  • Access control. Numerous advantages arise from integrating facial verification into security checkpoints and access control systems. By limiting access to sensitive locations and preventing unauthorized individuals from crossing borders, it improves security by reducing the possibility of unauthorized entry and possible security threats. It also expedites the authentication procedure, cutting down on wait times and improving security operations' overall effectiveness.

  • Time and attendance tracking. One of the key advantages of using facial recognition for attendance tracking is its accuracy and reliability. In contrast to conventional techniques like PIN numbers or swipe cards, which are shared or easily altered, facial biometrics provide a distinct, unchangeable identity that is directly linked to the person. As a result, there is a much lower chance of fraudulent clock-ins or clock-outs, guaranteeing that every attendance record correctly indicates the employee's presence or absence. To learn more about a face recognition attendance system and how it works, visit our website page: Face Recognition Attendance System.

Luxand.cloud Face Verification API

Luxand.cloud offers a face verification API that's part of the suite of facial recognition and biometric services. This API allows developers to integrate face recognition capabilities into their applications, enabling the verification of users' identities through facial biometrics. Here are some benefits of Luxand.cloud Face Verification API:

  • Free plan. You can use Luxand.cloud face verification API for free to build your app/software! 500 API requests are available monthly for every user, you just need to create an account.

  • Real-time face verification. Enables the comparison of a live or captured image against a stored face image to verify an individual's identity. This feature is crucial for security-sensitive applications like banking apps, secure access systems, and any platform requiring reliable user authentication.

  • High accuracy. Luxand.cloud's facial recognition algorithms are known for their precision, ensuring high reliability in face matching and verification. This accuracy holds up even with variations in lighting, angles, or facial expressions over time.

  • Liveness detection. Luxand.cloud provides a liveness detection API as well to prevent spoofing and the usage of images, videos, or masks for authentication. This feature adds an additional layer of protection by guaranteeing that the face being validated is present in real time.

  • Ease of integration. Luxand.cloud provides a well-documented API so developers can easily integrate it into web, desktop, or mobile applications, allowing for a wide range of use cases across different platforms.

  • Cloud-based solution. Since Luxand.cloud runs in the cloud, you don't need to invest in expensive hardware or software to use it. This makes it scalable to your needs – no matter if you're a small startup or a large corporation. All you need is an internet connection to access the API's functionalities.

How to Build Face Verification with Python

Below we'll demonstrate the use of Luxand.cloud face verification API in Python by showing you how to enroll a person into the database and then verify if this person appears in another photo.

Setting up the Environment

Install the required libraries by running the following command in your terminal:

pip3 install requests

Enrolling the Person

Create a Python file and import the necessary libraries:

#!/usr/bin/env python3

import requests
import json

API_TOKEN = "your_token"

Define a function to add a person to the database:

def add_person(name, image_path, collections = ""):
    if image_path.startswith("https://"):
        files = {"photos": image_path}
    else:
        files = {"photos": open(image_path, "rb")}

    response = requests.post(
        url="https://api.luxand.cloud/v2/person",
        headers={"token": API_TOKEN},
        data={"name": name, "store": "1", "collections": collections},
        files=files,
    )

    if response.status_code == 200:
    	person = response.json()

    	print("Added person", name, "with UUID", person["uuid"])
    	return person["uuid"]
    else:
    	print("Can't add person", name, ":", response.text)
    	return None

Now you can add people to the database one by one:

person_name = "person name"

# path to image can be local file name or URL
path_to_image = "path_to_image"

# enter the collection name to create the collection and add person to it
collection_name = ""

person_uuid = add_person(person_name, path_to_image, collection_name)

Improving Accuracy of Verification

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

def add_face(person_uuid, image_path):
    if image_path.startswith("https://"):
        files = {"photo": image_path}
    else:
        files = {"photo": open(image_path, "rb")}


    response = requests.post(
        url="https://api.luxand.cloud/v2/person/%s" % person_uuid,
        headers={"token": API_TOKEN},
        data={"store": "1"},
        files=files
    )

Now, add more photos to this person to improve face verification accuracy. While having a single image of a person is acceptable, adding 3-5 more images will significantly improve face verification accuracy.

add_face(person_uuid, "path_to_another_image")

Verification Process

Define a function to verify an individual:

def verify_person(person_uuid, image_path):
    url = "https://api.luxand.cloud/photo/verify/%s" % person_uuid
    headers = {"token": API_TOKEN}

    if image_path.startswith("https://"):
        files = {"photo": image_path}
    else:
        files = {"photo": open(image_path, "rb")}

    response = requests.post(url, headers=headers, files=files)
    result = json.loads(response.text)

    if response.status_code == 200:
        return response.json()
    else:
        print("Can't recognize people:", response.text)
        return None

Replace the path_to_image_for_recognition with the actual image file path.

Complete Code

Here you can find the complete version of the code we used above. You can just copy and paste it into your file, replace parameters, and it will work.

<!doctype html>
<html lang="en">
<head>
    <meta name="robots" content="noindex">
	<link rel="stylesheet" href="/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

	<link rel="stylesheet" href="/css/signup.css?20240327" defer>
	<link rel="stylesheet" href="/css/menu.css?20240327" defer>
	<link rel="stylesheet" href="/css/dashboard.css?20240327" defer>
	<link rel="stylesheet" href="/css/token.css?20240327" defer>
	<link rel="stylesheet" href="/css/profile.css?20240327" defer>
	<link rel="stylesheet" href="/css/documentation.css?20240327" defer>
    <link rel="stylesheet" href="/css/billing.css?20240327" defer>
    <link rel="stylesheet" href="/css/widget.css?20240327" defer>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" />


    <script src="https://checkout.stripe.com/checkout.js"></script>
    <script src="https://js.stripe.com/v3/" defer></script>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/css/bootstrap-select.min.css">


<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/css/intlTelInput.css">
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/intlTelInput.min.js"></script>

    



<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-171548798-1"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-171548798-1');
</script>


<!-- Global site tag (gtag.js) - Google Ads: 618209357 -->
<script>
  window.dataLayer2 = window.dataLayer || [];
  function gtag2(){dataLayer.push(arguments);}
  gtag2('js', new Date());

  gtag2('config', 'AW-618209357');
</script>


</head>
<body>



<script type="text/javascript" src="/js/jquery.min.js?20240327"></script>
<script type="text/javascript" src="/js/jquery.cookie.js?20240327"></script>

<script src="/js/popper.min.js?20240327" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="/js/bootstrap.min.js?20240327" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<script src="/js/highcharts.src.js?20240327"></script>

<link rel="stylesheet" href="/css/rainbow.css?20240327">
<script src="/js/highlight.min.js?20240327"></script>

<!-- Latest compiled and minified JavaScript -->
<script src="/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="/js/statistics.js?20240327"></script>
<script type="text/javascript" src="/js/onboarding.js?20240327"></script>
<script type="text/javascript" src="/js/page.js?20240327"></script>
<script type="text/javascript" src="/js/widget.js?20240327"></script>
<script type="text/javascript" src="/js/api-docs.js?20240327"></script>

<script type="text/javascript" src="/js/documentation.js?20240327"></script>
<script type="text/javascript" src="/js/attendance.js?20240327"></script>
<script type="text/javascript" src="/js/app.js?20240327"></script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>

<script type="text/javascript" src="/js/fabric.min.js"></script>

<script type="text/javascript">
var clicked=false;//Global Variable
function ClickLogin()
{
    clicked=true;
}
</script>


    


    <!--
<div class="g-signin2 container" onclick="ClickLogin()" data-onsuccess="onSignIn" data-width="230" data-height="38" data-theme="dark" data-longtitle="true" style="display: none;">Continue with Google</div>
-->


<script src="/js/bundle.min.js" integrity="sha384-/Cqa/8kaWn7emdqIBLk3AkFMAHBk0LObErtMhO+hr52CntkaurEnihPmqYj3uJho" crossorigin="anonymous">
</script>

<script src="https://js.stripe.com/v3/"></script>

<script type="text/javascript">
    
function face_login(token){
        $.ajax("https://api.luxand.cloud/user", {
             method: 'POST',
             data: {
                    type: "token",
                    token: token,
                    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
                },
            crossDomain: true,
            success: function(response, status, xhr){
                    console.info(xhr)

                    if (response.token != undefined){
                        $.cookie("token", response.token, {path: "/"})
                        setTimeout(function(){
                            window.app.location("/dashboard")
                        }, 100)
                        
                    }
            }
    })
}  

function face_link(token){
    window.face_token = token
}

</script>

<script type="text/javascript">
Sentry.init({ dsn: 'https://2c90da9a886f4f9fa7b47bffb41cc68b@sentry.io/1757791' });
</script>

<!-- Chatra {literal} -->
<!-- <script>
    (function(d, w, c) {
        w.ChatraID = 'utDbYJs964bJzgs8g';
        var s = d.createElement('script');
        w[c] = w[c] || function() {
            (w[c].q = w[c].q || []).push(arguments);
        };
        s.async = true;
        s.src = 'https://call.chatra.io/chatra.js';
        if (d.head) d.head.appendChild(s);
    })(document, window, 'Chatra');
</script> -->
<!-- /Chatra {/literal} -->


<div aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center" style="min-height: 0px;">
  <div class="toast" style="position: fixed; bottom: 10px; right: 0;z-index: -1; margin-top: 10px; margin-right: 10px;">
    <div class="toast-header">
      <img src="/img/favicon.ico" class="rounded mr-2" alt="..." style="width:20px;">
      <strong class="mr-auto">Luxand.cloud</strong>
      <small>now</small>
      <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
        <span aria-hidden="true">×</span>
      </button>
    </div>
    <div class="toast-body">
      <b>The code has been successfully copied to your clipboard</b>
      <br/><br/>You are now able to paste it into the desired location within your project. 
    </div>
  </div>
</div>


</body>
</html>

Conclusion

Developing a face verification application from the ground up can be a complex task. However, the emergence of face verification APIs has significantly simplified the process for developers. These APIs offer pre-built functionalities, allowing integration of facial recognition features into various applications without requiring in-depth knowledge of computer vision algorithms. This streamlines development and accelerates the creation of face verification applications.

Luxand.cloud offers secure, scalable and easy to use face verification API. This can be beneficial for developers seeking to integrate facial recognition functionalities into their applications without extensive expertise in the underlying technology.

Create a free account, follow the steps and enjoy the face verification technology!

Have questions? Feel free to join pur Reddit community to ask questions on our facial recognition.