Skip to content

Instantly share code, notes, and snippets.

@jacobeturpin
Last active April 21, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacobeturpin/77d1f64a8205409a546dda9a9f363f74 to your computer and use it in GitHub Desktop.
Save jacobeturpin/77d1f64a8205409a546dda9a9f363f74 to your computer and use it in GitHub Desktop.
Example of using AWS Rekognition to identify and draw bounding boxes for faces
"""Use AWS Rekognition face detection to produce bounding boxes"""
import boto3
from PIL import Image, ImageDraw
IMG = 'example-img.jpg'
REGION = 'us-east-1'
def get_face_details(img_path):
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.detect_faces
rekognition = boto3.client("rekognition", REGION)
with open(img_path, "rb") as image_file:
encoded_img = image_file.read()
response = rekognition.detect_faces(
Image={
'Bytes': encoded_img
}
)
return response['FaceDetails']
def main():
face_details = get_face_details(IMG)
im = Image.open(IMG)
(width, height) = im.size
draw = ImageDraw.Draw(im)
for idx, face in enumerate(face_details):
print('Face Detected {} with confidence {:.4f}'.format(idx, face['Confidence']))
bbox = face['BoundingBox']
x1, y1 = (bbox['Left'] * width, bbox['Top'] * height)
x2, y2 = (x1 + bbox['Width'] * width, y1 + bbox['Height'] * height)
draw.rectangle(xy=[x1, y1, x2, y2], outline='red', width=3)
im.save('example-img-bbox.jpg', 'JPEG')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment