麦星 - arcturus technologies- 

テクノロジー関連情報と日常的な何かを発信しています

Rekognition でリアルタイム顔認識

こんにちは。@うしです。

以前、AWSのEC2とAmazon Rekognition を使用して
リアルタイム顔認識の仕組みを作ったので、
そのサンプルコードを記載します。

開発環境は以下になります

アクセスキーの取得(作成)

※Rekognitionを使用するには IAMから、 認証情報タブ  >  アクセスキーの作成で アクセスキーを取得(生成)して下さい。  
 
 
以下は、画像をアップロードする側の「index.html」 ファイルです。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
        <meta name="ROBOTS" content="NOODP, NOARCHIVE, INDEX, FOLLOW">
        <meta name="format-detection" content="telephone=no">     
        <title>顔認証テスト</title>
        <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script type="text/javascript">
        //<![CDATA[
            $(function()
            {
                $('#send').on( "click", function()
                {
                    $('#upfile').click();
                });

                $('#upfile').on( "change", function()
                {
                    if( this.files != null && this.files.length > 0 )  
                    {
                        var file = this.files[0];
                        var reader = new FileReader();

                        reader.readAsDataURL( file );

                        reader.onload = function() 
                        {
                            $('#image').val( reader.result );
                            $('form').submit();
                        }
                    }
                });
            });
        //]]>
        </script>
    </head>
    <body>
        <br />
        Rekognition Image オペレーションでは、.jpg または .png 形式のイメージを分析できます。
        <br />
        <br />
        <input type="file" name="upfile" id="upfile" accept="image/*" capture="user" style="display:none;"/>
        <input type="button" name="send" id="send" value=" 認 証 " />

        <form action="upload.php" method="post" >
            <input type="hidden" name="image" id="image" value="" />
        </form>
    </body>
</html>

以下は、アップロード画像を受信した受け側のPHPファイル「upload.php」です。

<?php

$image = isset( $_POST['image'] ) && ( $_POST['image'] ) ? $_POST['image'] :""; 

if( $image !="" )
{
    $image = explode(',', $image);
    $image = $image[ count($image)-1 ];
    $image = base64_decode($image);

    require('../aws.phar');


    $awsRekognition = new Aws\Rekognition\RekognitionClient(
    [
        'credentials' => array(
            'key'   => '{IAM作成時に取得したAccess key ID}',
            'secret'=> '{IAM作成時に取得したSecret access key}'
        ),
        'region'    => 'us-west-2',
        'version'   => 'latest'
    ]);

    $result = $awsRekognition->detectFaces(
    [
        'Attributes'=> ['ALL'],
        'Image'     => [
            'Bytes' => $image
        ]
    ]);
 
    $result = ( array ) $result;

    foreach( $result as $line ) 
    {
        $result = $line;
        break;
    }

    $result = json_encode( $result );

    header("Content-Type: application/json; charset=utf-8");
    print $result;
}
else
{
    print "no images";
}
?>

この2つのファイルをEC2の公開領域(同PATH)に設置します。
「index.html」にアクセスし、写真をアップロードすると
年齢、性別、人種、メガネや髭の有無、気分などを分析してJSONで返却してくれます。

S3に画像ファイルを設置し、アップロードされた写真との比較で、
誰か映っているか?まで探してくれるそうです。
また、以下URLによると写真に写っている人が複数人でも検出可能とのこと。

aws.amazon.com

※ちなみに、Rekognitionが使えるリージョンは限られてるっぽいのでご注意を!