0
0

More than 3 years have passed since last update.

AWS:Rekognitionとpythonで顔の分析を行ってみる

Posted at

AWSのサービスを色々使って、理解を深める。

AWSの勉強をしていたら予想以上に色々できることに驚いた。
AWSを自由自在に使えたら便利なのでは?と思い付き、やってみた。

参考

①_Qiita記事(コードの内容)
https://qiita.com/banquet_kuma/items/560787299b83fb924ff7
②_AWS_Rekognition公式入門ガイド
https://aws.amazon.com/jp/rekognition/resources/
③_AWS_Rekognition detect_facesオペレーション
https://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/faces-detect-images.html

内容

1. IAMユーザーの作成

2. AWS CLI と AWS SDK をインストールして設定
  ※基本は参考③を見ながら実行しました。
  ※アクセスキーのデータは参考①のpythonのライブラリ「configparser」を使用

3. コードの記述及び実行
前半は参考①を、後半は参考③を参照し、つなぎ合わせたイメージ。

コード全体
import boto3
import configparser
from PIL import Image

#参考①を参照して記述
ini = configparser.ConfigParser()
ini.read("Rekognition/config.ini","utf-8")

filename = "読み取りたい画像"
img = Image.open(filename)
img_width = img.size[0]
img_height = img.size[1]

bucket = "AWS S3のバケット名"
region = "AWS のregion名"

#iniデータからaws_access_key_idとaws_secret_keyを参照
access_key = ini["AWS_KEY"]["aws_access_key_id"]
secret_key = ini["AWS_KEY"]["aws_secret_key"]
session = boto3.Session(aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=region)

s3 = session.client("s3")
rekognition = session.client("rekognition")

with open(filename, "rb") as f:
    # 読み込んだファイルをS3サービスにアップロード
    s3.put_object(Bucket=bucket, Key=filename, Body=f)

#参考③を参照して記述
response = rekognition.detect_faces(Image={"S3Object":{"Bucket":bucket,"Name":filename}},Attributes=["ALL"])


print('Detected faces for ' + filename)    
for faceDetail in response['FaceDetails']:
    print('The detected face is between ' + str(faceDetail['AgeRange']['Low']) 
            + ' and ' + str(faceDetail['AgeRange']['High']) + ' years old')


    #print('Here are the other attributes:')
    #print(json.dumps(faceDetail, indent=4, sort_keys=True))
    # Access predictions for individual face details and print them
    print("Gender: " + str(faceDetail['Gender']))
    print("Smile: " + str(faceDetail['Smile']))
    print("Eyeglasses: " + str(faceDetail['Eyeglasses']))
    print("Emotions: " + str(faceDetail['Emotions'][0]))

実行結果

下の画像で実行。
漫画絵でも判別してくれる。
nigaoe_edogawa_ranpo.png
screen 2.png
年齢:28〜44歳
笑っているか:不明
メガネ:あり
感情:落ち着いている

使用画像:いらすとや
https://www.irasutoya.com/

所感

詳細は理解していませんが、まずは動かせました、ヨシ!!
真剣に学びつつ、遊びつつ、AWSの理解を深めていこうと思います。
AWSに感動中。

0
0
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
0
0