Simplifying Identity Verification with AWS Rekognition and Gradio: A Step-by-Step Guide

SourceFuse
5 min readMay 27, 2024

--

By Ritika Arora, Machine Learning Engineer, SourceFuse

In an increasingly digital world, verifying identities accurately and efficiently is crucial for various applications.In this blog post, we’ll explore how to leverage the power of AWS Rekognition and Gradio to create a user-friendly face/identity verification system.

Matt Bomer and Henry Cavill

Understanding the Tools:

AWS Rekognition

AWS Rekognition is a powerful computer vision service that enables developers to incorporate facial analysis and recognition capabilities into their applications with ease. It offers pre-trained facial recognition and analysis capabilities that you can quickly add to your user on boarding and authentication workflows to verify opted-in users identity online. Utilising deep learning algorithms, Rekognition can detect, analyse, and compare faces in images and videos, making it a versatile tool for a wide range of use cases, including identity verification.

Gradio

Gradio is an open-source Python library that allows for the rapid creation of customizable UI components for machine learning models. With Gradio, we can create intuitive interfaces for our identity verification system without writing extensive code.

Key Features of AWS Rekognition:

  1. Facial Analysis: Rekognition can detect and analyse key facial features such as eyes, nose and mouth, enabling precise identification and comparison.
  2. Face Matching: The service offers robust face matching capabilities, allowing developers to compare faces with high accuracy and reliability.
  3. Scalability: AWS Rekognition is highly scalable, making it suitable for applications with varying workloads and data volumes.
  4. Security: With built-in encryption and access control features, Rekognition ensures the security and privacy of sensitive facial data.

Implementation:

  1. Data Collection:
  • I gathered images with identical and non-identical faces.
  • I created a Zipfile with 2 or more identical and non-identical faces.

2. Initializing Rekognition Client:

The boto3 library is used to initialize the Rekognition client with the necessary AWS credentials and region information.

Install the necessary packages.

pip install boto3
pip install gradio
pip install python-dotenv

Set your AWS secrets in your environment variables by running below command in your terminal.

export AWS_ACCESS_KEY_ID=<your_aws_access_key>
export AWS_SECRET_ACCESS_KEY=<your_aws_secret_access_key>
export AWS_REGION=<your_aws_region>

Import all the necessary packages into your application.

import boto3
import os
import shutil
from zipfile import ZipFile

3. Getting down with the code:

Compare_images method is used to compare 2 images.unzip_and compare method is used for zip files. It will unzip all the images present in zip file and then images are compared.

utils.py

# IMAGE COMPARISON
def compare_images(sourceFile, targetFile):
access_key = os.getenv("AWS_ACCESS_KEY_ID")
secret_key = os.getenv("AWS_SECRET_ACCESS_KEY")

session = boto3.Session(
aws_access_key_id=access_key, aws_secret_access_key=secret_key
)
client = session.client("rekognition", region_name="us-east-1")
imageSource = open(sourceFile, "rb")
imageTarget = open(targetFile, "rb")

response = client.compare_faces(
SimilarityThreshold=80,
SourceImage={"Bytes": imageSource.read()},
TargetImage={"Bytes": imageTarget.read()},
)
for faceMatch in response["FaceMatches"]:
position = faceMatch["Face"]["BoundingBox"]
similarity = str(faceMatch["Similarity"])

imageSource.close()
imageTarget.close()
match = len(response["FaceMatches"])
confidence=response['SourceImageFace']['Confidence']
if match == 1:
confidence="{:.3f}".format(confidence)
return f"Faces are Identical with condidence level of {confidence}"
else:
return "Faces are not Identical!"

def del_folder(*args):
path = list(args)
for x in path:
folder_path = x.split("/")
folder_path = "/".join(map(str, folder_path[0:4]))
shutil.rmtree(folder_path)

# ZIPFILE COMPARISON

def extract_zip(zip_file):
# Get the base name of the zip file (without the extension)
folder_name = os.path.splitext(zip_file)[0]

# Create a folder with the same name as the zip file
os.makedirs(folder_name, exist_ok=True)

# Extract the contents of the zip file into the created folder
with ZipFile(zip_file, 'r') as zip_ref:
zip_ref.extractall(folder_name)
return folder_name

def unzip_and_compare(image_folder):
folder_path=extract_zip(image_folder)
path=os.listdir(folder_path)
path=sorted(path)
path= path[0]
file_path = os.path.join(folder_path, path)

extracted_images = [f for f in os.listdir(file_path) if f.endswith(('.png', '.jpg', '.jpeg'))]

# Compare images
results = []
for i in range(len(extracted_images)):
for j in range(i+1, len(extracted_images)):
image1_path = os.path.join(file_path, extracted_images[i])
image2_path = os.path.join(file_path, extracted_images[j])

# Perform image recognition using AWS Rekognition
rekognition = boto3.client('rekognition', region_name='us-east-1')
with open(image1_path, 'rb') as image1_file, open(image2_path, 'rb') as image2_file:
response = rekognition.compare_faces(
SourceImage={'Bytes': image1_file.read()},
TargetImage={'Bytes': image2_file.read()}
)
# Store the comparison result
match = len(response["FaceMatches"])
confidence=response['FaceMatches'][0]['Similarity']
if match == 1:
confidence="{:.3f}".format(confidence)
results.append(f"{extracted_images[i]} and {extracted_images[j]} are Identical with Confidence level of {confidence}")

else:
results=f"{extracted_images[i]} and {extracted_images[j]} are not Identical"
results = '\n'.join(results)
return results

4.Making User Interface using Gradio:

Gradio Interface allows you to create a web-based GUI around a machine learning model. You have to upload Images/Zip file from your local system. upload_image method is used to upload images and upload_zip method is used to upload Zip file.

Here, I have used gr.TabbedInterface for providing a list of Interfaces, each of which gets rendered in a separate tab. Only the components from the Interface will be rendered in the tab.

main.py

import gradio as gr
from utils import compare_aws, del_folder,unzip_and_compare
from dotenv import load_dotenv
import shutil

load_dotenv()

def upload_image(file1, file2):
try:
image_path1 = file1.name
image_path2 = file2.name
if image_path1 != image_path2:
result = compare_aws(image_path1, image_path2)
# Delete the import shutiltemporary folder and its contents
del_folder(image_path1, image_path2)
else:
result= "Images are identical with confidence level of 100%"
# Delete the import shutiltemporary folder and its contents
del_folder(image_path1)
return result

except Exception as e:
raise gr.Warning("Please use clear button to upload new image!")


def upload_zip(zip_file):
# Step 1: Unzip and Compare images using AWS Rekognition
image_folder = zip_file.name
comparison_results = unzip_and_compare(image_folder)

# Step 2: Clean up
del_path=image_folder.split("/")
del_path=folder_path = "/".join(map(str, del_path[0:4]))
shutil.rmtree(del_path)
return comparison_results

# For Image Comparison
interface1 = gr.Interface(
fn=upload_image,
allow_flagging="never",
inputs=[gr.File(label="Upload Image 1"), gr.File(label="Upload Image 2")],
outputs=gr.Textbox(label="RESULTS"))

# For Zip Comparison
interface2 = gr.Interface(
fn=upload_zip,
allow_flagging="never",
inputs=gr.File(label="Upload a zip file containing images"),
outputs=gr.Textbox(label="RESULTS"))

app = gr.TabbedInterface(interface_list=[interface1, interface2],
tab_names = ["UPLOAD IMAGE", "UPLOAD ZIP"])

if __name__ == '__main__':
app.launch(server_name="0.0.0.0", server_port=7860)
$ python main.py

Output:

The AWS Rekognition achieves remarkable performance in face identity verification. It accurately distinguishes between the two images, providing the correct response. It operates with high confidence levels, enhancing its reliability and usability.

In the output image, it correctly identifies the faces of Matt Bomer and Henry Cavill (who bears a resemblance to Matt Bomer) as non-identical.

verified images as non-identical

Conclusion:

By combining the capabilities of AWS Rekognition and the user-friendly interface provided by Gradio, we’ve created a robust and intuitive identity verification system. Whether it’s for authenticating users, verifying identities, or enhancing security measures, this solution offers a seamless and efficient way to perform face matching tasks.

--

--

SourceFuse
SourceFuse

Written by SourceFuse

Strategic digital transformation helping businesses evolve through cloud-native technologies

No responses yet