How to Build a Face Verification Application with Python

How to Build a Face Verification Application 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>

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.

Learn more here: How to Build a Face Verification Application with Python