in dags/processing/processing.py [0:0]
def draw_bounding_box(bucket, json_key):
"""
Given a Rekognition json file all detected bounding boxes will be written into the related image
:param bucket:
:param key:
:return:
"""
import boto3
import json
import io
from PIL import Image, ImageDraw
s3 = boto3.resource("s3")
# load json from S3
json_object = s3.Object(bucket, json_key)
json_content = json.loads(json_object.get()['Body'].read().decode('utf-8'))
# load matching image key
png_key = json_key.replace(".json", ".png")
stream = io.BytesIO(s3.Object(bucket, png_key).get()['Body'].read())
image = Image.open(stream)
imgWidth, imgHeight = image.size
draw = ImageDraw.Draw(image)
for item in json_content:
for inst in item["Instances"]:
box = inst['BoundingBox']
left = imgWidth * box['Left']
top = imgHeight * box['Top']
width = imgWidth * box['Width']
height = imgHeight * box['Height']
points = (
(left, top),
(left + width, top),
(left + width, top + height),
(left, top + height),
(left, top)
)
draw.line(points, fill='#00d400', width=2)
in_mem_image = io.BytesIO()
image.save(in_mem_image, format=image.format)
in_mem_image.seek(0)
save_to_s3(in_mem_image, bucket, png_key)