Setup AWS Rekognition API with NodeJS SDK (v3)
Hello! This is my first blog, so I'll try to be clear and right to the point.
One day I was trying to implement the face recognition service of Amazon; Rekognition.
During my investigation, I encountered a little big problem. The AWS Rekognition documentation is quite... obsolete? I'm not trying to say that it is definitely out of date, but it was hard to get the information I needed. For example;
AWS SDK v2 is still on the main documentation
If you visit this link (March 2023), you will notice that the example shown of using the Compare Faces in Images service with NodeJS is still using the v2 of the AWS SDK:
const AWS = require('aws-sdk')
const bucket = 'bucket' // the bucketname without s3://
const photo_source = 'source.jpg'
const photo_target = 'target.jpg'
const config = new AWS.Config({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
})
const client = new AWS.Rekognition();
const params = {
SourceImage: {
S3Object: {
Bucket: bucket,
Name: photo_source
},
},
TargetImage: {
S3Object: {
Bucket: bucket,
Name: photo_target
},
},
SimilarityThreshold: 70
}
client.compareFaces(params, function(err, response) {
if (err) {
console.log(err, err.stack); // an error occurred
} else {
response.FaceMatches.forEach(data => {
let position = data.Face.BoundingBox
let similarity = data.Similarity
console.log(`The face at: ${position.Left}, ${position.Top} matches with ${similarity} % confidence`)
}) // for response.faceDetails
} // if
});
The little big problem begins when you take the above code and put it into your project, you'll notice this message in the console:
NOTE: We are formalizing our plans to enter AWS SDK for JavaScript (v2) into maintenance mode in 2023.
Please migrate your code to use AWS SDK for JavaScript (v3).
For more information, check the migration guide at https://a.co/7PzMCcy
Not that all a problem, but they strongly recommend migrating your code just to use their v3 SDK.
For this particular case, I'm going to make it easy for you how to quickly implement the AWS SDK v3 before you start coding your entire project. (We´re talking about AWS Rekognition, right? 😁)
First of all, I am assuming that you already have:
NodeJS project (In this case I'm using it with Express)
A
"type": "module"
project (in your package.json 😎)AWS IAM user with credentials (yup, that CSV file with your
accessKeyId
andsecretAccessKey
👌)The hidden (okay, not at all) documentation of the AWS SDK v3 for Rekognition
And (optional) an S3 Bucket
Shall we start?
Installing AWS Rekognition dependencies
According to the documentation, we need to install the separate package of AWS Rekognition:
NPM: npm install @aws-sdk/client-rekognition
Yarn: yarn add @aws-sdk/client-rekognition
PNPM: pnpm add @aws-sdk/client-rekognition
And of course, bring the imports like this:
import {
RekognitionClient,
CompareFacesCommand,
DetectFacesCommand,
DetectLabelsCommand
} from "@aws-sdk/client-rekognition";
"The AWS SDK is modulized by clients and commands.".- AWS
So, you may have noticed that I have imported the main client (RekognitionClient
),
and 3 commands that I'm using as an example of how you can use the other services they offer: CompareFacesCommand
, DetectFacesCommand
and DetectLabelsCommand
You are not familiar with these commands? In your AWS Console, you can check the free demo of each command and what they do (Not sponsored) or I'm pretty sure that you have already read the Main Documentation 😁(Of course you don't need to read the exact whole documentation, remember only to catch what you need 🫠)
Coding... (Did you skip to this part?! 👺)
Let's initialize our client:
const rekognitionClient = new AWS.RekognitionClient({
region: AWS_BUCKET_REGION, //This is a .env variable of the AWS region
credentials: {
accessKeyId: AWS_PUBLIC_KEY, //Same here, with our public key
secretAccessKey: AWS_SECRET_KEY,// Same here, with our secret key
},
});
Next, we need to define the parameters that we will use to send a request. In this example, I will use the CompareFacesCommand
. In the code below, I'm sending a base64 string from a client in order to compare faces between that base64 image and an S3 Object (corresponding to an image stored in an S3 Bucket)
const buffer = Buffer.from(req.body.base64Url, "base64");
//Format the base64 string into a new buffer with our base64 string.
const params = {
SourceImage: { //The image we send
Bytes: buffer, //We can change this to an S3 Object, no worries.
},
TargetImage: { //The image that will be compared with the one we sent
S3Object: {
Bucket: AWS_BUCKET_NAME,
Name: `${req.body.username}.jpeg`, //Name of the S3 Object (image)
},
},
SimilarityThreshold: 70, //Returns a value if the result of similarity is higher than this
};
We're ready to make a request to AWS Rekognition. We declare a new CompareFacesCommand
and pass the params we defined before
try {
const command = new CompareFacesCommand(params);
const result = await rekognitionClient.send(command); //We await for the result
return res.status(200).json({ //We send the result
message: "looks great!",
recognition_data: result,
});
} catch (error) {
return res.status(400).json({ //We have an error? Catch it and return it
ok: false,
error
});
}
The result of what Rekognition will be responding to should look like this:
{
"FaceMatches": [{
"Face": {
"BoundingBox": {...},
"Confidence": 99.98751068115234,
"Pose": {...},
"Quality": {...},
"Landmarks": [{...}]
},
"Similarity": 100.0
}
And that's practically it! I hope this mini-tutorial was helpful for you, I know it is not the big thing, but I bet you can save precious time by following (or copy-pasting) this guide. If you are having issues with this implementation, Here is the GitHub Repo of the entire (little) project. See ya next time!