LoginSignup
0
1

More than 1 year has passed since last update.

EC2+Flask+AWS Rekognitionで画像処理を行う

Last updated at Posted at 2022-07-24

画像に映っている人物の年齢と人数を取得する

AWS Rekognitionとは

  • AIを活用した画像認識サービス
  • APIのように簡単に利用可能
  • 画像から様々な解析が可能

本記事では以下の方法については省略します

  • ec2インスタンスの起動
  • nginx+uwsgi+flaskでのWEBサーバの構築

IAMロールを作成する

  • IAMのダッシュボードから「ロール」を選択
  • 「ロールを作成」を選択
  • 以下の項目を選択して「次へ」を選択
    • 信頼されたエンティティタイプ「AWSのサービス」
    • 一般的なユースケース「EC2」
  • 許可ポリシーで「AmazonRekognitionFullAccess」と検索しチェックを付けて「次へ」を選択
  • 任意のロール名を付けて「ロールを作成」を選択

EC2インスタンスにロールをアタッチする

  • EC2ダッシュボードから「インスタンス」を選択
  • AWS Rekognitionを使いたいインスタンスにチェックを付ける
  • アクションのセキュリティから「IAMロールを変更」を選択
  • 作成したIAMロールを選択する

flaskからAWSRekognitionに問い合わせる

  • EC2上でboto3をインストールする
pip3 install boto3
  • 年齢と人数情報を取得するプログラム
import os
import boto3
import json
from flask import Flask, request, Response, render_template

app = Flask(__name__)
client = boto3.client('rekognition', 'ap-northeast-1')

@app.route("/analysis")
def analysis():
    age = 0
    people = 0
    # 年齢取得
    img = open("./images/img1.jpg", 'rb')   #解析したい画像のパスを指定
    response = client.detect_faces(
        Image={
            'Bytes': img.read()
        },
        Attributes=[
            'ALL'
        ]
    )
    if 'FaceDetails' in response:
        FaceDetails = response['FaceDetails']
        if not FaceDetails:
            pass
        else:
            age = int(FaceDetails[0]['AgeRange']['Low']) 
            age2 = age + int(FaceDetails[0]['AgeRange']['High'])
            age = age2 // 2 #解析結果の平均を取得

    # 人数取得
    img = open("./images/img1.jpg", 'rb')
    response = client.detect_labels(
        Image={
            'Bytes': img.read()
            }
        )
    for label in response['Labels']:
        if label['Name'] == 'Person':
            people = str(len(label['Instances']))
            return '人数:' + people + ' 平均年齢:' + str(age)

if __name__ == "__main__":
    app.run()

引用

https://tsukasa-blog.com/programming/amazon-rekognition-method/
https://tekuzo.org/awsai-countperson/
https://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/rekognition-dg.pdf

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