物体抽出したい画像が集まったら、オリジナルの学習モデルをカスタムラベルで作成します。
(1) Custom Labelsのプロジェクトを作成
Amazon RekognitionからCustom Labels -> Use Custom Labels -> Get Started -> S3バケットの作成をしていきます。このS3バケットに画像を入れて学習をしていきます。
(2) 学習用データセットを作成
プロジェクトが作成されると下の図のように、順番に何をするかが示されます。最初はデータセットを作成していきます。
1のcreate datasetをクリックします。
いくつかの選択肢がありますが、今回は
「Start with a single dataset」:学習データ、テストデータには自動で分割
「Import images from S3 bucket」:S3にアップロードしたデータを利用
の2つを選んで実施します。
今回は imageフォルダの中の3つのフォルダに入っている画像30枚を利用します。Custom Labelで強制的に作られたS3バケットの中にimageフォルダをアップロードしておきます。
アップロードが終わると、下記の画面が見えます。右上にある「Copy S3 URI」でリンクをコピーします。
コピーしたら、もう一度Custom Labelsに戻ります。S3 URIをコピーし、「Automatically assign image-level labels to images based on the folder name」にチェックを入れます。これでフォルダ名がラベル名となります。
ここまでできたら、Create Datasetをクリックします。画像が取り込まれると、ラベルのついた画像があることがわかります。
注意:AWS Academyで上記を実行すると、Network エラーになるかもしれません。なった場合は、S3からの同期ではなく、自分のPCからアップロードを選択して、一つひとつやってみて下さい。
(3) 学習の実行
「3. Train model」でボタンを押し実行します。
trainが始まり、進行中だと表示されます。数時間、学習に時間がかかります。
表示が変わり、精度など確認できれば学習完了です。
作成した学習モデルを使っていきます。学習済みのプロジェクトから上のメニューで「Use Model」を選択します。下の API Code でPythonを選択すると、pythonコードが出てきます。
ソースコードには、Start Model、Analyze Image、Stop Modelがあります。Start、Stopはプロジェクトのボタンでもできます。Startは時間がかかります。Stopはすぐにできます。利用しないときはStopしましょう。ここではAnalyze Imageを見ていきます。PythonコードをSageMakerで実行していくので、SageMakerを開きます。
!pip install boto3
でライブラリをインストールしておきます。モデルをStartした後、以下を実行します。AWS Academyの場合はセッション情報も必要です。
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
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', | |
aws_access_key_id='xxxxxxxx', | |
aws_secret_access_key='xxxxxx', | |
region_name='xxxxxx' | |
) | |
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', | |
aws_access_key_id='xxxxxxxxxxxx', | |
aws_secret_access_key='xxxxxxxxx', | |
region_name='xxxxxxxxxxxxxxxx' | |
) | |
#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='mzn-publicproperty' | |
photo='img/カーブミラー/49685365707_9c29a8c40a_z.jpg' | |
model='arn:aws:rekognition............' | |
min_confidence=95 | |
label_count=show_custom_labels(model,bucket,photo, min_confidence) | |
print("Custom labels detected: " + str(label_count)) | |
if __name__ == "__main__": | |
main() |
図のように検出ができればOKです。
0 件のコメント:
コメントを投稿