Skip to content

Instantly share code, notes, and snippets.

@kacerekz
Created May 13, 2022 15:16
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 kacerekz/6b86f5d8af0a7f0dbf6b7fa3d083edf4 to your computer and use it in GitHub Desktop.
Save kacerekz/6b86f5d8af0a7f0dbf6b7fa3d083edf4 to your computer and use it in GitHub Desktop.
Using AWS to detect Red Bull cans, for reasons. It's quite stupid.
# You will need AWS creds for this
import boto3
import io
from PIL import Image, ImageDraw, ImageFont
import sys
def detect_redbull(im_bytes, target_height_px, target_center_px):
# Get Rekognition client
rek_client = boto3.client('rekognition', region_name='us-west-2')
# Upload image to AWS
response = rek_client.detect_labels(Image={'Bytes': im_bytes})
# Get default font to draw texts
image = Image.open(io.BytesIO(im_bytes))
font = ImageFont.truetype('arial.ttf', size=80)
draw = ImageDraw.Draw(image)
# Get all labels
w, h = image.size
for label in response['Labels']:
name = label['Name']
print(name)
names = ["Beer", "Can", "Tin", "Shaker", "Bottle", "Cup", "Coffee Cup", "Beverage", "Drink"]
if name in names:
# Draw all instancex box, if any
for instance in label['Instances']:
bbox = instance['BoundingBox']
x0 = int(bbox['Left'] * w)
y0 = int(bbox['Top'] * h)
x1 = x0 + int(bbox['Width'] * w)
y1 = y0 + int(bbox['Height'] * h)
#draw.rectangle([x0, y0, x1, y1], outline=(255, 0, 0), width=10)
#draw.text((x0, y1), name, font=font, fill=(255, 0, 0))
#image.save('labels.jpg')
heightdiff = bbox['Height'] * h - target_height_px
centerdiff = (x0 + (x1 - x0) * 0.5) - (w * 0.5)
# Height diff so you can regulate distance
# Center diff so you can regulate turn amount
return (heightdiff, centerdiff)
return (float("nan"), float("nan"))
file_name = sys.argv[1]
with open(file_name, 'rb') as im:
# Read image bytes
im_bytes = im.read()
coords = detect_redbull(im_bytes, 100, 0)
print(coords)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment