

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

# イメージ内のラベルの検出
<a name="labels-detect-labels-image"></a>

[DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) オペレーションを使用して、イメージ内のラベル (オブジェクトと概念) を検出し、イメージのプロパティに関する情報を取得できます。イメージプロパティには、前景や背景の色、イメージの鮮明度、明るさ、コントラストなどの属性が含まれます。イメージ内のラベルのみ、イメージプロパティのみ、またはその両方を取得できます。例については、[Amazon S3 バケットに保存されたイメージの分析](images-s3.md)を参照してください。

次の例では AWS SDKs と を使用して AWS CLI を呼び出します`DetectLabels`。`DetectLabels` オペレーションからのレスポンスの詳細については、「[DetectLabels のレスポンス](#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)」を参照してください。

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 で使用したバケット名とイメージ名に置き換えます。

   ```
   package com.amazonaws.samples;
   import java.util.List;
   
   import com.amazonaws.services.rekognition.model.BoundingBox;
   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.Instance;
   import com.amazonaws.services.rekognition.model.Label;
   import com.amazonaws.services.rekognition.model.Parent;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
   
   public class DetectLabels {
   
       public static void main(String[] args) throws Exception {
   
           String photo = "photo";
           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 + "\n");
               for (Label label : labels) {
                   System.out.println("Label: " + label.getName());
                   System.out.println("Confidence: " + label.getConfidence().toString() + "\n");
   
                   List<Instance> instances = label.getInstances();
                   System.out.println("Instances of " + label.getName());
                   if (instances.isEmpty()) {
                       System.out.println("  " + "None");
                   } else {
                       for (Instance instance : instances) {
                           System.out.println("  Confidence: " + instance.getConfidence().toString());
                           System.out.println("  Bounding box: " + instance.getBoundingBox().toString());
                       }
                   }
                   System.out.println("Parent labels for " + label.getName() + ":");
                   List<Parent> parents = label.getParents();
                   if (parents.isEmpty()) {
                       System.out.println("  None");
                   } else {
                       for (Parent parent : parents) {
                           System.out.println("  " + parent.getName());
                       }
                   }
                   System.out.println("--------------------");
                   System.out.println();
                  
               }
           } catch (AmazonRekognitionException e) {
               e.printStackTrace();
           }
       }
   }
   ```

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

   この例では、`detect-labels`　CLI オペレーションの JSON 出力を表示します。`bucket` および `photo` の値は、ステップ 2 で使用した Amazon S3 バケット名とイメージ名に置き換えます。`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 デバイスで CLI にアクセスする場合は、パーサーエラーの発生に対処するため、一重引用符の代わりに二重引用符を使用し、内側の二重引用符をバックスラッシュ (\\) でエスケープします。例として以下を参照してください。

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

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

   この例では、入力イメージ内で検出されたラベルを表示します。関数 `main` で、`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()
   ```

------
#### [ .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
   ```

------
#### [ Node.js ]

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

   TypeScript 定義を使用している場合は、`import AWS from 'aws-sdk'` の代わりに`const AWS = require('aws-sdk')` Node.js でプログラムを実行するようになります。詳細については、[AWS JavaScriptのSDK](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/) をご覧ください。構成の設定方法によっては、`AWS.config.update({region:{{region}}});` でリージョンを指定する必要がある場合もあります。

   ```
                                   
   // Load the SDK
   var AWS = require('aws-sdk');
   const bucket = 'bucket-name' // the bucketname without s3://
   const photo  = 'image-name' // the name of file
   
   var credentials = new AWS.SharedIniFileCredentials({profile: 'profile-name'});
   AWS.config.credentials = credentials;
   AWS.config.update({region:'region-name'});
   
   const client = new AWS.Rekognition();
   const params = {
     Image: {
       S3Object: {
         Bucket: bucket,
         Name: photo
       },
     },
     MaxLabels: 10
   }
   client.detectLabels(params, function(err, response) {
     if (err) {
       console.log(err, err.stack); // if an error occurred
     } else {
       console.log(`Detected labels for: ${photo}`)
       response.Labels.forEach(label => {
         console.log(`Label:      ${label.Name}`)
         console.log(`Confidence: ${label.Confidence}`)
         console.log("Instances:")
         label.Instances.forEach(instance => {
           let box = instance.BoundingBox
           console.log("  Bounding box:")
           console.log(`    Top:        ${box.Top}`)
           console.log(`    Left:       ${box.Left}`)
           console.log(`    Width:      ${box.Width}`)
           console.log(`    Height:     ${box.Height}`)
           console.log(`  Confidence: ${instance.Confidence}`)
         })
         console.log("Parents:")
         label.Parents.forEach(parent => {
           console.log(`  ${parent.Name}`)
         })
         console.log("------------")
         console.log("")
       }) // for response.labels
     } // if
   });
   ```

------
#### [ 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) を参照してください。

   ```
   //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]
   }
   ```

------

   

## DetectLabels オペレーションのリクエスト
<a name="detectlabels-request"></a>

`DetectLabel` への入力はイメージです。この JSON 入力の例では、ソースイメージを Amazon S3 バケットからロードします。`MaxLabels` はレスポンスで返すラベルの最大数です。`MinConfidence` は Amazon Rekognition イメージが検出済みラベルの精度で保持しなければならない必要最小限の信頼度であり、それのためにレスポンスで返されます。

Features では、返されるイメージの 1 つ以上の特徴を指定でき、`GENERAL_LABELS` と `IMAGE_PROPERTIES` を選択できます。`GENERAL_LABELS` を含めると、入力イメージで検出されたラベルが返され、`IMAGE_PROPERTIES` を含めるとイメージの色と品質を確認できるようになります。

Settings では、返されるアイテムを `GENERAL_LABELS` と `IMAGE_PROPERTIES` 機能の両方でフィルターできます。ラベルには、包含フィルターと除外フィルターを使用できます。特定のラベル、個別のラベル、またはラベルカテゴリ別にフィルタリングすることもできます。
+ LabelInclusionFilters - レスポンスに含めるラベルを指定できます。
+ LabelExclusionFilters - レスポンスから除外するラベルを指定できます。
+ LabelCategoryInclusionFilters - レスポンスに含めるラベルカテゴリを指定できます。
+ LabelCategoryExclusionFilters - レスポンスから除外するラベルカテゴリを指定できます。

 また、必要に応じて包含フィルターと除外フィルターを組み合わせて、一部のラベルやカテゴリを除外したり、含めたりすることもできます。

`IMAGE_PROPERTIES` は、イメージのドミナントカラーや、鮮明度、明るさ、コントラストなどの品質属性を指します。`IMAGE_PROPERTIES` の検出時に、`MaxDominantColors` パラメータを使用して、返されるドミナントカラーの最大数を指定できます (デフォルトは 10)。

```
{
    "Image": {
        "S3Object": {
            "Bucket": "bucket",
            "Name": "input.jpg"
        }
    },
    "MaxLabels": 10,
    "MinConfidence": 75,
    "Features": [ "GENERAL_LABELS", "IMAGE_PROPERTIES" ],
    "Settings": {
        "GeneralLabels": {
            "LabelInclusionFilters": [<Label(s)>],
            "LabelExclusionFilters": [<Label(s)>],
            "LabelCategoryInclusionFilters": [<Category Name(s)>],
            "LabelCategoryExclusionFilters": [<Category Name(s)>] 
        },
        "ImageProperties": {
            "MaxDominantColors":10
        }
    }
}
```

## DetectLabels のレスポンス
<a name="detectlabels-response"></a>

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

以下に、`DetectLabels` からのレスポンス例を示します。以下のサンプルレスポンスには、GENERAL\_LABELS に対して返される次のようなさまざまな属性が含まれています。
+ 名前 - 検出されたラベルの名前 この例では、オペレーションによって「携帯電話」というラベルの付いたオブジェクトが検出されました。
+ 信頼度 - 各ラベルには信頼度が関連付けられています。この例では、ラベルの信頼度は 99.36% でした。
+ 親 - 検出されたラベルの祖先ラベルです。この例では、「携帯電話」というラベルには「電話」という親ラベルが 1 つあります。
+ エイリアス - ラベルに含まれている可能があるエイリアスの情報 この例では、「携帯電話」ラベルに「セルフォン」というエイリアスが含まれている可能性があります。
+ カテゴリ - 検出されたラベルが属するラベルカテゴリ この例では、「テクノロジーとコンピューティング」です。

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

レスポンスには IMAGE\_PROPERTIES に関する属性も含まれています。IMAGE\_PROPERTIES 機能によって提供される属性は以下のとおりです。
+ 品質 - 入力イメージの鮮明度、明るさ、コントラストに関する情報です。スコアは 0～100 です。品質で評価されるのは、イメージ全体、イメージの背景と前景 (可能な場合) です。ただし、コントラストで評価されるのはイメージ全体のみです。鮮明度と明るさでは、背景と前景も評価に含まれます。
+  ドミナントカラー - イメージ内のドミナントカラーの配列です。ドミナントカラーはそれぞれ、簡略化された色名、CSS カラーパレット、RGB 値、16 進コードで記述されます。
+  前景 - 入力イメージの前景のドミナントカラー、鮮明度、明るさに関する情報です。
+  背景 - 入力イメージの背景のドミナントカラー、鮮明度、明るさに関する情報です。

GENERAL\_LABELS と IMAGE\_PROPERTIES を入力パラメータとして一緒に使用すると、Amazon Rekognition Image は境界ボックスを持つオブジェクトのドミナントカラーも返します。

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

```
{
   
   "Labels": [
        {
            "Name": "Mobile Phone",
            "Parents": [
              { 
                "Name": "Phone" 
              }
            ],
            "Aliases": [
              {
                "Name": "Cell Phone" 
              }
            ], 
            "Categories": [
              {
                "Name": "Technology and Computing"
              }
            ],
            "Confidence": 99.9364013671875,
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.26779675483703613,
                        "Height": 0.8562285900115967,
                        "Left": 0.3604024350643158,
                        "Top": 0.09245597571134567,
                    }
                    "Confidence": 99.9364013671875,
                    "DominantColors": [
                    {
                "Red": 120,
                "Green": 137,
                "Blue": 132,
                "HexCode": "3A7432",
                "SimplifiedColor": "red", 
                "CssColor": "fuscia",    
                "PixelPercentage": 40.10 
                    }       
                        ],
                }
            ]
        }
    ],
    "ImageProperties": {
        "Quality": {
            "Brightness": 40,
            "Sharpness": 40,
            "Contrast": 24,
        },
        "DominantColors": [
            {
                "Red": 120,
                "Green": 137,
                "Blue": 132,
                "HexCode": "3A7432",
                "SimplifiedColor": "red", 
                "CssColor": "fuscia",    
                "PixelPercentage": 40.10 
            }       
        ],
        "Foreground": {
            "Quality": {
                "Brightness": 40,
                "Sharpness": 40,
            },
            "DominantColors": [                
                {                    
                    "Red": 200,
                    "Green": 137,
                    "Blue": 132,
                    "HexCode": "3A7432",
                    "CSSColor": "",
                    "SimplifiedColor": "red", 
                    "PixelPercentage": 30.70             
                }          
            ],   
        }
        "Background": {
            "Quality": {
                "Brightness": 40,
                "Sharpness": 40,
            },
            "DominantColors": [                
                {                    
                    "Red": 200,
                    "Green": 137,
                    "Blue": 132,
                    "HexCode": "3A7432",
                    "CSSColor": "",
                    "SimplifiedColor": "Red", 
                    "PixelPercentage": 10.20              
                }          
            ],   
        }, 
    },
    "LabelModelVersion": "3.0"
}
```

## DetectLabels レスポンスの変換
<a name="detectlabels-transform-response"></a>

DetectLabels API を使用する場合、プライマリラベルとエイリアスの両方が同じリストに含まれていた古い API のレスポンス構造を模倣したレスポンス構造が必要になることがあります。

以下は、[DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) からの現在の API レスポンスの例です。

```
"Labels": [
        {
            "Name": "Mobile Phone",
            "Confidence": 99.99717712402344,
            "Instances": [],
            "Parents": [
                { 
                "Name": "Phone" 
                }
             ],
            "Aliases": [
                {
                "Name": "Cell Phone" 
                }
             ]
        }
 ]
```

以下は、[DetectLabels](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectLabels.html) からの以前の API レスポンスの例です。

```
"Labels": [
        {
            "Name": "Mobile Phone",
            "Confidence": 99.99717712402344,
            "Instances": [],
            "Parents": [
                {
                "Name": "Phone" 
                }
             ]
         },
         {
            "Name": "Cell Phone",
            "Confidence": 99.99717712402344,
            "Instances": [],
            "Parents": [
                { 
                "Name": "Phone" 
                }
             ]
         },
]
```

必要に応じて、現在のレスポンスを古いレスポンスの形式に従うように変換できます。次のサンプルコードを使用して、最新の API レスポンスを以前の API レスポンス構造に変換できます。

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

次のコードサンプルは、DetectLabels API からの現在のレスポンスを変換する方法を示しています。以下のコードサンプルでは、{{EXAMPLE\_INFERENCE\_OUTPUT}} の値を、実行した DetectLabels オペレーションの出力に置き換えることができます。

```
from copy import deepcopy

LABEL_KEY = "Labels"
ALIASES_KEY = "Aliases"
INSTANCE_KEY = "Instances"
NAME_KEY = "Name"

#Latest API response sample
EXAMPLE_INFERENCE_OUTPUT = {
    "Labels": [
        {
            "Name": "Mobile Phone",
            "Confidence": 97.530106,
            "Categories": [
                {
                    "Name": "Technology and Computing"
                }
            ],
            "Aliases": [
                {
                    "Name": "Cell Phone"
                }
            ],
            "Instances":[
                {
                    "BoundingBox":{
                        "Height":0.1549897,
                        "Width":0.07747964,
                        "Top":0.50858885,
                        "Left":0.00018205095
                    },
                    "Confidence":98.401276
                }
            ]
        },
        {
            "Name": "Urban",
            "Confidence": 99.99982,
            "Categories": [
                "Colors and Visual Composition"
            ]
        }
    ]
}

def expand_aliases(inferenceOutputsWithAliases):

    if LABEL_KEY in inferenceOutputsWithAliases:
        expandInferenceOutputs = []
        for primaryLabelDict in inferenceOutputsWithAliases[LABEL_KEY]:
            if ALIASES_KEY in primaryLabelDict:
                for alias in primaryLabelDict[ALIASES_KEY]:
                    aliasLabelDict = deepcopy(primaryLabelDict)
                    aliasLabelDict[NAME_KEY] = alias[NAME_KEY]
                    del aliasLabelDict[ALIASES_KEY]
                    if INSTANCE_KEY in aliasLabelDict:
                        del aliasLabelDict[INSTANCE_KEY]
                    expandInferenceOutputs.append(aliasLabelDict)

        inferenceOutputsWithAliases[LABEL_KEY].extend(expandInferenceOutputs)

    return inferenceOutputsWithAliases


if __name__ == "__main__":

    outputWithExpandAliases = expand_aliases(EXAMPLE_INFERENCE_OUTPUT)
    print(outputWithExpandAliases)
```

変換されたレスポンスの例を以下に示します。

```
#Output example after the transformation
{
    "Labels": [
        {
            "Name": "Mobile Phone",
            "Confidence": 97.530106,
            "Categories": [
                {
                    "Name": "Technology and Computing"
                }
            ],
            "Aliases": [
                {
                    "Name": "Cell Phone"
                }
            ],
            "Instances":[
                {
                    "BoundingBox":{
                        "Height":0.1549897,
                        "Width":0.07747964,
                        "Top":0.50858885,
                        "Left":0.00018205095
                    },
                    "Confidence":98.401276
                }
            ]
        },
        {
            "Name": "Cell Phone",
            "Confidence": 97.530106,
            "Categories": [
                {
                    "Name": "Technology and Computing"
                }
            ],
            "Instances":[]
        },
        {
            "Name": "Urban",
            "Confidence": 99.99982,
            "Categories": [
                "Colors and Visual Composition"
            ]
        }
    ]
}
```

------