SageMaker の物体検出によるオブジェクトカウント

SageMaker の物体検出によるオブジェクトカウント

Ground Truth で画像にラベルを付け、SageMaker の物体検出モデルを学習し、推論結果からオブジェクトを数えます。

Takahiro Iwasa
10 min read

Ground Truth による画像のラベリングから、物体検出モデルの学習・デプロイ、推論までの流れを説明します。

ℹ️ Note

この記事内の画像は説明用のものであり、特定の顧客プロジェクトとは関係ありません。

この例では、学習済みモデルのテストに SageMaker 推論エンドポイントを使用します。

Ground Truth によるラベリング

ラベリングワークフォースの作成

ラベリング用のプライベートワークフォースを作成します。チームメンバーは Amazon Cognito または OIDC ID プロバイダーで認証できます。

ワークフォースを作成すると、ラベリングポータルの URL を含む招待メールが各ワーカーへ送信されます。

ラベリングポータルの URL は、SageMaker コンソールの Private workforce summary > Labeling portal sign-in URL からも取得できます。

ワーカーは招待メールの手順に従ってサインアップし、ラベリングポータルにアクセスする必要があります。

招待メールの例は以下のとおりです。

Hi,
You are invited by [email protected] from <COMPANY> to work on a labeling project.
Click on the link below to log into your labeling project.
"https://<LABELING_PORTAL_URL>"
You will need the following username and temporary password provided below to login for the first time.
User name: <USER_NAME>
Temporary password: <PASSWORD>
Once you log in with your temporary password, you will be required to create a new password for your account.
After creating a new password, you can log into your private team to access your labeling project.
If you have any questions, please contact us at [email protected].

URL にアクセスし、招待メールに記載されたユーザー名と一時パスワードを入力します。

その後、一時パスワードを新しいパスワードに変更するよう求められます。

サインインすると、ラベリングポータルのホーム画面に割り当て済みのジョブが表示されます。

ラベリングジョブの作成

SageMaker コンソールへ戻り、ラベリングジョブを作成します。必要な項目を入力し、Complete data setup をクリックします。

💡 Tip

作成後のラベリングジョブは削除できません。uuidgen | tr "[:upper:]" "[:lower:]" などで生成した一意な名前を使用してください。

複雑なラベリングタスクでは、Task timeout に長めの時間を指定します。

ラベリングの開始

ラベリングポータルにサインインし、新しいジョブを開いて Start working をクリックします。

ℹ️ Note

ラベリングジョブが一覧に表示されるまで、しばらく時間がかかることがあります。

ジョブの指示に従ってバウンディングボックスを描画し、ラベルを割り当てます。以下は作業例です。

すべてのワーカーがタスクを完了したら、ラベリングジョブを停止します。

ラベリング出力の確認

ラベリングジョブが停止すると、Ground Truth が指定した S3 バケットへ結果を出力します。この物体検出タスクでは、manifests/output/output.manifest を学習データとして使用します。出力構成は公式ドキュメントを参照してください。

Terminal window
annotation-tool/
annotations/
consolidated-annotation/
worker-response/
manifests/
intermediate/
output/
output.manifest
temp/

Ground Truth はラベリング結果を Augmented Manifest 形式で出力します。物体検出用のフィールドは公式ドキュメントを参照してください。

SageMaker による学習

ラベリングが完了したら、SageMaker の学習ジョブを以下のように設定します。

  • Job settings
  • Job name: 一意な値を使用します(例: uuidgen | tr "[:upper:]" "[:lower:]")。
  • Algorithm source: SageMaker built-in algorithm
  • Choose an algorithm:
  • Algorithm: Vision - Object Detection (MXNet)
  • Input mode: Pipe
  • Resource configuration
  • Instance typeml.p2.xlarge のような GPU インスタンスを使用します。
  • SageMaker の物体検出アルゴリズムは GPU インスタンスで学習します。
  • Hyperparameters
  • num_classes:オブジェクトクラスの数を設定します(この例では 1)。
  • num_training_samples: マニフェストファイルの行数と同じ値にします。
  • Input data configuration
  • Training channel
  • Channel name: train
  • Input mode: Pipe
  • Content type: application/x-recordio
  • Record wrapper: RecordIO
  • Data source: S3 (Augmented Manifest File)
  • Attribute namessource-ref やバウンディングボックスのデータキーなどを指定します。
  • S3 location:学習データのマニフェストファイルの S3 URI を指定します。
  • Validation channel
  • Channel name: validation
  • Output data configuration
  • S3 location:モデルアーティファクトを保存する S3 URI を指定します。

Augmented Manifest 形式を使うと、RecordIO ファイルを別途生成せずに、Pipe 入力モードと RecordIO ラッパーを使用できます。詳細は公式ドキュメントを参照してください。

推論

学習ジョブからモデルを作成する

完了した学習ジョブからモデルを作成するには、SageMaker コンソールで Create model をクリックします。

モデルのデプロイ

モデルを作成したら、Create endpoint をクリックしてデプロイします。推論頻度が低く、リソース制限内に収まる場合は、サーバーレスエンドポイントも選択できます。

リクエストの送信

エンドポイントの詳細画面で SageMaker Runtime エンドポイント を確認します。テストでは、AWS SDK または Postman などの SigV4 対応クライアントから呼び出します。

🔥 Caution

SageMaker のリアルタイム推論エンドポイントは本番環境でも利用できますが、AWS 認証が必要です。信頼できないクライアントに AWS 認証情報を持たせず、必要に応じて認証済みのアプリケーションや API をエンドポイントの前段に配置してください。以下の Postman からの直接呼び出しはテスト用です。

例:Postman の設定

AWS Signature Version 4 認証を以下の値で設定します。

  • AccessKey
  • SecretKey
  • Session Token:長期的な認証情報ではなく、一時的な認証情報を使用します。
  • AWS Region:SageMaker エンドポイントのリージョン
  • Service Namesagemaker

リクエストに Accept: application/json と、モデルが期待する画像の Content-Type(例:Content-Type: application/x-image)を設定します。

画像をバイナリのリクエストボディとして送信します。

例:AWS SDK(boto3)の使用

以下の例では、boto3 の invoke_endpoint でエンドポイントを呼び出します。

import json
import boto3
# Initialize SageMaker runtime client
runtime = boto3.client('sagemaker-runtime')
# Define endpoint and input details
endpoint_name = '<YOUR_ENDPOINT_NAME>'
content_type = 'application/x-image'
payload = None
# Read the image file in binary mode
with open('/path/to/image.jpg', 'rb') as f:
payload = f.read()
# Invoke the endpoint
response = runtime.invoke_endpoint(
EndpointName=endpoint_name,
ContentType=content_type,
Body=payload
)
# Parse and display the response
body = response['Body'].read()
predictions = json.loads(body.decode())
print(json.dumps(predictions, indent=2))
# Save the response to a file
with open('./response.json', 'w') as f:
json.dump(predictions, f, indent=2)

レスポンスの確認

JSON レスポンスには、検出結果ごとに以下の値が含まれます。

  • クラスラベル ID
  • 信頼度スコア
  • バウンディングボックスの座標
ℹ️ Note

バウンディングボックスの座標は、実際の画像サイズに対する相対値です。詳細は公式ドキュメントを参照してください。

{
"prediction": [
[
0.0,
0.9953756332397461,
0.3821756839752197,
0.007661208510398865,
0.525381863117218,
0.19436971843242645
],
[
0.0,
0.9928023219108582,
0.3435703217983246,
0.23781903088092804,
0.5533013343811035,
0.6385164260864258
],
[
0.0,
0.9911478757858276,
0.15510153770446777,
...
0.9990172982215881
]
]
}

レスポンスの可視化

推論結果は、Jupyter Notebookmatplotlib で可視化できます。

以下の Python スクリプトで、入力画像にバウンディングボックスとカウント番号を重ねます。

import json
import matplotlib.patches as patches
import matplotlib.pyplot as plt
from PIL import Image
# Configure plot
plt.figure()
axes = plt.axes()
# Read an image
im = Image.open('/path/to/image.jpg')
# Display the image
plt.imshow(im)
# Read SageMaker inference predictions
with open('response.json') as f:
predictions = json.loads(f.read())['prediction']
# Set initial count
count = 0
# Create rectangles
for prediction in predictions:
score = prediction[1]
if score < 0.2:
continue
# Count up
count += 1
x = prediction[2] * im.width
y = prediction[3] * im.height
width = prediction[4] * im.width - x
height = prediction[5] * im.height - y
rect = patches.Rectangle((x, y), width, height, linewidth=1, edgecolor='r', facecolor='none')
axes.annotate(count, (x + width / 2, y + height / 2), color='yellow', weight='bold', fontsize=18, ha='center', va='center')
axes.add_patch(rect)
# Display the rectangles
plt.show()

このスクリプトは、信頼度スコアで検出結果を絞り込み、正規化された座標をピクセルへ変換して、バウンディングボックスと連番を描画します。

まとめ

Ground Truth のラベルと SageMaker の組み込み物体検出アルゴリズムから、matplotlib で絞り込み、カウント、可視化できる正規化済みバウンディングボックスが得られます。

可視化スクリプトの score < 0.2 フィルターが、カウントに含める検出結果を決めます。この信頼度しきい値は、1 枚のテスト画像ではなく、検証データを使って調整してください。

カウント精度は Ground Truth のアノテーション品質にも左右されます。特に、重なったオブジェクトや一部だけ見えるオブジェクトについて、ラベリング基準と検証結果を確認してから大規模に利用してください。

About the author

Takahiro Iwasa

Takahiro Iwasa

Software Developer

This blog shares technical notes from hands-on projects—architecture, implementation, and AWS service integrations.