Created
June 8, 2017 09:16
-
-
Save softberries/226e87db44a3051f72d6ab2ae0c7ed5a to your computer and use it in GitHub Desktop.
Lambda funtion for comparing photos and publishing back to IoT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import print_function | |
import boto3 | |
from decimal import Decimal | |
import json | |
import urllib | |
print('Loading function') | |
rekognition = boto3.client('rekognition') | |
iot = boto3.client('iot-data') | |
# --------------- Helper Functions to call Rekognition APIs ------------------ | |
def compare_faces(bucket, key, key_target, threshold=80): | |
response = rekognition.compare_faces( | |
SourceImage={ | |
"S3Object": { | |
"Bucket": bucket, | |
"Name": key, | |
} | |
}, | |
TargetImage={ | |
"S3Object": { | |
"Bucket": bucket, | |
"Name": key_target, | |
} | |
}, | |
SimilarityThreshold=threshold, | |
) | |
return response['SourceImageFace'], response['FaceMatches'] | |
# --------------- Main handler ------------------ | |
def lambda_handler(event, context): | |
print("Received event: " + json.dumps(event, indent=2)) | |
bucket = event['Records'][0]['s3']['bucket']['name'] | |
key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key'].encode('utf8')) | |
key_target = "target/" + key | |
try: | |
response = compare_faces(bucket, key, key_target) | |
print(response) | |
mypayload = json.dumps(response) | |
iotResponse = iot.publish( | |
topic="rekognition/result", | |
qos=1, | |
payload=mypayload) | |
print(iotResponse) | |
return iotResponse | |
except Exception as e: | |
print(e) | |
print("Error processing object {} from bucket {}. ".format(key, bucket) + | |
"Make sure your object and bucket exist and your bucket is in the same region as this function.") | |
raise e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment