

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# イメージの操作
<a name="images"></a>

このセクションには、Amazon Rekognition Image でイメージに対して実行できる分析のタイプの説明が含まれます。
+ [オブジェクトとシーンの検出](labels.md)
+ [顔の検出と比較](faces.md)
+ [コレクション内での顔の検索](collections.md)
+ [有名人の認識](celebrities.md)
+ [イメージモデレーション](moderation.md)
+ [イメージ内のテキスト検出](text-detection.md)

これらは非ストレージ型 API オペレーションにより実行され、オペレーションで検出された情報は Amazon Rekognition Image によって保持されません。非ストレージ API オペレーションでは入力イメージのバイトは保持されません。詳細については、「[非ストレージ型およびストレージ型の API オペレーションについて](how-it-works-storage-non-storage.md)」を参照してください。

Amazon Rekognition Image では、コレクションに顔のメタデータを保存して後で取得することもできます。詳細については、「[コレクション内での顔の検索](collections.md)」を参照してください。

このセクションでは、Amazon Rekognition Image　 API オペレーションを使用して、Amazon S3 バケットに保存されたイメージと、ローカルファイルシステムからロードされたイメージのバイトを分析します。このセクションでは、.jpg イメージからイメージの向きの情報を取得する方法についても説明します。

 Rekognition は、RGB チャネルのみを使用して推論を実行します。 は、ディスプレイを使用して比較を視覚的に (手動で) 検査する前に、アルファチャネルを削除 AWS することをお勧めします。

**Topics**
+ [イメージの仕様](images-information.md)
+ [Amazon S3 バケットに保存されたイメージの分析](images-s3.md)
+ [ローカルファイルシステムからロードしたイメージの分析](images-bytes.md)
+ [境界ボックスの表示](images-displaying-bounding-boxes.md)
+ [イメージの向きおよび境界ボックス座標の取得](images-orientation.md)

# イメージの仕様
<a name="images-information"></a>

Amazon Rekognition Image オペレーションでは、.jpg 形式または .png 形式の入力イメージを分析します。

イメージバイトを呼び出しの一部として Amazon Rekognition Image オペレーションに渡すか、既存の Amazon S3 オブジェクトを参照します。Amazon S3 バケットに保存されているイメージの分析例については、「[Amazon S3 バケットに保存されたイメージの分析](images-s3.md)」を参照してください。Amazon Rekognition Image API オペレーションにイメージバイトを渡す例については、「[ローカルファイルシステムからロードしたイメージの分析](images-bytes.md)」を参照してください。

HTTP を使用して Amazon Rekognition Image オペレーションの一部として渡す場合のイメージバイトは、base64 でエンコードされた文字列であることが必要です。AWS SDK を使用して API オペレーションの呼び出しの一部としてイメージのバイトを渡す場合、イメージのバイトを Base64 でエンコードする必要があるかどうかは使用言語によって異なります。

次の AWS SDKsイメージを base64 エンコードします。Amazon Rekognition Image API オペレーションを呼び出す前にイメージのバイトをエンコードする必要はありません。
+ Java
+ JavaScript
+ Python
+ PHP

別の AWS SDK を使用しているときに Rekognition API オペレーションの呼び出しに伴ってイメージ形式エラーが発生した場合は、イメージのバイトを base64 でエンコードしてから Rekognition API オペレーションに渡してみてください。

を使用して Amazon Rekognition Image オペレーション AWS CLI を呼び出す場合、呼び出しの一部としてイメージのバイトを渡すことはサポートされていません。最初に Amazon S3 バケットにイメージをアップロードし、次にアップロードしたイメージを参照するオペレーションを呼び出します。

**注記**  
イメージのバイトの代わりに `S3Object` に保存されたイメージを渡す場合は、イメージを base64 でエンコードする必要はありません。

Amazon Rekognition オペレーションのレイテンシーをできるだけ低くする方法の詳細については、「[Amazon Rekognition イメージオペレーションのレイテンシ](operation-latency.md)」を参照してください。

## イメージの向きの修正
<a name="images-image-orientation-correction"></a>

いくつかの Rekognition　API オペレーションでは、分析されたイメージの向きが返されます。イメージの向きを知ることは、表示用にイメージの向きを変えるために重要です。顔を分析する Rekognition API オペレーションでは、イメージ内の顔の位置の境界ボックスも返されます。境界ボックスを使用して、顔またはイメージの周囲にボックスを表示できます。返される境界ボックスの座標は、イメージの向きによって影響を受けます。顔の周囲に正しくボックスを表示するには、境界ボックスの座標の変換が必要になる場合があります。詳細については、「[イメージの向きおよび境界ボックス座標の取得](images-orientation.md)」を参照してください。

## イメージのサイズ変更
<a name="images-image-sizing"></a>

Amazon Rekognition は、分析中に特定のモデルまたはアルゴリズムに最も適した定義済みの範囲のセットを使用して、内部的に画像のサイズを変更します。Amazon Rekognition は、入力イメージの解像度に応じて、異なる数のオブジェクトを検出したり、異なる結果を提供したりすることがあります。たとえば、2 つのイメージがあるとします。最初の画像の解像度は 1024 x 768 ピクセルです。2 番目の画像 (最初のイメージのサイズを変更したバージョン) の解像度は 640 x 480 ピクセルです。イメージを [DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) に送信した場合、`DetectLabels` への 2 つの呼び出しからのレスポンスが若干異なる可能性があります。

# Amazon S3 バケットに保存されたイメージの分析
<a name="images-s3"></a>

Amazon Rekognition Image は、 バケットに保存されたイメージ、またはイメージのバイトとして提供されたイメージを分析できます。

このトピックでは、 [DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) API オペレーションを使用して、Amazon S3 バケットに保存されたイメージ (JPEG または PNG) 内のオブジェクト、概念、シーンを検出します。イメージを Amazon Rekognition Image API オペレーションに渡すには、[Image](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Image.html) 入力パラメータを使用します。`Image` 内で [S3Object](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_3Object.html) オブジェクトプロパティを指定し、S3 バケットに保存されたイメージを参照します。Amazon S3 バケットに保存されたイメージのバイトは base64 でエンコードする必要はありません。詳細については、「[イメージの仕様](images-information.md)」を参照してください。

## リクエストの例
<a name="images-s3-request"></a>

次の `DetectLabels` に対する JSON リクエストの例では、ソースイメージ (`input.jpg`) を `amzn-s3-demo-bucket` と名前をつけた　Amazon S3 バケット からロードします。S3 オブジェクトが含まれている S3 バケットのリージョンと Amazon Rekognition Image オペレーションで使用するリージョンが一致している必要があります。

```
{
    "Image": {
        "S3Object": {
            "Bucket": "amzn-s3-demo-bucket",
            "Name": "input.jpg"
        }
    },
    "MaxLabels": 10,
    "MinConfidence": 75
}
```

次の例では AWS SDKs と を使用して AWS CLI を呼び出します`DetectLabels`。`DetectLabels` オペレーションからのレスポンスの詳細については、「[DetectLabels のレスポンス](labels-detect-labels-image.md#detectlabels-response)」を参照してください。

**イメージ内のラベルを検出するには**

1. まだ実行していない場合:

   1. `AmazonRekognitionFullAccess` と `AmazonS3ReadOnlyAccess` のアクセス権限を持つユーザーを作成または更新します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md#setting-up-iam)」を参照してください。

   1. と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 2: AWS CLI と AWS SDKsを設定する](setup-awscli-sdk.md)」を参照してください。API オペレーションを呼び出すユーザーに、プログラムによるアクセスに必要な適切な権限が付与されていることを確認してください。付与する方法については、「[プログラマチックアクセス権を付与する](sdk-programmatic-access.md)」を参照してください。

1. 1 つ以上のオブジェクト (樹木、家、ボートなど) が含まれているイメージを S3 バケットにアップロードします。イメージは、*.jpg* 形式または *.png* 形式にする必要があります。

   手順については、[Amazon Simple Storage Service 入門ガイド](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)の「*Amazon S3 へのオブジェクトのアップロード*」を参照してください。

1. 以下の例を使用して、`DetectLabels` オペレーションを呼び出します。

------
#### [ Java ]

   この例では、入力イメージ内で検出されたラベルのリストを表示します。`bucket` および `photo` の値は、ステップ 2 で使用したバケット名とイメージ名に置き換えます。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package com.amazonaws.samples;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
   import com.amazonaws.services.rekognition.model.DetectLabelsRequest;
   import com.amazonaws.services.rekognition.model.DetectLabelsResult;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.Label;
   import com.amazonaws.services.rekognition.model.S3Object;
   import java.util.List;
   
   public class DetectLabels {
   
      public static void main(String[] args) throws Exception {
   
         String photo = "input.jpg";
         String bucket = "bucket";
   
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         DetectLabelsRequest request = new DetectLabelsRequest()
              .withImage(new Image()
              .withS3Object(new S3Object()
              .withName(photo).withBucket(bucket)))
              .withMaxLabels(10)
              .withMinConfidence(75F);
   
         try {
            DetectLabelsResult result = rekognitionClient.detectLabels(request);
            List <Label> labels = result.getLabels();
   
            System.out.println("Detected labels for " + photo);
            for (Label label: labels) {
               System.out.println(label.getName() + ": " + label.getConfidence().toString());
            }
         } catch(AmazonRekognitionException e) {
            e.printStackTrace();
         }
      }
   }
   ```

------
#### [ AWS CLI ]

   この例では、`detect-labels`　CLI オペレーションの JSON 出力を表示します。`bucket` および `photo` の値は、ステップ 2 で使用した Amazon S3 バケット名とイメージ名に置き換えます。Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   aws rekognition detect-labels --image '{ "S3Object": { "Bucket": "bucket-name", "Name": "file-name" } }' \
   --features GENERAL_LABELS IMAGE_PROPERTIES \
   --settings '{"ImageProperties": {"MaxDominantColors":1}, {"GeneralLabels":{"LabelInclusionFilters":["Cat"]}}}' \
   --profile profile-name \
   --region us-east-1
   ```

   Windows を使用しているお客様は、場合によって、以下の例のように引用符をエスケープする必要があります。

   ```
   aws rekognition detect-labels --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"file-name\"}}" --features GENERAL_LABELS IMAGE_PROPERTIES --settings "{\"GeneralLabels\":{\"LabelInclusionFilters\":[\"Car\"]}}" --profile profile-name --region us-east-1
   ```

------
#### [ Java V2 ]

   このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。完全な例を [こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabelsS3.java) を参照してください。

   ```
   //snippet-start:[rekognition.java2.detect_labels.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.DetectLabelsRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectLabelsResponse;
   import software.amazon.awssdk.services.rekognition.model.Label;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.S3Object;
   import java.util.List;
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class DetectLabels {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <bucket> <image>\n\n" +
               "Where:\n" +
               "   bucket - The name of the Amazon S3 bucket that contains the image (for example, ,ImageBucket)." +
               "   image - The name of the image located in the Amazon S3 bucket (for example, Lake.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String bucket = args[0];
           String image = args[1];
           Region region = Region.US_WEST_2;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           getLabelsfromImage(rekClient, bucket, image);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.detect_labels_s3.main]
       public static void getLabelsfromImage(RekognitionClient rekClient, String bucket, String image) {
   
           try {
               S3Object s3Object = S3Object.builder()
                   .bucket(bucket)
                   .name(image)
                   .build() ;
   
               Image myImage = Image.builder()
                   .s3Object(s3Object)
                   .build();
   
               DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
                   .image(myImage)
                   .maxLabels(10)
                   .build();
   
               DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest);
               List<Label> labels = labelsResponse.labels();
               System.out.println("Detected labels for the given photo");
               for (Label label: labels) {
                   System.out.println(label.name() + ": " + label.confidence().toString());
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
    // snippet-end:[rekognition.java2.detect_labels.main]
   }
   ```

------
#### [ Python ]

   この例では、入力イメージ内で検出されたラベルを表示します。`bucket` と `photo` の値を、ステップ 2 で使用した Amazon S3 バケットとイメージの名前に置き換えます。Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def detect_labels(photo, bucket):
   
        session = boto3.Session(profile_name='profile-name')
        client = session.client('rekognition')
   
        response = client.detect_labels(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
        MaxLabels=10,
        # Uncomment to use image properties and filtration settings
        #Features=["GENERAL_LABELS", "IMAGE_PROPERTIES"],
        #Settings={"GeneralLabels": {"LabelInclusionFilters":["Cat"]},
        # "ImageProperties": {"MaxDominantColors":10}}
        )
   
        print('Detected labels for ' + photo)
        print()
        for label in response['Labels']:
            print("Label: " + label['Name'])
            print("Confidence: " + str(label['Confidence']))
            print("Instances:")
   
            for instance in label['Instances']:
                print(" Bounding box")
                print(" Top: " + str(instance['BoundingBox']['Top']))
                print(" Left: " + str(instance['BoundingBox']['Left']))
                print(" Width: " + str(instance['BoundingBox']['Width']))
                print(" Height: " + str(instance['BoundingBox']['Height']))
                print(" Confidence: " + str(instance['Confidence']))
                print()
   
            print("Parents:")
            for parent in label['Parents']:
               print(" " + parent['Name'])
   
            print("Aliases:")
            for alias in label['Aliases']:
                print(" " + alias['Name'])
   
                print("Categories:")
            for category in label['Categories']:
                print(" " + category['Name'])
                print("----------")
                print()
   
        if "ImageProperties" in str(response):
            print("Background:")
            print(response["ImageProperties"]["Background"])
            print()
            print("Foreground:")
            print(response["ImageProperties"]["Foreground"])
            print()
            print("Quality:")
            print(response["ImageProperties"]["Quality"])
            print()
   
        return len(response['Labels'])
   
   def main():
       photo = 'photo-name'
       bucket = 'amzn-s3-demo-bucket'
       label_count = detect_labels(photo, bucket)
       print("Labels detected: " + str(label_count))
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Node.Js ]

   この例では、イメージ内で検出されたラベルに関する情報を表示します。

   `photo` の値は、1 つ以上の有名人の顔が含まれているイメージファイルのパスとファイル名に変更します。`bucket` の値を、提供されたイメージファイルを含む S3 バケット名に変更します。`REGION` の値を、アカウントに関連付けられているリージョンの名前に変更します。Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   // Import required AWS SDK clients and commands for Node.js
   import { DetectLabelsCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   
   // Create SNS service object.
   const rekogClient = new RekognitionClient({
     region: REGION,
     credentials: fromIni({
          profile: 'profile-name',
     }),
   });
   
   const bucket = 'bucket-name'
   const photo = 'photo-name'
   
   // Set params
   const params = {For example, to grant
       Image: {
         S3Object: {
           Bucket: bucket,
           Name: photo
         },
       },
     }
   
   const detect_labels = async () => {
       try {
           const response = await rekogClient.send(new DetectLabelsCommand(params));
           console.log(response.Labels)
           response.Labels.forEach(label =>{
               console.log(`Confidence: ${label.Confidence}`)
               console.log(`Name: ${label.Name}`)
               console.log('Instances:')
               label.Instances.forEach(instance => {
                   console.log(instance)
               })
               console.log('Parents:')
               label.Parents.forEach(name => {
                   console.log(name)
               })
               console.log("-------")
           })
           return response; // For unit tests.
         } catch (err) {
           console.log("Error", err);
         }
   };
   
   detect_labels();
   ```

------
#### [ .NET ]

   この例では、入力イメージ内で検出されたラベルのリストを表示します。`bucket` および `photo` の値は、ステップ 2 で使用した Amazon S3 バケット名とイメージ名に置き換えます。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DetectLabels
   {
       public static void Example()
       {
           String photo = "input.jpg";
           String bucket = "amzn-s3-demo-bucket";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DetectLabelsRequest detectlabelsRequest = new DetectLabelsRequest()
           {
               Image = new Image()
               {
                   S3Object = new S3Object()
                   {
                       Name = photo,
                       Bucket = bucket
                   },
               },
               MaxLabels = 10,
               MinConfidence = 75F
           };
   
           try
           {
               DetectLabelsResponse detectLabelsResponse = rekognitionClient.DetectLabels(detectlabelsRequest);
               Console.WriteLine("Detected labels for " + photo);
               foreach (Label label in detectLabelsResponse.Labels)
                   Console.WriteLine("{0}: {1}", label.Name, label.Confidence);
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }
       }
   }
   ```

------
#### [ Ruby ]

   この例では、入力イメージ内で検出されたラベルのリストを表示します。`bucket` と `photo` の値を、ステップ 2 で使用した Amazon S3 バケットとイメージの名前に置き換えます。

   ```
      # Add to your Gemfile
      # gem 'aws-sdk-rekognition'
      require 'aws-sdk-rekognition'
      credentials = Aws::Credentials.new(
         ENV['AWS_ACCESS_KEY_ID'],
         ENV['AWS_SECRET_ACCESS_KEY']
      )
      bucket = 'bucket' # the bucket name without s3://
      photo  = 'photo' # the name of file
      client   = Aws::Rekognition::Client.new credentials: credentials
      attrs = {
        image: {
          s3_object: {
            bucket: bucket,
            name: photo
          },
        },
        max_labels: 10
      }
     response = client.detect_labels attrs
     puts "Detected labels for: #{photo}"
     response.labels.each do |label|
       puts "Label:      #{label.name}"
       puts "Confidence: #{label.confidence}"
       puts "Instances:"
       label['instances'].each do |instance|
         box = instance['bounding_box']
         puts "  Bounding box:"
         puts "    Top:        #{box.top}"
         puts "    Left:       #{box.left}"
         puts "    Width:      #{box.width}"
         puts "    Height:     #{box.height}"
         puts "  Confidence: #{instance.confidence}"
       end
       puts "Parents:"
       label.parents.each do |parent|
         puts "  #{parent.name}"
       end
       puts "------------"
       puts ""
     end
   ```

------



## レスポンスの例
<a name="images-s3-response"></a>

`DetectLabels` からのレスポンスは、イメージ内で検出されたラベルとラベルの検出に使用された信頼度の配列です。

イメージに対する `DetectLabels` オペレーションを実行するときは、Amazon Rekognition は次の応答例のような出力を返します。

このレスポンスは、オペレーションが Person、Vehicle、Car を含む複数のラベルを検出したことを示しています。各ラベルに信頼度が関連付けられています。たとえば、イメージに人物が含まれている確率として、検出アルゴリズムの信頼度は 98.991432% です。

レスポンスには `Parents` 配列内のラベルの先祖ラベルも含まれます。たとえば、ラベル Automobile には、Vehicle と Transportation という名前の 2 つの親ラベルがあります。

共通オブジェクトラベルに対するレスポンスは、入力画像上のラベルの位置に対する境界ボックス情報を含みます。例えば、Person ラベルには、2 つの境界ボックスを含むインスタンス配列があります。これらは、画像内で検出された 2 人の人物の位置です。

フィールド `LabelModelVersion` には `DetectLabels` で使用される検出モデルのバージョン番号が含まれます。

この `DetectLabels` オペレーションの使用の詳細については、「[オブジェクトおよび概念の検出](labels.md)」を参照してください。

```
{
            
    {
    "Labels": [
        {
            "Name": "Vehicle",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Transportation",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": []
        },
        {
            "Name": "Automobile",
            "Confidence": 99.15271759033203,
            "Instances": [],
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Car",
            "Confidence": 99.15271759033203,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.10616336017847061,
                        "Height": 0.18528179824352264,
                        "Left": 0.0037978808395564556,
                        "Top": 0.5039216876029968
                    },
                    "Confidence": 99.15271759033203
                },
                {
                    "BoundingBox": {
                        "Width": 0.2429988533258438,
                        "Height": 0.21577216684818268,
                        "Left": 0.7309805154800415,
                        "Top": 0.5251884460449219
                    },
                    "Confidence": 99.1286392211914
                },
                {
                    "BoundingBox": {
                        "Width": 0.14233611524105072,
                        "Height": 0.15528248250484467,
                        "Left": 0.6494812965393066,
                        "Top": 0.5333095788955688
                    },
                    "Confidence": 98.48368072509766
                },
                {
                    "BoundingBox": {
                        "Width": 0.11086395382881165,
                        "Height": 0.10271988064050674,
                        "Left": 0.10355594009160995,
                        "Top": 0.5354844927787781
                    },
                    "Confidence": 96.45606231689453
                },
                {
                    "BoundingBox": {
                        "Width": 0.06254628300666809,
                        "Height": 0.053911514580249786,
                        "Left": 0.46083059906959534,
                        "Top": 0.5573825240135193
                    },
                    "Confidence": 93.65448760986328
                },
                {
                    "BoundingBox": {
                        "Width": 0.10105438530445099,
                        "Height": 0.12226245552301407,
                        "Left": 0.5743985772132874,
                        "Top": 0.534368634223938
                    },
                    "Confidence": 93.06217193603516
                },
                {
                    "BoundingBox": {
                        "Width": 0.056389667093753815,
                        "Height": 0.17163699865341187,
                        "Left": 0.9427769780158997,
                        "Top": 0.5235804319381714
                    },
                    "Confidence": 92.6864013671875
                },
                {
                    "BoundingBox": {
                        "Width": 0.06003860384225845,
                        "Height": 0.06737709045410156,
                        "Left": 0.22409997880458832,
                        "Top": 0.5441341400146484
                    },
                    "Confidence": 90.4227066040039
                },
                {
                    "BoundingBox": {
                        "Width": 0.02848697081208229,
                        "Height": 0.19150497019290924,
                        "Left": 0.0,
                        "Top": 0.5107086896896362
                    },
                    "Confidence": 86.65286254882812
                },
                {
                    "BoundingBox": {
                        "Width": 0.04067881405353546,
                        "Height": 0.03428703173995018,
                        "Left": 0.316415935754776,
                        "Top": 0.5566273927688599
                    },
                    "Confidence": 85.36471557617188
                },
                {
                    "BoundingBox": {
                        "Width": 0.043411049991846085,
                        "Height": 0.0893595889210701,
                        "Left": 0.18293385207653046,
                        "Top": 0.5394920110702515
                    },
                    "Confidence": 82.21705627441406
                },
                {
                    "BoundingBox": {
                        "Width": 0.031183116137981415,
                        "Height": 0.03989990055561066,
                        "Left": 0.2853088080883026,
                        "Top": 0.5579366683959961
                    },
                    "Confidence": 81.0157470703125
                },
                {
                    "BoundingBox": {
                        "Width": 0.031113790348172188,
                        "Height": 0.056484755128622055,
                        "Left": 0.2580395042896271,
                        "Top": 0.5504819750785828
                    },
                    "Confidence": 56.13441467285156
                },
                {
                    "BoundingBox": {
                        "Width": 0.08586374670267105,
                        "Height": 0.08550430089235306,
                        "Left": 0.5128012895584106,
                        "Top": 0.5438792705535889
                    },
                    "Confidence": 52.37760925292969
                }
            ],
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ]
        },
        {
            "Name": "Human",
            "Confidence": 98.9914321899414,
            "Instances": [],
            "Parents": []
        },
        {
            "Name": "Person",
            "Confidence": 98.9914321899414,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.19360728561878204,
                        "Height": 0.2742200493812561,
                        "Left": 0.43734854459762573,
                        "Top": 0.35072067379951477
                    },
                    "Confidence": 98.9914321899414
                },
                {
                    "BoundingBox": {
                        "Width": 0.03801717236638069,
                        "Height": 0.06597328186035156,
                        "Left": 0.9155802130699158,
                        "Top": 0.5010883808135986
                    },
                    "Confidence": 85.02790832519531
                }
            ],
            "Parents": []
        }
    ],
    "LabelModelVersion": "2.0"
}

    
}
```

# ローカルファイルシステムからロードしたイメージの分析
<a name="images-bytes"></a>

Amazon Rekognition Image は、Amazon S3 バケットに保存されたイメージ、またはイメージのバイトとして提供されたイメージを分析できます。

以下のトピックでは、ローカルファイルシステムからロードしたファイルを使用して、Amazon Rekognition Image API オペレーションにイメージのバイトを渡す例を示します。イメージのバイトを Amazon Rekognition Image API オペレーションに渡すには [Image](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Image.html) 入力パラメータを使用します。`Image` 内で `Bytes` プロパティを指定し、base64 エンコードされたイメージのバイトを渡します。

`Bytes` 入力パラメータを使用して Amazon Rekognition API オペレーションに渡すイメージのバイトは、base64 でエンコードする必要があります。以下の例で使用する AWS SDK では、イメージを自動的に base64 でエンコードします。Amazon Rekognition API オペレーションを呼び出す前にイメージのバイトをエンコードする必要はありません。詳細については、「[イメージの仕様](images-information.md)」を参照してください。

次の `DetectLabels` に対する JSON リクエストの例では、ソースイメージのバイトを `Bytes` 入力パラメータで渡します。

```
{
    "Image": {
        "Bytes": "/9j/4AAQSk....."
    },
    "MaxLabels": 10,
    "MinConfidence": 77
}
```

次の例では AWS SDKs と を使用して AWS CLI を呼び出します`DetectLabels`。`DetectLabels` オペレーションからのレスポンスの詳細については、「[DetectLabels のレスポンス](labels-detect-labels-image.md#detectlabels-response)」を参照してください。

クライアント側の JavaScript の例については、「[JavaScript を使用する](image-bytes-javascript.md)」を参照してください。

**ローカルイメージ内のラベルを検出するには**

1. まだ実行していない場合:

   1. `AmazonRekognitionFullAccess` と `AmazonS3ReadOnlyAccess` のアクセス権限を持つユーザーを作成または更新します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md#setting-up-iam)」を参照してください。

   1. と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 2: AWS CLI と AWS SDKsを設定する](setup-awscli-sdk.md)」を参照してください。

1. 以下の例を使用して、`DetectLabels` オペレーションを呼び出します。

------
#### [ Java ]

   次の Java の例では、ローカルファイルシステムからイメージをロードし、[detectLabels](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/rekognition/model/DetectLabelsRequest.html) AWS SDK オペレーションを使用してラベルを検出する方法を示します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のパスとファイル名に変更します。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.InputStream;
   import java.nio.ByteBuffer;
   import java.util.List;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.AmazonClientException;
   import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
   import com.amazonaws.services.rekognition.model.DetectLabelsRequest;
   import com.amazonaws.services.rekognition.model.DetectLabelsResult;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.Label;
   import com.amazonaws.util.IOUtils;
   
   public class DetectLabelsLocalFile {
       public static void main(String[] args) throws Exception {
       	String photo="input.jpg";
   
   
           ByteBuffer imageBytes;
           try (InputStream inputStream = new FileInputStream(new File(photo))) {
               imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
           }
   
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           DetectLabelsRequest request = new DetectLabelsRequest()
                   .withImage(new Image()
                           .withBytes(imageBytes))
                   .withMaxLabels(10)
                   .withMinConfidence(77F);
   
           try {
   
               DetectLabelsResult result = rekognitionClient.detectLabels(request);
               List <Label> labels = result.getLabels();
   
               System.out.println("Detected labels for " + photo);
               for (Label label: labels) {
                  System.out.println(label.getName() + ": " + label.getConfidence().toString());
               }
   
           } catch (AmazonRekognitionException e) {
               e.printStackTrace();
           }
   
       }
   }
   ```

------
#### [ Python ]

   次の [AWS SDK for Python](https://aws.amazon.com/sdk-for-python/) の例では、ローカルファイルシステムからイメージをロードし、[detect\$1labels](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition.html#Rekognition.Client.detect_labels) オペレーションを呼び出す方法を示します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のパスとファイル名に変更します。

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def detect_labels_local_file(photo):
   
   
       client=boto3.client('rekognition')
      
       with open(photo, 'rb') as image:
           response = client.detect_labels(Image={'Bytes': image.read()})
           
       print('Detected labels in ' + photo)    
       for label in response['Labels']:
           print (label['Name'] + ' : ' + str(label['Confidence']))
   
       return len(response['Labels'])
   
   def main():
       photo='photo'
   
       label_count=detect_labels_local_file(photo)
       print("Labels detected: " + str(label_count))
   
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ .NET ]

   次の の例では、ローカルファイルシステムからイメージをロードし、`DetectLabels` オペレーションを使用してラベルを検出する方法を示します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のパスとファイル名に変更します。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using System.IO;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DetectLabelsLocalfile
   {
       public static void Example()
       {
           String photo = "input.jpg";
   
           Amazon.Rekognition.Model.Image image = new Amazon.Rekognition.Model.Image();
           try
           {
               using (FileStream fs = new FileStream(photo, FileMode.Open, FileAccess.Read))
               {
                   byte[] data = null;
                   data = new byte[fs.Length];
                   fs.Read(data, 0, (int)fs.Length);
                   image.Bytes = new MemoryStream(data);
               }
           }
           catch (Exception)
           {
               Console.WriteLine("Failed to load file " + photo);
               return;
           }
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DetectLabelsRequest detectlabelsRequest = new DetectLabelsRequest()
           {
               Image = image,
               MaxLabels = 10,
               MinConfidence = 77F
           };
   
           try
           {
               DetectLabelsResponse detectLabelsResponse = rekognitionClient.DetectLabels(detectlabelsRequest);
               Console.WriteLine("Detected labels for " + photo);
               foreach (Label label in detectLabelsResponse.Labels)
                   Console.WriteLine("{0}: {1}", label.Name, label.Confidence);
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }
       }
   }
   ```

------
#### [ PHP ]

   次の [AWS SDK for PHP](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/welcome.html#getting-started) の例では、ローカルファイルシステムからイメージをロードし、[DetectFaces](https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-rekognition-2016-06-27.html#detectfaces) API オペレーションを呼び出します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のパスとファイル名に変更します。

   ```
   
   <?php
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
       require 'vendor/autoload.php';
   
       use Aws\Rekognition\RekognitionClient;
   
       $options = [
          'region'            => 'us-west-2',
           'version'           => 'latest'
       ];
   
       $rekognition = new RekognitionClient($options);
   	
       // Get local image
       $photo = 'input.jpg';
       $fp_image = fopen($photo, 'r');
       $image = fread($fp_image, filesize($photo));
       fclose($fp_image);
   
   
       // Call DetectFaces
       $result = $rekognition->DetectFaces(array(
          'Image' => array(
             'Bytes' => $image,
          ),
          'Attributes' => array('ALL')
          )
       );
   
       // Display info for each detected person
       print 'People: Image position and estimated age' . PHP_EOL;
       for ($n=0;$n<sizeof($result['FaceDetails']); $n++){
   
         print 'Position: ' . $result['FaceDetails'][$n]['BoundingBox']['Left'] . " "
         . $result['FaceDetails'][$n]['BoundingBox']['Top']
         . PHP_EOL
         . 'Age (low): '.$result['FaceDetails'][$n]['AgeRange']['Low']
         .  PHP_EOL
         . 'Age (high): ' . $result['FaceDetails'][$n]['AgeRange']['High']
         .  PHP_EOL . PHP_EOL;
       }
   ?>
   ```

------
#### [ Ruby ]

   この例では、入力イメージ内で検出されたラベルのリストを表示します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のパスとファイル名に変更します。

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
       # gem 'aws-sdk-rekognition'
       require 'aws-sdk-rekognition'
       credentials = Aws::Credentials.new(
          ENV['AWS_ACCESS_KEY_ID'],
          ENV['AWS_SECRET_ACCESS_KEY']
       )
       client   = Aws::Rekognition::Client.new credentials: credentials
       photo = 'photo.jpg'
       path = File.expand_path(photo) # expand path relative to the current directory
       file = File.read(path)
       attrs = {
         image: {
           bytes: file
         },
         max_labels: 10
       }
       response = client.detect_labels attrs
       puts "Detected labels for: #{photo}"
       response.labels.each do |label|
         puts "Label:      #{label.name}"
         puts "Confidence: #{label.confidence}"
         puts "Instances:"
         label['instances'].each do |instance|
           box = instance['bounding_box']
           puts "  Bounding box:"
           puts "    Top:        #{box.top}"
           puts "    Left:       #{box.left}"
           puts "    Width:      #{box.width}"
           puts "    Height:     #{box.height}"
           puts "  Confidence: #{instance.confidence}"
         end
         puts "Parents:"
         label.parents.each do |parent|
           puts "  #{parent.name}"
         end
         puts "------------"
         puts ""
       end
   ```

------
#### [ Java V2 ]

   このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。完全な例を [こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectLabels.java) を参照してください。

   ```
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.*;
   
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   
   /**
    * Before running this Java V2 code example, set up your development
    * environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class DetectLabels {
       public static void main(String[] args) {
           final String usage = """
               Usage: <bucketName> <sourceImage>
   
               Where:
                   bucketName - The name of the Amazon S3 bucket where the image is stored
                   sourceImage - The name of the image file (for example, pic1.png).\s
               """;
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String bucketName = args[0] ;
           String sourceImage = args[1] ;
           Region region = Region.US_WEST_2;
           RekognitionClient rekClient = RekognitionClient.builder()
                   .region(region)
                   .build();
   
           detectImageLabels(rekClient, bucketName, sourceImage);
           rekClient.close();
       }
   
       /**
        * Detects the labels in an image stored in an Amazon S3 bucket using the Amazon Rekognition service.
        *
        * @param rekClient     the Amazon Rekognition client used to make the detection request
        * @param bucketName    the name of the Amazon S3 bucket where the image is stored
        * @param sourceImage   the name of the image file to be analyzed
        */
       public static void detectImageLabels(RekognitionClient rekClient, String bucketName, String sourceImage) {
           try {
               S3Object s3ObjectTarget = S3Object.builder()
                       .bucket(bucketName)
                       .name(sourceImage)
                       .build();
   
               Image souImage = Image.builder()
                       .s3Object(s3ObjectTarget)
                       .build();
   
               DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
                       .image(souImage)
                       .maxLabels(10)
                       .build();
   
               DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest);
               List<Label> labels = labelsResponse.labels();
               System.out.println("Detected labels for the given photo");
               for (Label label : labels) {
                   System.out.println(label.name() + ": " + label.confidence().toString());
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   }
   ```

------

# JavaScript を使用する
<a name="image-bytes-javascript"></a>

次の JavaScript ウェブページの例では、ユーザーがイメージを選択し、そのイメージで検出された顔の推定年齢を表示することを許可します。推定年齢は [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) を呼び出すと返されます。

選択したイメージは、JavaScript の `FileReader.readAsDataURL` 関数を使用してロードされます。これに伴って、イメージは base64 でエンコードされます。これは、HTML キャンバスでイメージを表示するのに役立ちます。ただし、イメージバイトを Amazon Rekognition Image オペレーションに渡す前にエンコードされていない状態にする必要があります。この例では、ロードされたイメージバイトをエンコードされていない状態にする方法を示しています。エンコードされたイメージバイトが有用でない場合は、代わりにロードされたイメージがエンコードされない `FileReader.readAsArrayBuffer` を使用します。つまり、最初にイメージバイトをエンコードされていない状態にする処理なしで、Amazon Rekognition Image オペレーションを呼び出すことができます。例については、[readAsArrayBuffer を使用する](#image-bytes-javascript-unencoded)を参照してください。

**JavaScript の例を実行するには**

1. ソースコード例をエディタにロードします。

1. Amazon Cognito identity プールの識別子を取得します。詳細については、「[Amazon Cognito identity プールの識別を取得します。](#image-bytes-javascript-auth)」を参照してください。

1. コード例の `AnonLog` 関数で、`IdentityPoolIdToUse` と `RegionToUse` は「[Amazon Cognito identity プールの識別を取得します。](#image-bytes-javascript-auth)」のステップ 9 で書き留めた値に変更します。

1. `DetectFaces` 関数の `RegionToUse` を、前のステップで使用した値に変更します。

1. ソースコード例を `.html` ファイルとして保存します。

1. ブラウザにファイルをロードします。

1. [**参照...**] ボタンを選択して、1 つ以上の顔が含まれたイメージを選択します。イメージ内で検出された顔ごとの推定年齢が含まれたテーブルが表示されます。

**注記**  
以下のコード例では、Amazon Cognito に含まれなくなった 2 つのスクリプトを使用しています。これらのファイルを取得するには、[aws-cognito-sdk.min.js](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/aws-cognito-sdk.js) および [amazon-cognito-identity.min.js](https://raw.githubusercontent.com/aws/amazon-cognito-identity-js/master/dist/amazon-cognito-identity.min.js) のリンクをたどり、それぞれのテキストを個別の `.js` ファイルとして保存します。

## JavaScript のコード例
<a name="image-bytes-javascript-code"></a>

次のコード例では JavaScript V2 を使用しています。JavaScript V3 の例については、[AWS 「Documentation SDK examples GitHub repository」の「例」を参照してください。](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/rekognition/estimate-age-example/src)

```
<!--
Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
-->
<!DOCTYPE html>
<html>
<head>
  <script src="aws-cognito-sdk.min.js"></script>
  <script src="amazon-cognito-identity.min.js"></script>
  <script src="https://sdk.amazonaws.com/js/aws-sdk-2.16.0.min.js"></script>
  <meta charset="UTF-8">
  <title>Rekognition</title>
</head>

<body>
  <H1>Age Estimator</H1>
  <input type="file" name="fileToUpload" id="fileToUpload" accept="image/*">
  <p id="opResult"></p>
</body>
<script>

  document.getElementById("fileToUpload").addEventListener("change", function (event) {
    ProcessImage();
  }, false);
  
  //Calls DetectFaces API and shows estimated ages of detected faces
  function DetectFaces(imageData) {
    AWS.region = "RegionToUse";
    var rekognition = new AWS.Rekognition();
    var params = {
      Image: {
        Bytes: imageData
      },
      Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });
  }
  //Loads selected image and unencodes image bytes for Rekognition DetectFaces API
  function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        var img = document.createElement('img');
        var image = null;
        img.src = e.target.result;
        var jpg = true;
        try {
          image = atob(e.target.result.split("data:image/jpeg;base64,")[1]);

        } catch (e) {
          jpg = false;
        }
        if (jpg == false) {
          try {
            image = atob(e.target.result.split("data:image/png;base64,")[1]);
          } catch (e) {
            alert("Not an image file Rekognition can process");
            return;
          }
        }
        //unencode image bytes for Rekognition DetectFaces API 
        var length = image.length;
        imageBytes = new ArrayBuffer(length);
        var ua = new Uint8Array(imageBytes);
        for (var i = 0; i < length; i++) {
          ua[i] = image.charCodeAt(i);
        }
        //Call Rekognition  
        DetectFaces(ua);
      };
    })(file);
    reader.readAsDataURL(file);
  }
  //Provides anonymous log on to AWS services
  function AnonLog() {
    
    // Configure the credentials provider to use your identity pool
    AWS.config.region = 'RegionToUse'; // Region
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'IdentityPoolIdToUse',
    });
    // Make the call to obtain credentials
    AWS.config.credentials.get(function () {
      // Credentials will be available when this function is called.
      var accessKeyId = AWS.config.credentials.accessKeyId;
      var secretAccessKey = AWS.config.credentials.secretAccessKey;
      var sessionToken = AWS.config.credentials.sessionToken;
    });
  }
</script>
</html>
```

### readAsArrayBuffer を使用する
<a name="image-bytes-javascript-unencoded"></a>

次のコードスニペットは、JavaScript V2 を使用したサンプルコード内の `ProcessImage` 関数の代替の実装です。`readAsArrayBuffer` を使用してイメージを読み込み、`DetectFaces` を呼び出します。ロードしたファイルは `readAsArrayBuffer` で base64 エンコードされないため、Amazon Rekognition オペレーションを呼び出す前にイメージのバイトをエンコード解除する必要はありません。

```
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

function ProcessImage() {
    AnonLog();
    var control = document.getElementById("fileToUpload");
    var file = control.files[0];

    // Load base64 encoded image for display 
    var reader = new FileReader();
    reader.onload = (function (theFile) {
      return function (e) {
        //Call Rekognition  
        AWS.region = "RegionToUse";  
        var rekognition = new AWS.Rekognition();
        var params = {
          Image: {
          Bytes: e.target.result
        },
        Attributes: [
        'ALL',
      ]
    };
    rekognition.detectFaces(params, function (err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else {
       var table = "<table><tr><th>Low</th><th>High</th></tr>";
        // show each face and build out estimated age table
        for (var i = 0; i < data.FaceDetails.length; i++) {
          table += '<tr><td>' + data.FaceDetails[i].AgeRange.Low +
            '</td><td>' + data.FaceDetails[i].AgeRange.High + '</td></tr>';
        }
        table += "</table>";
        document.getElementById("opResult").innerHTML = table;
      }
    });

      };
    })(file);
    reader.readAsArrayBuffer(file);
  }
```

## Amazon Cognito identity プールの識別を取得します。
<a name="image-bytes-javascript-auth"></a>

わかりやすいように、この例では、匿名の Amazon Cognito identity プールを使用して、 Amazon Rekognition Image API に認証されていないアクセスを提供します。これは、お客様のニーズに適している場合もあります。たとえば、認証されていないアクセスを使用して、ユーザーがサインアップする前に、無料または試用でウェブサイトにアクセスできるようにできます。認証されたアクセスを提供するには、Amazon Cognito ユーザープールを使用します。詳細については、[Amazon Cognito ID ユーザープール](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) を参照してください。

以下の手順では、認証されていない ID へのアクセスを有効にする ID プールを作成する方法と、コード例で必要な ID プールの ID を取得する方法を説明します。

**ID プールの ID を取得するには**

1. [Amazon Cognito コンソール](https://console.aws.amazon.com/cognito/federated)を開きます。

1. [**Create new identity pool**] を選択します。

1. [**ID プール名\$1**] に ID プールの名前を入力します。

1. [**認証されていない ID**] で、[**認証されていない ID に対してアクセスを有効にする**] を選択します。

1. **[プールの作成]** を選択します。

1. [**詳細の表示**] を選択して、認証されていない ID のロール名をメモします。

1. [**許可**] を選択します。

1. [**プラットフォーム**] で [**JavaScript**] を選択します。

1. [**AWS 認証情報の取得**] で、コードスニペットに表示される `AWS.config.region` と `IdentityPooldId` の値をメモします。

1. IAM コンソール ([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)) を開きます。

1. ナビゲーションペインで **Roles (ロール) ** を選択してください。

1. ステップ 6 で書き留めたロール名を選択します。

1. [**アクセス許可**] タブで、[**ポリシーのアタッチ**] を選択します。

1. [**AmazonRekognitionReadOnlyAccess**] を選択します。

1. ［**ポリシーをアタッチ**] を選択します。

# 境界ボックスの表示
<a name="images-displaying-bounding-boxes"></a>

Amazon Rekognition Image オペレーションは、画像内で検出されたアイテムの境界ボックス座標を返すことができます。例えば、[DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) オペレーションは、イメージから検出された各顔の境界ボックス ([BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html)) を返します。境界ボックス座標を使用して、検出されたアイテムの周囲にボックスを表示できます。たとえば、次の図は、顔を囲む境界ボックスを示しています。

![\[眼鏡をかけ、微笑んでいる若い女性。周りにシャボン玉が浮かんでいる。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/face.png)


`BoundingBox` には以下のプロパティがあります。
+ Height – 画像全体の高さの比率としての境界ボックスの高さ。
+ Left – 画像全体の幅の比率としての境界ボックスの左座標。
+ Top – 画像全体の高さの比率としての境界ボックスの上端座標。
+ Width – 画像全体の幅の比率としての境界ボックスの幅。

各 BoundingBox プロパティには、0 から 1 の値があります。各プロパティ値は全体の画像幅 (`Left` および `Width`) または高さ (`Height` および `Top`) の比率です。たとえば、入力イメージが 700 x 200 ピクセルの場合、境界ボックスの左上の座標は 350 x 50 ピクセルで、API は `Left` 値 0.5 (350/700) および `Top` 値 0.25 (50/200) を返します。

次の図は、各境界ボックスのプロパティがカバーする画像の範囲を示しています。

![\[境界ボックスと画像の寸法の関係を示すグラフィック。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/bounding-box.png)


適切な場所に適切なサイズで境界ボックスを表示するには、ピクセル値を取得するには、BoundingBox 値にイメージの幅または高さ (必要な値に応じて) を掛ける必要があります。境界ボックスを表示するには、ピクセル値を使用します。たとえば、前の画像のピクセルのディメンションは、幅 608x 高さ 588 です。顔の境界ボックスの値は次のとおりです。

```
BoundingBox.Left: 0.3922065
BoundingBox.Top: 0.15567766
BoundingBox.Width: 0.284666
BoundingBox.Height: 0.2930403
```

顔の境界ボックスの位置 (ピクセル) は次のように計算されます。

`Left coordinate = BoundingBox.Left (0.3922065) * image width (608) = 238`

`Top coordinate = BoundingBox.Top (0.15567766) * image height (588) = 91`

`Face width = BoundingBox.Width (0.284666) * image width (608) = 173`

`Face height = BoundingBox.Height (0.2930403) * image height (588) = 172`

これらの値を使用して、面の周囲に境界ボックスを表示します。

**注記**  
画像の向きはさまざまです。アプリケーションのなかには、画像を回転させて補正方向で表示する必要がある場合があります。境界ボックスの座標は、画像の向きに影響されます。正しい位置に境界ボックスを表示する前に、座標を変換する必要があるかもしれません。詳細については、「[イメージの向きおよび境界ボックス座標の取得](images-orientation.md)」を参照してください。

次の例は、[DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) を呼び出すことによって検出された顔の周囲に境界ボックスを表示する方法を示しています。例では、画像が 0 度に向けられていると仮定する。この例では、Amazon S3 バケットから画像をダウンロードする方法も示しています。

**境界ボックスを表示するには**

1. まだ実行していない場合:

   1. `AmazonRekognitionFullAccess` と `AmazonS3ReadOnlyAccess` のアクセス権限を持つユーザーを作成または更新します。詳細については、「[ステップ 1: AWS アカウントを設定してユーザーを作成する](setting-up.md#setting-up-iam)」を参照してください。

   1. と AWS SDKs をインストール AWS CLI して設定します。詳細については、「[ステップ 2: AWS CLI と AWS SDKsを設定する](setup-awscli-sdk.md)」を参照してください。

1. 以下の例を使用して、`DetectFaces` オペレーションを呼び出します。

------
#### [ Java ]

   `bucket` の値を、画像ファイルが保存される Amazon S3 バケットに変更します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のファイル名に変更します。

   ```
    
   //Loads images, detects faces and draws bounding boxes.Determines exif orientation, if necessary.
   package com.amazonaws.samples;
   
   //Import the basic graphics classes.
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.util.List;
   import javax.imageio.ImageIO;
   import javax.swing.*;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   
   import com.amazonaws.services.rekognition.model.BoundingBox;
   import com.amazonaws.services.rekognition.model.DetectFacesRequest;
   import com.amazonaws.services.rekognition.model.DetectFacesResult;
   import com.amazonaws.services.rekognition.model.FaceDetail;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.s3.AmazonS3;
   import com.amazonaws.services.s3.AmazonS3ClientBuilder;
   import com.amazonaws.services.s3.model.S3ObjectInputStream;
   
   // Calls DetectFaces and displays a bounding box around each detected image.
   public class DisplayFaces extends JPanel {
   
       private static final long serialVersionUID = 1L;
   
       BufferedImage image;
       static int scale;
       DetectFacesResult result;
   
       public DisplayFaces(DetectFacesResult facesResult, BufferedImage bufImage) throws Exception {
           super();
           scale = 1; // increase to shrink image size.
   
           result = facesResult;
           image = bufImage;
   
           
       }
       // Draws the bounding box around the detected faces.
       public void paintComponent(Graphics g) {
           float left = 0;
           float top = 0;
           int height = image.getHeight(this);
           int width = image.getWidth(this);
   
           Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
   
           // Draw the image.
           g2d.drawImage(image, 0, 0, width / scale, height / scale, this);
           g2d.setColor(new Color(0, 212, 0));
   
           // Iterate through faces and display bounding boxes.
           List<FaceDetail> faceDetails = result.getFaceDetails();
           for (FaceDetail face : faceDetails) {
               
               BoundingBox box = face.getBoundingBox();
               left = width * box.getLeft();
               top = height * box.getTop();
               g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                       Math.round((width * box.getWidth()) / scale), Math.round((height * box.getHeight())) / scale);
               
           }
       }
   
   
       public static void main(String arg[]) throws Exception {
   
           String photo = "photo.png";
           String bucket = "bucket";
           int height = 0;
           int width = 0;
   
           // Get the image from an S3 Bucket
           AmazonS3 s3client = AmazonS3ClientBuilder.defaultClient();
   
           com.amazonaws.services.s3.model.S3Object s3object = s3client.getObject(bucket, photo);
           S3ObjectInputStream inputStream = s3object.getObjectContent();
           BufferedImage image = ImageIO.read(inputStream);
           DetectFacesRequest request = new DetectFacesRequest()
                   .withImage(new Image().withS3Object(new S3Object().withName(photo).withBucket(bucket)));
   
           width = image.getWidth();
           height = image.getHeight();
   
           // Call DetectFaces    
           AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();
           DetectFacesResult result = amazonRekognition.detectFaces(request);
           
           //Show the bounding box info for each face.
           List<FaceDetail> faceDetails = result.getFaceDetails();
           for (FaceDetail face : faceDetails) {
   
               BoundingBox box = face.getBoundingBox();
               float left = width * box.getLeft();
               float top = height * box.getTop();
               System.out.println("Face:");
   
               System.out.println("Left: " + String.valueOf((int) left));
               System.out.println("Top: " + String.valueOf((int) top));
               System.out.println("Face Width: " + String.valueOf((int) (width * box.getWidth())));
               System.out.println("Face Height: " + String.valueOf((int) (height * box.getHeight())));
               System.out.println();
   
           }
   
           // Create frame and panel.
           JFrame frame = new JFrame("RotateImage");
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           DisplayFaces panel = new DisplayFaces(result, image);
           panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
           frame.setContentPane(panel);
           frame.pack();
           frame.setVisible(true);
   
       }
   }
   ```

------
#### [ Python ]

   `bucket` の値を、画像ファイルが保存される Amazon S3 バケットに変更します。`photo` の値は、イメージファイル (.jpg 形式または .png 形式) のファイル名に変更します。Rekognition セッションを作成する行の `profile_name` の値を、自分のデベロッパープロファイル名に置き換えます。

   ```
   import boto3
   import io
   from PIL import Image, ImageDraw
   
   def show_faces(photo, bucket):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       # Load image from S3 bucket
       s3_connection = boto3.resource('s3')
       s3_object = s3_connection.Object(bucket, photo)
       s3_response = s3_object.get()
   
       stream = io.BytesIO(s3_response['Body'].read())
       image = Image.open(stream)
   
       # Call DetectFaces
       response = client.detect_faces(Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
                                      Attributes=['ALL'])
   
       imgWidth, imgHeight = image.size
       draw = ImageDraw.Draw(image)
   
       # calculate and display bounding boxes for each detected face
       print('Detected faces for ' + photo)
       for faceDetail in response['FaceDetails']:
           print('The detected face is between ' + str(faceDetail['AgeRange']['Low'])
                 + ' and ' + str(faceDetail['AgeRange']['High']) + ' years old')
   
           box = faceDetail['BoundingBox']
           left = imgWidth * box['Left']
           top = imgHeight * box['Top']
           width = imgWidth * box['Width']
           height = imgHeight * box['Height']
   
           print('Left: ' + '{0:.0f}'.format(left))
           print('Top: ' + '{0:.0f}'.format(top))
           print('Face Width: ' + "{0:.0f}".format(width))
           print('Face Height: ' + "{0:.0f}".format(height))
   
           points = (
               (left, top),
               (left + width, top),
               (left + width, top + height),
               (left, top + height),
               (left, top)
   
           )
           draw.line(points, fill='#00d400', width=2)
   
           # Alternatively can draw rectangle. However you can't set line width.
           # draw.rectangle([left,top, left + width, top + height], outline='#00d400')
   
       image.show()
   
       return len(response['FaceDetails'])
   
   def main():
       bucket = "bucket-name"
       photo = "photo-name"
       faces_count = show_faces(photo, bucket)
       print("faces detected: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Java V2 ]

   このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。完全な例を [こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DisplayFacesFrame.java) を参照してください。

   `s3` AWS SDK Amazon S3 クライアントを参照し、`rekClient` AWS SDK Amazon Rekognition クライアントを参考することを注意ください。

   ```
   //snippet-start:[rekognition.java2.detect_labels.import]
   import java.awt.*;
   import java.awt.image.BufferedImage;
   import java.io.ByteArrayInputStream;
   import java.io.FileNotFoundException;
   import java.io.IOException;
   import java.io.InputStream;
   import java.util.List;
   import javax.imageio.ImageIO;
   import javax.swing.*;
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.core.ResponseBytes;
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.model.Attribute;
   import software.amazon.awssdk.services.rekognition.model.BoundingBox;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceDetail;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.s3.S3Client;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.s3.model.GetObjectRequest;
   import software.amazon.awssdk.services.s3.model.GetObjectResponse;
   import software.amazon.awssdk.services.s3.model.S3Exception;
   //snippet-end:[rekognition.java2.detect_labels.import]
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class DisplayFaces extends JPanel {
   
       static DetectFacesResponse result;
       static BufferedImage image;
       static int scale;
   
       public static void main(String[] args) throws Exception {
   
           final String usage = "\n" +
               "Usage: " +
               "   <sourceImage> <bucketName>\n\n" +
               "Where:\n" +
               "   sourceImage - The name of the image in an Amazon S3 bucket (for example, people.png). \n\n" +
               "   bucketName - The name of the Amazon S3 bucket (for example, amzn-s3-demo-bucket). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String sourceImage = args[0];
           String bucketName = args[1];
           Region region = Region.US_EAST_1;
           S3Client s3 = S3Client.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           displayAllFaces(s3, rekClient, sourceImage, bucketName);
           s3.close();
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.display_faces.main]
       public static void displayAllFaces(S3Client s3,
                                          RekognitionClient rekClient,
                                          String sourceImage,
                                          String bucketName) {
           int height;
           int width;
           byte[] data = getObjectBytes (s3, bucketName, sourceImage);
           InputStream is = new ByteArrayInputStream(data);
   
           try {
               SdkBytes sourceBytes = SdkBytes.fromInputStream(is);
               image = ImageIO.read(sourceBytes.asInputStream());
               width = image.getWidth();
               height = image.getHeight();
   
               // Create an Image object for the source image
               software.amazon.awssdk.services.rekognition.model.Image souImage = Image.builder()
                   .bytes(sourceBytes)
                   .build();
   
               DetectFacesRequest facesRequest = DetectFacesRequest.builder()
                   .attributes(Attribute.ALL)
                   .image(souImage)
                   .build();
   
               result = rekClient.detectFaces(facesRequest);
   
               // Show the bounding box info for each face.
               List<FaceDetail> faceDetails = result.faceDetails();
               for (FaceDetail face : faceDetails) {
                   BoundingBox box = face.boundingBox();
                   float left = width * box.left();
                   float top = height * box.top();
                   System.out.println("Face:");
   
                   System.out.println("Left: " + (int) left);
                   System.out.println("Top: " + (int) top);
                   System.out.println("Face Width: " + (int) (width * box.width()));
                   System.out.println("Face Height: " + (int) (height * box.height()));
                   System.out.println();
               }
   
               // Create the frame and panel.
               JFrame frame = new JFrame("RotateImage");
               frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               DisplayFaces panel = new DisplayFaces(image);
               panel.setPreferredSize(new Dimension(image.getWidth() / scale, image.getHeight() / scale));
               frame.setContentPane(panel);
               frame.pack();
               frame.setVisible(true);
   
           } catch (RekognitionException | FileNotFoundException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           } catch (IOException e) {
              e.printStackTrace();
           }
       }
   
       public static byte[] getObjectBytes (S3Client s3, String bucketName, String keyName) {
   
           try {
               GetObjectRequest objectRequest = GetObjectRequest
                   .builder()
                   .key(keyName)
                   .bucket(bucketName)
                   .build();
   
               ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest);
               return objectBytes.asByteArray();
   
           } catch (S3Exception e) {
               System.err.println(e.awsErrorDetails().errorMessage());
               System.exit(1);
           }
           return null;
       }
   
       public DisplayFaces(BufferedImage bufImage) {
           super();
           scale = 1; // increase to shrink image size.
           image = bufImage;
       }
   
       // Draws the bounding box around the detected faces.
       public void paintComponent(Graphics g) {
           float left;
           float top;
           int height = image.getHeight(this);
           int width = image.getWidth(this);
           Graphics2D g2d = (Graphics2D) g; // Create a Java2D version of g.
   
           // Draw the image
           g2d.drawImage(image, 0, 0, width / scale, height / scale, this);
           g2d.setColor(new Color(0, 212, 0));
   
           // Iterate through the faces and display bounding boxes.
           List<FaceDetail> faceDetails = result.faceDetails();
           for (FaceDetail face : faceDetails) {
               BoundingBox box = face.boundingBox();
               left = width * box.left();
               top = height * box.top();
               g2d.drawRect(Math.round(left / scale), Math.round(top / scale),
                       Math.round((width * box.width()) / scale), Math.round((height * box.height())) / scale);
           }
       }
       // snippet-end:[rekognition.java2.display_faces.main]
   }
   ```

------

# イメージの向きおよび境界ボックス座標の取得
<a name="images-orientation"></a>

Amazon Rekognition Image を一般的に使用するアプリケーションは、Amazon Rekognition Image オペレーションによって検出されたイメージと、検出された顔の周囲のボックスを表示する必要があります。アプリケーションで正しくイメージを表示するには、イメージの向きを知り、必要に応じて修正する必要があります。この向きを修正することが必要な場合があります。一部の .jpg ファイルでは、イメージの向きは、イメージの Exchangeable イメージファイル形式 (Exif) メタデータに含まれています。

顔の周りにボックスを表示するには、顔の境界ボックスの座標が必要です。ボックスの向きが正しくない場合は、座標の調整が必要になることがあります。Amazon Rekognition イメージの顔検出オペレーションでは、検出された顔ごとに境界ボックスが返されます。しかし Exif メタデータがない.jpg ファイルの座標は推定されません。

下記の例は、イメージで検出された顔の境界ボックスの座標を示す際の例です。

この例の情報を使用して、イメージの向きが正しく、境界ボックスがアプリケーションで正しい位置に表示されるようにします。

イメージと境界ボックスを回転および表示するためのコードは、使用する言語と環境に依存するため、イメージと境界ボックスをコードで表示する方法や、Exif メタデータから向きの情報を取得する方法については説明しません。



## イメージの向きの検索
<a name="images-discovering-image-orientation"></a>

アプリケーションで正しくイメージを表示するには、回転が必要になる場合があります。次のイメージの向きは 0 度で、正しく表示されています。

![\[ユーザーアカウントやプロフィール画像を表す一般的なプロフィールアイコン。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/00face.png)


ただし、次のイメージは反時計回りに 90 度回転しています。これを正しく表示するには、イメージの向きを見つけ、その情報をコードで使用してイメージを 0 度に回転する必要があります。

![\[ユーザーアカウントやプロフィール画像を表す一般的なプロフィールアイコン。反時計回りに 90 度回転している。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/90face.png)


.jpg 形式の一部のイメージには、Exif メタデータに向きの情報が含まれています。使用可能な場合、イメージの Exif メタデータには向きが含まれています。Exif メタデータで、イメージの向きは `orientation` フィールドで見つかります。Amazon Rekognition は Exif メタデータ内のイメージの向きの情報の存在を認識しますが、その情報へのアクセスは提供しません。イメージで Exif メタデータにアクセスするには、サードパーティーのライブラリを使用するか、独自のコードを記述します。詳細については、「[Exif バージョン 2.32](http://cipa.jp/std/documents/download_e.html?DC-008-Translation-2019-E)」を参照してください。

 



イメージの向きがわかっている場合は、コードを記述して回転し、正しく表示できます。

## 境界ボックスの表示
<a name="images-bounding-boxes"></a>

イメージの顔を分析する Amazon Rekognition Image オペレーションも、顔を囲む境界ボックスの座標を返します。詳細については、「[BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html)」を参照してください。

アプリケーションの次のイメージに示すボックスに類似した境界ボックスを顔の周囲に表示するには、コードで境界ボックスの座標を使用します。オペレーションで返される境界ボックスの座標は、イメージの向きを反映しています。イメージを回転して正しく表示する必要がある場合は、境界ボックスの座標の変換が必要になる場合があります。



![\[顔が赤色の四角で強調表示されているプロフィールアイコン。\]](http://docs.aws.amazon.com/ja_jp/rekognition/latest/dg/images/00facebounding.png)




### 向きの情報が Exif メタデータに存在するときに境界ボックスを表示する
<a name="images-exif-metadata"></a>

イメージの向きが Exif メタデータに含まれている場合、Amazon Rekognition Image オペレーションで以下が実行されます。
+ オペレーションのレスポンスの向き修正フィールドで null が返されます。イメージを回転するには、コードの Exif メタデータに含まれている向きを使用します。
+ すでに向きが設定されている境界ボックスの座標を 0 度に戻します。正しい位置に境界ボックスを表示するには、返された座標を使用します。それらを変換する必要はありません。

## 例: イメージの向きおよびイメージの境界ボックス座標の取得
<a name="images-correcting-image-orientation-java"></a>

以下の例では、AWS SDK を使用して Exif イメージの推定された向きを取得し、`RecognizeCelebrities` オペレーションで検出された有名人の境界ボックス座標を変換する方法を示します。

**注記**  
`OrientationCorrection` フィールドを使用した画像方向の見積もりは、2021 年 8 月をもってサポートを終了しています。API レスポンスに含まれるこのフィールドの戻り値は、常に NULL になります。

------
#### [ Java ]

この例では、ローカルファイルシステムからイメージをロードし、`RecognizeCelebrities` オペレーションを呼び出して、イメージの高さと幅を判断してから、回転したイメージの顔の境界ボックスの座標を計算します。この例では、Exif メタデータに保存される向きの情報を処理する方法は示しません。

関数 `main` で、`photo` の値は、ローカルに保存されているイメージ (.png または .jpg 形式) の名前とパスに置き換えます。

```
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

package com.amazonaws.samples;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.List;
import javax.imageio.ImageIO;
import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.Image;
import com.amazonaws.services.rekognition.model.RecognizeCelebritiesRequest;
import com.amazonaws.services.rekognition.model.RecognizeCelebritiesResult;
import com.amazonaws.util.IOUtils;
import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
import com.amazonaws.services.rekognition.model.BoundingBox;
import com.amazonaws.services.rekognition.model.Celebrity;
import com.amazonaws.services.rekognition.model.ComparedFace;

public class RotateImage {

public static void main(String[] args) throws Exception {

  String photo = "photo.png";

  //Get Rekognition client
 AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();


  // Load image
  ByteBuffer imageBytes=null;
  BufferedImage image = null;

  try (InputStream inputStream = new FileInputStream(new File(photo))) {
     imageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));

  }
  catch(Exception e)
  {
      System.out.println("Failed to load file " + photo);
      System.exit(1);
  }

  //Get image width and height
  InputStream imageBytesStream;
  imageBytesStream = new ByteArrayInputStream(imageBytes.array());

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  image=ImageIO.read(imageBytesStream);
  ImageIO.write(image, "jpg", baos);

  int height = image.getHeight();
  int width = image.getWidth();

  System.out.println("Image Information:");
  System.out.println(photo);
  System.out.println("Image Height: " + Integer.toString(height));
  System.out.println("Image Width: " + Integer.toString(width));

  //Call GetCelebrities

  try{
    RecognizeCelebritiesRequest request = new RecognizeCelebritiesRequest()
           .withImage(new Image()
              .withBytes((imageBytes)));


      RecognizeCelebritiesResult result = amazonRekognition.recognizeCelebrities(request);
      // The returned value of OrientationCorrection will always be null
      System.out.println("Orientation: " + result.getOrientationCorrection() + "\n");
      List <Celebrity> celebs = result.getCelebrityFaces();

      for (Celebrity celebrity: celebs) {
          System.out.println("Celebrity recognized: " + celebrity.getName());
          System.out.println("Celebrity ID: " + celebrity.getId());
          ComparedFace  face = celebrity.getFace()
;             ShowBoundingBoxPositions(height,
                  width,
                  face.getBoundingBox(),
                  result.getOrientationCorrection());
                 
            System.out.println();
       }

   } catch (AmazonRekognitionException e) {
      e.printStackTrace();
   }

}


public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, String rotation) {

  float left = 0;
  float top = 0;
   
  if(rotation==null){
      System.out.println("No estimated estimated orientation. Check Exif data.");
      return;
  }
  //Calculate face position based on image orientation.
  switch (rotation) {
     case "ROTATE_0":
        left = imageWidth * box.getLeft();
        top = imageHeight * box.getTop();
        break;
     case "ROTATE_90":
        left = imageHeight * (1 - (box.getTop() + box.getHeight()));
        top = imageWidth * box.getLeft();
        break;
     case "ROTATE_180":
        left = imageWidth - (imageWidth * (box.getLeft() + box.getWidth()));
        top = imageHeight * (1 - (box.getTop() + box.getHeight()));
        break;
     case "ROTATE_270":
        left = imageHeight * box.getTop();
        top = imageWidth * (1 - box.getLeft() - box.getWidth());
        break;
     default:
        System.out.println("No estimated orientation information. Check Exif data.");
        return;
  }

  //Display face location information.
  System.out.println("Left: " + String.valueOf((int) left));
  System.out.println("Top: " + String.valueOf((int) top));
  System.out.println("Face Width: " + String.valueOf((int)(imageWidth * box.getWidth())));
  System.out.println("Face Height: " + String.valueOf((int)(imageHeight * box.getHeight())));

  }
}
```

------
#### [ Python ]

この例では、PIL/Pillow イメージライブラリを使用してイメージの幅と高さを取得します。詳細については、「[Pillow](https://pillow.readthedocs.io/en/stable/)」を参照してください。この例では、exif メタデータを保存し、アプリケーションの他の場所で利用できるようにします。

関数 `main` で、`photo` の値は、ローカルに保存されているイメージ (.png または .jpg 形式) の名前とパスに置き換えます。

```
#Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

import boto3
import io
from PIL import Image


# Calculate positions from from estimated rotation
def show_bounding_box_positions(imageHeight, imageWidth, box):
    left = 0
    top = 0

    print('Left: ' + '{0:.0f}'.format(left))
    print('Top: ' + '{0:.0f}'.format(top))
    print('Face Width: ' + "{0:.0f}".format(imageWidth * box['Width']))
    print('Face Height: ' + "{0:.0f}".format(imageHeight * box['Height']))


def celebrity_image_information(photo):
    client = boto3.client('rekognition')

    # Get image width and height
    image = Image.open(open(photo, 'rb'))
    width, height = image.size

    print('Image information: ')
    print(photo)
    print('Image Height: ' + str(height))
    print('Image Width: ' + str(width))

    # call detect faces and show face age and placement
    # if found, preserve exif info
    stream = io.BytesIO()
    if 'exif' in image.info:
        exif = image.info['exif']
        image.save(stream, format=image.format, exif=exif)
    else:
        image.save(stream, format=image.format)
    image_binary = stream.getvalue()

    response = client.recognize_celebrities(Image={'Bytes': image_binary})

    print()
    print('Detected celebrities for ' + photo)

    for celebrity in response['CelebrityFaces']:
        print('Name: ' + celebrity['Name'])
        print('Id: ' + celebrity['Id'])

        # Value of "orientation correction" will always be null
        if 'OrientationCorrection' in response:
            show_bounding_box_positions(height, width, celebrity['Face']['BoundingBox'])

        print()
    return len(response['CelebrityFaces'])


def main():
    photo = 'photo'

    celebrity_count = celebrity_image_information(photo)
    print("celebrities detected: " + str(celebrity_count))


if __name__ == "__main__":
    main()
```

------
#### [ Java V2 ]

このコードは、 AWS Documentation SDK サンプル GitHub リポジトリから取得されます。詳しい事例は[こちら](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/RotateImage.java)です。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.RecognizeCelebritiesRequest;
import software.amazon.awssdk.services.rekognition.model.Image;
import software.amazon.awssdk.services.rekognition.model.RecognizeCelebritiesResponse;
import software.amazon.awssdk.services.rekognition.model.Celebrity;
import software.amazon.awssdk.services.rekognition.model.ComparedFace;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.BoundingBox;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class RotateImage {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <sourceImage>

                Where:
                   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String sourceImage = args[0];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Locating celebrities in " + sourceImage);
        recognizeAllCelebrities(rekClient, sourceImage);
        rekClient.close();
    }

    public static void recognizeAllCelebrities(RekognitionClient rekClient, String sourceImage) {
        try {
            BufferedImage image;
            InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            image = ImageIO.read(sourceBytes.asInputStream());
            int height = image.getHeight();
            int width = image.getWidth();

            Image souImage = Image.builder()
                    .bytes(sourceBytes)
                    .build();

            RecognizeCelebritiesRequest request = RecognizeCelebritiesRequest.builder()
                    .image(souImage)
                    .build();

            RecognizeCelebritiesResponse result = rekClient.recognizeCelebrities(request);
            List<Celebrity> celebs = result.celebrityFaces();
            System.out.println(celebs.size() + " celebrity(s) were recognized.\n");
            for (Celebrity celebrity : celebs) {
                System.out.println("Celebrity recognized: " + celebrity.name());
                System.out.println("Celebrity ID: " + celebrity.id());
                ComparedFace face = celebrity.face();
                ShowBoundingBoxPositions(height,
                        width,
                        face.boundingBox(),
                        result.orientationCorrectionAsString());
            }

        } catch (RekognitionException | FileNotFoundException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, String rotation) {
        float left;
        float top;
        if (rotation == null) {
            System.out.println("No estimated estimated orientation.");
            return;
        }

        // Calculate face position based on the image orientation.
        switch (rotation) {
            case "ROTATE_0" -> {
                left = imageWidth * box.left();
                top = imageHeight * box.top();
            }
            case "ROTATE_90" -> {
                left = imageHeight * (1 - (box.top() + box.height()));
                top = imageWidth * box.left();
            }
            case "ROTATE_180" -> {
                left = imageWidth - (imageWidth * (box.left() + box.width()));
                top = imageHeight * (1 - (box.top() + box.height()));
            }
            case "ROTATE_270" -> {
                left = imageHeight * box.top();
                top = imageWidth * (1 - box.left() - box.width());
            }
            default -> {
                System.out.println("No estimated orientation information. Check Exif data.");
                return;
            }
        }

        System.out.println("Left: " + (int) left);
        System.out.println("Top: " + (int) top);
        System.out.println("Face Width: " + (int) (imageWidth * box.width()));
        System.out.println("Face Height: " + (int) (imageHeight * box.height()));
    }
}
```

------