Skip to content

Instantly share code, notes, and snippets.

@jorke
Last active May 3, 2021 03:54
Show Gist options
  • Save jorke/1fbb6f41cc0d41d0a3c4859eb604882d to your computer and use it in GitHub Desktop.
Save jorke/1fbb6f41cc0d41d0a3c4859eb604882d to your computer and use it in GitHub Desktop.
rekognition-testing.ipnyb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "77c5fd12",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"# Using default Rekognition model\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "73b0e581",
"metadata": {},
"outputs": [],
"source": [
"import io\n",
"import boto3\n",
"from PIL import Image, ImageDraw, ExifTags, ImageColor, ImageFont\n",
"r = boto3.client(\"rekognition\")\n",
"\n",
"# ignore anything below this confidence level\n",
"confidence = 80\n",
"\n",
"#filepath\n",
"testimage = \"testing/glass81.jpg\"\n",
"\n",
"image = Image.open(testimage)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0de15080",
"metadata": {},
"outputs": [],
"source": [
"#%matplotlib inline\n",
"def display_bbox(image, labels):\n",
" # Ready image to draw bounding boxes on it.\n",
" imgWidth, imgHeight = image.size\n",
" draw = ImageDraw.Draw(image)\n",
"\n",
" for label in labels:\n",
" print('Label ' + str(label['Name']))\n",
" print('Confidence ' + str(label['Confidence']))\n",
" if 'Instances' in label:\n",
" for instance in label['Instances']:\n",
" box = instance['BoundingBox']\n",
" left = imgWidth * box['Left']\n",
" top = imgHeight * box['Top']\n",
" width = imgWidth * box['Width']\n",
" height = imgHeight * box['Height']\n",
"\n",
" fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 50)\n",
" draw.text((left,top), f\"{label['Name']} - {label['Confidence']}\", fill='#00d400', font=fnt)\n",
"\n",
" print('Left: ' + '{0:.0f}'.format(left))\n",
" print('Top: ' + '{0:.0f}'.format(top))\n",
" print('Label Width: ' + \"{0:.0f}\".format(width))\n",
" print('Label Height: ' + \"{0:.0f}\".format(height))\n",
"\n",
" points = (\n",
" (left,top),\n",
" (left + width, top),\n",
" (left + width, top + height),\n",
" (left , top + height),\n",
" (left, top))\n",
" draw.line(points, fill='#00d400', width=5)\n",
"\n",
" #image.show()\n",
" return image"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "357a35cd",
"metadata": {},
"outputs": [],
"source": [
"%time\n",
"fd = open(testimage, 'rb')\n",
"img = fd.read()\n",
"fd.close()\n",
"\n",
"response = r.detect_labels(Image={'Bytes': img})\n",
"\n",
"labels = [{ x['Name'],x['Confidence']} for i,x in enumerate(response['Labels']) if x['Confidence'] > confidence]\n",
"\n",
"display_bbox(image,response['Labels'])"
]
},
{
"cell_type": "markdown",
"id": "8dfb2f76",
"metadata": {},
"source": [
"# Using custom labelling Rekognition\n",
"\n",
"https://ap-southeast-2.console.aws.amazon.com/rekognition/custom-labels#/datasets/rubbish-photos\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "70d81f99",
"metadata": {},
"outputs": [],
"source": [
"# start model\n",
"\n",
"def start_model(project_arn, model_arn, version_name, min_inference_units):\n",
"\n",
" client=boto3.client('rekognition')\n",
"\n",
" try:\n",
" # Start the model\n",
" print('Starting model: ' + model_arn)\n",
" response=client.start_project_version(ProjectVersionArn=model_arn, MinInferenceUnits=min_inference_units)\n",
" # Wait for the model to be in the running state\n",
" project_version_running_waiter = client.get_waiter('project_version_running')\n",
" project_version_running_waiter.wait(ProjectArn=project_arn, VersionNames=[version_name])\n",
"\n",
" #Get the running status\n",
" describe_response=client.describe_project_versions(ProjectArn=project_arn,\n",
" VersionNames=[version_name])\n",
" for model in describe_response['ProjectVersionDescriptions']:\n",
" print(\"Status: \" + model['Status'])\n",
" print(\"Message: \" + model['StatusMessage']) \n",
" except Exception as e:\n",
" print(e)\n",
" \n",
" print('Done...')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a3737206",
"metadata": {},
"outputs": [],
"source": [
"\n",
"project_arn='arn:aws:rekognition:xxxxx'\n",
"model_arn='arn:aws:rekognition:xxxx'\n",
"min_inference_units=1 \n",
"version_name='xxxx'\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ddd7b72",
"metadata": {},
"outputs": [],
"source": [
"#start the inference endpoint \n",
"start_model(project_arn, model_arn, version_name, min_inference_units)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1053a86c",
"metadata": {},
"outputs": [],
"source": [
"# call with custom labels\n",
"custom_labels = r.detect_custom_labels(Image={'Bytes': img},ProjectVersionArn=model_arn)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e5c7e3ba",
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"\n",
"[{ x['Name'],x['Confidence']} for i,x in enumerate(custom_labels['CustomLabels']) if x['Confidence']]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "33e3b37a",
"metadata": {},
"outputs": [],
"source": [
"display_bbox(image,custom_labels['CustomLabels'])"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.4"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
import io
import boto3
from PIL import Image, ImageDraw, ExifTags, ImageColor, ImageFont
r = boto3.client("rekognition")
# ignore anything below this confidence level
confidence = 80
#filepath
testimage = "testing/glass81.jpg"
image = Image.open(testimage)
def display_bbox(image, labels):
# Ready image to draw bounding boxes on it.
imgWidth, imgHeight = image.size
draw = ImageDraw.Draw(image)
for label in labels:
print('Label ' + str(label['Name']))
print('Confidence ' + str(label['Confidence']))
if 'Instances' in label:
for instance in label['Instances']:
box = instance['BoundingBox']
left = imgWidth * box['Left']
top = imgHeight * box['Top']
width = imgWidth * box['Width']
height = imgHeight * box['Height']
fnt = ImageFont.truetype('/Library/Fonts/Arial.ttf', 50)
draw.text((left,top), f"{label['Name']} - {label['Confidence']}", fill='#00d400', font=fnt)
print('Left: ' + '{0:.0f}'.format(left))
print('Top: ' + '{0:.0f}'.format(top))
print('Label Width: ' + "{0:.0f}".format(width))
print('Label 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)
#image.show()
return image
%time
fd = open(testimage, 'rb')
img = fd.read()
fd.close()
response = r.detect_labels(Image={'Bytes': img})
labels = [{ x['Name'],x['Confidence']} for i,x in enumerate(response['Labels']) if x['Confidence'] > confidence]
display_bbox(image,response['Labels'])
# start model
def start_model(project_arn, model_arn, version_name, min_inference_units):
client=boto3.client('rekognition')
try:
# Start the model
print('Starting model: ' + model_arn)
response=client.start_project_version(ProjectVersionArn=model_arn, MinInferenceUnits=min_inference_units)
# Wait for the model to be in the running state
project_version_running_waiter = client.get_waiter('project_version_running')
project_version_running_waiter.wait(ProjectArn=project_arn, VersionNames=[version_name])
#Get the running status
describe_response=client.describe_project_versions(ProjectArn=project_arn,
VersionNames=[version_name])
for model in describe_response['ProjectVersionDescriptions']:
print("Status: " + model['Status'])
print("Message: " + model['StatusMessage'])
except Exception as e:
print(e)
print('Done...')
project_arn='arn:aws:rekognition:xxxxx'
model_arn='arn:aws:rekognition:xxxx'
min_inference_units=1
version_name='xxxx'
start_model(project_arn, model_arn, version_name, min_inference_units)
custom_labels = r.detect_custom_labels(Image={'Bytes': img},ProjectVersionArn=model_arn)
[{ x['Name'],x['Confidence']} for i,x in enumerate(custom_labels['CustomLabels']) if x['Confidence']]
display_bbox(image,custom_labels['CustomLabels'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment