Creating a Lambda function to perform image recognition on AWS
Analyzing images with an AWS Lambda function - Rekognition
Creating a Lambda function to perform image recognition on AWS is a bit more involved than creating a basic function, but it is still relatively straightforward. Here is a step-by-step tutorial on how to create a Lambda function to do image recognition using the AWS Management Console and the AWS Rekognition service.
- Sign in to the AWS Management Console and navigate to the Lambda service.
- Click on the "Create function" button to start the process of creating a new function.
- In the "Create function" page, choose "Author from scratch"
- Enter a name for your function and choose a runtime. For image recognition, you can use a runtime that supports the programming language you are comfortable with, such as Node.js, Java, C#, Go, or Python.
- In the "Permissions" section, choose "Create a new role with basic Lambda permissions" and click on the "Create function" button.
- Now you should be taken to the function editor. In this page, you will write your function code.
- In the "Function code" section, you can provide your code by either writing it in the inline code editor or uploading a .zip file containing your function code.
- Here's an example of Node.js code that will take an image as a base64 encoded string, call the AWS Rekognition service to detect labels in the image, and return the labels in the response:
const AWS = require('aws-sdk');
const rekognition = new AWS.Rekognition({apiVersion : '2016-06-27'});
exports.handler = (event, context, callback) = > {
const image = event.image;
const params = {
Image : {
Bytes : new Buffer.from(image, 'base64'),
},
MaxLabels : 10,
MinConfidence : 70,
};
rekognition.detectLabels(
params, (err, data) = > {
if (err) {
callback(err);
} else {
callback(null, data.Labels);
}
});
};
- Once your code is uploaded, click on the "Save" button.
- Next, you need to configure the AWS Rekognition service to allow your Lambda function to access it. To do this, navigate to the IAM service in the AWS Management Console.
- In IAM, create a new role that has permissions to access the Rekognition service. You can use an existing role if you have one.
- Attach the newly created role to your Lambda function by editing the function and updating the role in the "Designer" section.
- Test your function by invoking it with a sample image encoded in base64, you can use an event test to do so.
- Once your function is working as expected, you can then create a trigger for your function like an S3 bucket where users can upload their images and then your function can process those images.
After this, your function will be ready to perform image recognition on images that are uploaded to the configured trigger. You can also monitor the function's execution and performance using the AWS Lambda monitoring and logging features, and also use Rekognition's monitor feature to keep an eye on your usage and costs.