Python face recognition using AWS Rekognition.

Face recognition using AWS Rekognition with Python programming language.

· 2 min read
Python face recognition using AWS Rekognition.

Hello everyone, In this article, I am going to discuss how you can implement face recognition using an AWS service named "Rekognition" with Python programming language.

For all developers who just needed the code to quickly want to complete the task.

Code Explanation

In this section, I'll be explaining how the code works.

Step 1

import boto3

Firstly we had imported the AWS official library for Python "Boto3".

You can install this using pip  like below

pip install boto3

Step 2

rekognition = boto3.client(
    "rekognition",
    region_name='ap-south-1',
    aws_access_key_id=os.environ['BOTO3_ACCESS_KEY'],
    aws_secret_access_key=os.environ['BOTO3_SECRET_KEY'],
)

In this, we are creating an object of boto3 client. This object will give us access to call the rekognition service. In this, we have to specify these parameters -

  1. Service name
  2. Region name
  3. Access key ID
  4. Secret key

And please make sure that the Access key & Secret key has the proper permission to access the Rekognition service.

Step 3

def match_face(face1, face2):
    try:
        response = rekognition.compare_faces(
            SourceImage={
                'Bytes': face1,
            },
            TargetImage={
                'Bytes': face2,
            },
            SimilarityThreshold=80.0,
            QualityFilter='AUTO'
        )
        if len(response['FaceMatches']) >= 1:
            if response['FaceMatches'][0]['Similarity'] > 80.0:
                print('Match Successful')
        else:
            print('Match Failed')
    except Exception as e:
        print(e)

NOTE  - Both the face images should be in the form of bytes.

In this, we have defined the match_face function that takes images of two faces in the form of bytes and call the rekognition.compare_faces function. The function in response returns the number of faces that match with their score. You can also change the SimilarityThreshold as per your requirement.

Talking about single face matching.  If it contains an empty list, that means the face does not match & if it returns something in the list, check the similarity score, and if the score is greater than a certain number count it as a successful match.

I hope you have found this article informative. If you have any questions related to this article, ask me in the comment section.

BONUS - AWS Lambda function

Here you can also use the code below to directly use it on the AWS Lambda function to make an API for Face Recognition