5 мар. 2024

How to Build Facial Recognition Application with Python

Computer Vision is a field of artificial intelligence that studies methods and algorithms for interpreting and analyzing images and videos. The goal is to teach a computer to "detect" and “understand” images in the same way that a human does.

Face recognition is a technology in the field of computer vision that is used in various contexts, such as for accessing a mobile phone, entering a building, and authorizing both physical and digital access. 

Face recognition technology is used to build applications, systems, and software in various fields. Integrating a face recognition API is very easy, and in this tutorial, we will walk you through the steps of creating a face recognition application using Luxand.cloud API on Python.

About Luxand.cloud Face Recognition API

In order to help you reach the best results, Luxand.cloud offers facial recognition API that is cloud-based and AI-powered. Our face recognition solution has a wide range of features, including:

Here is what makes Luxand.cloud face recognition API the best choice for your business and project:

  • Security Guaranteed. Your data remains private. Instead of storing photos, we use anonymous templates, impossible to reverse engineer into faces.

  • Cross-platform. Our solution can be integrated equally into web apps, desktop apps, and mobile apps.

  • High performance. You can expect our solution to be fast and reliable, regardless of the feature you are using.

  • Cost-Effective. The basic plan costs $19/month and includes 10,000 API requests, 500 faces in a storage, and 100 transactions/minute. This is one of the most cost-effective solutions on the market today.

  •  Ready-to-use cases. We've created code examples for most of the popular use cases so you can simply copy and paste them into your project.

Our liveness detection technology used in the Facial Recognition API is iBeta certified.

Luxand.cloud solutions can be used to build applications for various use cases and industries, such as:

  • Finance. For example, banks are using face recognition to verify the identity of customers when they open new accounts or apply for loans.

  • Crypto. Crypto platforms use Luxand.cloud face recognition API for enhanced KYC/AML compliance, fraud prevention, and secure access, ultimately streamlining user experience and boosting platform security. 

  • Gambling. Gambling platforms use face recognition to prevent cheating, account sharing, and prevent unauthorized attempts.

  • Transportation. The technology may be used to verify the identities of passengers and passengers at airports or to track the movements of vehicles.

  • Marketplaces. The usage of facial recognition ranges from personalized advertising and targeted promotions to security measures like shoplifting prevention and access control.

  • Entertainment. Face recognition API can be used to create special effects and filters for photos and videos. For example, a filter might use face detection to change the user's hair color or add funny accessories.

Now that you have an idea of what the Luxand.cloud API is and its advantages, let's dive into a real example of how to use the Luxand.cloud face recognition API using Python.

Building Facial Recognition Application with Python Using Luxand.cloud

We will use the standard synchronous algorithm for making requests to the REST API service, which can be reproduced in any modern programming language.

Preparation

To use the REST API, you need to install any of the frameworks for making HTTP requests to the Luxand.cloud API.

In this example, we will use the requests module because Python Requests is a library that is designed to make working with requests quick and easy. Standard Python HTTP libraries, such as Urllib3, often require significantly more code to perform the same action, which makes it difficult to work with.

To install the library from the command line, you need to enter:

pip install requests

The JSON module, which is included in the standard Python library, is also required to process API responses.

Do not forget to connect the specified libraries in the program code.

import requests

import json

Authorization

To use the Luxand.cloud API, you need to obtain authorization data. To get access, you need a token, which can be obtained for free for a trial period. Each request to the Luxand.cloud API must be accompanied by an HTTP header with the "token" parameter set to the token value. The serialization of such a header in Python will look like this:

headers = {
   "token": token
}

Uploading Images to the Database

To fully use all the functionality of Luxand.cloud, you need to upload your own database of images (dataset) that we will work with. Uploading an image to the Luxand.cloud service is done using a POST request to the URL:

https://api.luxand.cloud/subject/v2

Such a request must be accompanied by the "name" parameter in the request body with the name of the uploaded file, the file itself is directly attached to the request as a byte string (multipart/form-data body type). The implementation in Python will look like this:

headers = {
   "token": token
}

data = {
   "name": name
}

files = {
   "photo": open(image_path, "rb")
}

response = requests.post(url, headers=headers, data=data, files=files)


Name is the file name, image_path is the full path to the file on the system where the code is running, and token is the token for accessing the API.

The result of this request must be accepted in order to extract the ‘id’ field, which is the identifier of the uploaded file in the Luxand.cloud system.

In case of an upload error (incorrect format or too large file size), the service will return an error with its definition in the ‘error’ field of the response.

In Python, the response can be processed as follows:

result = json.loads(response.text)

if response.ok:
    print(result['id'])
else:
    print(result['error'])

Using the Luxand.cloud Functionality

Now everything is ready for the final use of all the features of the Luxand.cloud API.

The API has the following features and corresponding endpoints:

All requests to the Luxand.cloud API endpoints are made using the POST method. The request body is formed similarly to the method of uploading an image to the database (discussed above).

Let's consider an example of using one of the Luxand.cloud API functions. Let's use one of the most popular Computer Vision functions - face recognition. In the Luxand.cloud API, this functionality is provided by the method. Learn more about the method here: Recognize People in a Photo.

Pipeline for using this method, as well as other standard ones:

  1. Method POST

  2. Header

headers = {
   "token": token
}
  1. The request body (multipart/form-data) is the byte contents of the image file in the 'photo' field.

The implementation of such a request in Python using the requests module will look like this:

headers = {
   "token": token
}

files = {
   "photo": open(image_path, "rb")
}

response = requests.post(url, headers=headers, data=data, files=files)

Here is an explanation:

  • image_path is the full path to the file on the system where the code is running.

  • token is the access token for the API.

The service returns a JSON object with the following fields:

  • status - the status of the result, for example "success"

  • name - the name of the person identified in the image, according to the uploaded face database (for example, from the previous step, using this method - Recognize People in a Photo)

  • id - the ID of the person in the photo, also from the uploaded face database

  • confidence - the degree of similarity or "confidence" of our model in the result

  • error - this field is filled in if there is an error

In Python, you can process the response as follows:

result = json.loads(response.text)
if response.ok:
    print(result['status' ], result['name'], result['id'], result['confidence'])
else:
    print(result['error'])


In addition to the basic functionality of the Computer Vision class, our Luxand.cloud API provides auxiliary methods that simplify the use of the main functionality.

For example, the Luxand.cloud API allows you to upload your own collection of photos of people and their faces. You can create a photo gallery from this database and manage it.

You can find out more about the full functionality in the Postman service documentation.

Here is the full version of the Python code implementing the example of face recognition on a photo discussed in the article. The full code listing will look like this:

import requests
import json
import sys

HEADERS = {
   "token": 'XXXXXXXXXXXXXXXXXX'
}


def add_face_to_service(headers, image_path, image_name):
   url = "https://api.luxand.cloud/subject/v2"
  
   data = {
       "name": image_name
   }
   files = {
       "photo": open(image_path, "rb")
   }

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

   if response.ok:
       print(f"Ok adding face: {result['id']}")
       return result['id']
   else:
       print(f"Error adding face: {result['error']}")
       return None


def recognize_face_from_file(headers, image_path):
   url = "https://api.luxand.cloud/photo/search"

   files = {
       "photo": open(image_path, "rb")
   }

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

   if response.ok:
       if result['status'] == "success":
           print(f"Recognized face: {result['name']}, ID: {result['id']}, Confidence: {result['confidence']}")
       else:
           print("No match found")
   else:
       print(f"Error recognizing face: {result['error']}")
      

if __name__ == '__main__':
   #Step1 - Prepare our image database to search faces within it
   file_to_base_path = 'base_file.png'
   file_to_base_name = 'Mr.Test'
  
   id = add_face_to_service(HEADERS, file_to_base_path, file_to_base_name)
   if not id:
       sys.exit()
  
   #Step2 - Recognize particular face from image file
   file_to_recognize_path = 'recognize_file.png'
   recognize_face_from_file(HEADERS, file_to_recognize_path)
  
   sys.exit()

Conclusion

As you can see from this tutorial, working with the Luxand.cloud API is built in a very simple and understandable pipeline. At the same time, the service shows excellent and accurate results.

Image processing takes less than 1 second! Moreover, the algorithm itself can query a database of photos at a speed of 100 million images in just one-tenth of a second.

The Luxand.cloud API does not impose high requirements on the resolution of the processed image, files with a small size and resolution are processed with the same accuracy, the main thing is to observe the condition that there are at least 75 pixels between the person's eyes. Luxand.cloud API perfectly copes with the recognition of images up to 12 KB in size.

And of course, all data and images that you use in the Luxand.cloud API are completely confidential. They are not stored in the service database as is, only their digital vector is stored, which cannot be converted back into an image. Thus, complete data security is achieved when using the Luxand.cloud API.