AWS
5-3. Rekognition 사용자 지정 레이블 분석
황수진
2022. 1. 26. 17:42
셋팅도 하구, dataset설정, label 지정, 모델 훈련까지 마쳤습니다
이제 학습시킨 모델을 이용해 이미지를 분석해봅시다 !
학습시킨 Rekognition custom label 프로젝트에 들어가 'Use model'을 클릭해줍니다.
클릭하게 되면 AWS CLI command를 이용하거나 Python을 사용할 수 있습니다.
이제 밑에 있는 start model, analyze image, stop model 코드를 이용해 이미지를 분석하면 끝입니다!
Start model
#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-custom-labels-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
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...')
def main():
project_arn='PROJECT_ARN'
model_arn='MODEL_ARN'
min_inference_units=1
version_name='VERSION_NAME'
start_model(project_arn, model_arn, version_name, min_inference_units)
if __name__ == "__main__":
main()
이 때, project_arn, model_arn, version_name은 본인의 arn과 version을 적어주면 됩니다
출력 결과입니다!
Analyze model
#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-custom-labels-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
import io
from PIL import Image, ImageDraw, ExifTags, ImageColor, ImageFont
def display_image(bucket,photo,response):
# Load image from S3 bucket
s3_connection = boto3.resource('s3')
s3_object = s3_connection.Object(bucket,photo)
s3_response = s3_object.get()
stream = io.BytesIO(s3_response['Body'].read())
image=Image.open(stream)
# Ready image to draw bounding boxes on it.
imgWidth, imgHeight = image.size
draw = ImageDraw.Draw(image)
# calculate and display bounding boxes for each detected custom label
print('Detected custom labels for ' + photo)
for customLabel in response['CustomLabels']:
print('Label ' + str(customLabel['Name']))
print('Confidence ' + str(customLabel['Confidence']))
if 'Geometry' in customLabel:
box = customLabel['Geometry']['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), customLabel['Name'], 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()
def show_custom_labels(model,bucket,photo, min_confidence):
client=boto3.client('rekognition')
#Call DetectCustomLabels
response = client.detect_custom_labels(Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
MinConfidence=min_confidence,
ProjectVersionArn=model)
# For object detection use case, uncomment below code to display image.
# display_image(bucket,photo,response)
return len(response['CustomLabels'])
def main():
bucket='MY_BUCKET'
photo='MY_IMAGE_KEY'
model='MODEL_ARN'
min_confidence=95
label_count=show_custom_labels(model,bucket,photo, min_confidence)
print("Custom labels detected: " + str(label_count))
if __name__ == "__main__":
main()
마찬가지로 본인의 bucket, photo, model로 수정해주면 됩니다!
이렇게 출력되면 성공!
stop model
#Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-custom-labels-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
import time
def stop_model(model_arn):
client=boto3.client('rekognition')
print('Stopping model:' + model_arn)
#Stop the model
try:
response=client.stop_project_version(ProjectVersionArn=model_arn)
status=response['Status']
print ('Status: ' + status)
except Exception as e:
print(e)
print('Done...')
def main():
model_arn='MODEL_ARN'
stop_model(model_arn)
if __name__ == "__main__":
main()
이렇게 모델이 스탑되면 성공입니다!