第4回 Amazon Rekognition 動作確認(Python)


前回の内容はこちらから「第3回 Amazon Rekognition 動作確認(Python)


今回はイメージ内の顔の検出(DetectFaces)を行ってみます。

 

・Pythonサンプルソース。

# インストールしたPython用のライブラリ
import boto3
from matplotlib import pyplot as plt
from PIL import Image

def translationFunc(type):
    if type == 'HAPPY':
        return '幸せ'
    elif type == 'SAD':
        return '悲しい'
    elif type == 'ANGRY':
        return '怒り'
    elif type == 'SURPRISED':
        return '驚き'
    elif type == 'DISGUSTED':
        return '嫌悪'
    elif type == 'CALM':
        return '穏やか'
    elif type == 'CONFUSED':
        return '困惑'
    elif type == 'FEAR':
        return '恐れ'

# 画像ファイルのパス
filename = r"※画像ファイルのパスを指定"

# 画像ファイルのサイズを取得する
img = Image.open(filename)
img_width = img.size[0]
img_height = img.size[1]

rekognition=boto3.client('rekognition')

with open(filename, 'rb') as f:
    # DetectFacesの呼び出し
    res = rekognition.detect_faces(Image={'Bytes': f.read()},Attributes=['ALL'])

# ラベル表示用のフォント
font_dict = dict(family="serif",
    color="#ff0000",
    weight="bold",
    size=8)

for faceDetail in res["FaceDetails"]:
    # 画像に顔の枠を表示させる
    bb = faceDetail["BoundingBox"]
    rect = plt.Rectangle(
        (bb["Left"] * img_width, bb["Top"] * img_height),
        bb["Width"] * img_width,
        bb["Height"] * img_height,
        fill=False,
        edgecolor='red',
    )
    plt.gca().add_patch(rect)

    # 年齢取得
    label_name = str(faceDetail['AgeRange']['Low']) + '歳~' + str(faceDetail['AgeRange']['High']) + '歳'

    # 感情の取得
for emotions in faceDetail["Emotions"]:
    typeNm = translationFunc(emotions['Type'])
    confidenceNm = str(round(emotions["Confidence"], 2)) + "%"
    label_name = label_name + " " + typeNm + ":" +confidenceNm
    break

# 画像に年齢+感情を表示させる
plt.text(bb["Left"] * img_width, bb["Top"] * img_height
    , label_name
    , fontdict=font_dict, fontname="MS Gothic")

plt.axis("off")
plt.imshow(img)
# 結果画像ファイルを保存
plt.savefig("result.png")

 

実行すると

rekognition.detect_facesで返却されたJsonの値をもとに、読み込んだ画像に枠線とラベルを出力し結果画像に保存されます。

今回はAgeRange(年齢)、Emotions(感情)を結果画像に出力してみました。
{'FaceDetails': [
    {'BoundingBox': {'Width': 0.5237365365028381, 'Height': 0.5711398124694824, 'Left': 0.1613551378250122, 'Top': 0.1750694066286087
        }, 'AgeRange': {'Low': 15, 'High': 27
        }, 'Smile': {'Value': False, 'Confidence': 83.26225280761719
        }, 'Eyeglasses': {'Value': False, 'Confidence': 99.42730712890625
        }, 'Sunglasses': {'Value': False, 'Confidence': 99.72573852539062
        }, 'Gender': {'Value': 'Female', 'Confidence': 99.2392578125
        }, 'Beard': {'Value': False, 'Confidence': 98.81663513183594
        }, 'Mustache': {'Value': False, 'Confidence': 99.68753051757812
        }, 'EyesOpen': {'Value': True, 'Confidence': 97.44046020507812
        }, 'MouthOpen': {'Value': False, 'Confidence': 97.19811248779297
        }, 'Emotions': [
            {'Type': 'CALM', 'Confidence': 72.99432373046875 },
            {'Type': 'HAPPY', 'Confidence': 22.288368225097656 },
            {'Type': 'ANGRY', 'Confidence': 1.6257643699645996 },
            {'Type': 'SAD', 'Confidence': 1.382449984550476 },
            {'Type': 'DISGUSTED', 'Confidence': 0.7320917844772339 },
            {'Type': 'SURPRISED', 'Confidence': 0.3821593225002289 },
            {'Type': 'CONFUSED', 'Confidence': 0.2983729839324951 },
            {'Type': 'FEAR', 'Confidence': 0.296474426984787 }
        ], 'Landmarks': [
            {'Type': 'eyeLeft', 'X': 0.26009565591812134, 'Y': 0.42786064743995667 },
            {'Type': 'eyeRight', 'X': 0.4918273389339447, 'Y': 0.4259592890739441 

 

実行した結果がこちらになります。

  お問い合わせ  - お気軽にお問い合わせください - 

  • 株式会社 パブリックリレーションズ
  • 〒064-0807
  • 北海道札幌市中央区南7条西1丁目13番地 弘安ビル5階
メールでのお問い合わせはこちら

  • この記事をシェアする