LoginSignup
3
4

More than 5 years have passed since last update.

Amazon Rekognitionで画像ファイルのラベル検出(Python boto3で)

Posted at

概要

Amazon Rekognitionでは様々な画像認識機能が提供されます。
今回はLabel Detect、画像からのラベル検出をPythonから実行するスクリプトを紹介します。
ラベル検出では、例えば例えば海辺の写真なら海、岩、灯台、砂浜などのラベルが検出されます。
DetectLabels - Amazon Rekognition

前提条件

Rekognitionを実行できる権限としてAmazonRekognitionFullAccessなどを付けたIAMアカウント、もしくはロールを事前に設定しておきましょう。

スクリプト

Pythonとboto3を使った場合のスクリプト例です。
S3のURLパスを渡す方法と画像ファイルのバイト列を渡す方法があります。今回はバイト列を渡す方法でやってみました。

# -*- coding: utf-8 -*-
import boto3

#boto3のclient作成、rekognitionとリージョンを指定
client = boto3.client('rekognition','us-east-1')

# 画像ファイルを読み込んでバイト列を取得
with open('sample.png', 'rb') as source_image:
    source_bytes = source_image.read()

# rekognitionのdetect_labelsにバイト列を渡してラベル検出実行
response = client.detect_labels(
               Image={
                   'Bytes': source_bytes
               }
)

# 返ってきたresponseからラベル名(Name)と確度(Confidence)を整形して出力
for label in response['Labels']:
    print("{Name:30},{Confidence:.2f}%".format(**label))

処理結果

今回はレスポンスのJSONを整形したので以下のような結果が返ります。ラベルとその確度になります

Beacon                        ,96.46%
Coast                         ,76.84%
Nature                        ,76.84%
Ocean                         ,76.84%
Outdoors                      ,76.84%
Sea                           ,76.84%
Water                         ,76.84%
Architecture                  ,51.37%
Building                      ,51.37%
Lighthouse                    ,51.37%
Tower                         ,51.37%
Flora                         ,50.57%
Grass                         ,50.57%
Plant                         ,50.57%
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4