AWS Code Sample

The AWS Documentation website is getting a new look!
Try it now and let us know what you think. Switch to the new look >>

You can return to the original look by selecting English in the language selector above. demonstrates how to draw bounding boxes around faces in images. The image file is local.

# Copyright 2010-2019, Inc. or its affiliates. All Rights Reserved. # # This file is licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. A copy of the # License is located at # # # # This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS # OF ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import boto3 import io from PIL import Image, ImageDraw, ExifTags, ImageColor if __name__ == "__main__": # Change photo to the path and filename of your image. photo = 'photo' # Open image and get image data from stream. image =,'rb')) stream = io.BytesIO(), format=image.format) image_binary = stream.getvalue() client = boto3.client('rekognition') response = client.detect_faces(Image={'Bytes': image_binary}, Attributes=['ALL']) draw = ImageDraw.Draw(image) # Calculate and display a bounding box around each detected face print('Detected faces for ' + photo) for faceDetail in response['FaceDetails']: print('The detected face is between ' + str(faceDetail['AgeRange']['Low']) + ' and ' + str(faceDetail['AgeRange']['High']) + ' years old') box = faceDetail['BoundingBox'] imgWidth, imgHeight = image.size left = imgWidth * box['Left'] top = imgHeight * box['Top'] width = imgWidth * box['Width'] height = imgHeight * box['Height'] print('Left: ' + '{0:.0f}'.format(left)) print('Top: ' + '{0:.0f}'.format(top)) print('Face Width: ' + "{0:.0f}".format(width)) print('Face Height: ' + "{0:.0f}".format(height)) points = ( (left,top), (left + width, top), (left + width, top + height), (left , top + height), (left, top) ) draw.line(points, fill='#00d400', width=5) # Alternatively can draw rectangle. However you can't set line width. # draw.rectangle([left,top, left + (width * box['Width']), top +(height * box['Height'])], outline='yellow')

Sample Details

Service: rekognition

Last tested: 2019-01-3

Author: reesch (AWS)

Type: snippet

On this page: