

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 分析從本機檔案系統載入的映像
<a name="images-bytes"></a>

Amazon Rekognition Image 操作可以分析做為映像位元組提供的映像，或存放在 Amazon S3 儲存貯體中的映像。

這些主題提供範例，其示範透過使用從本機檔案系統載入的檔案，將映像位元組提供給 Amazon Rekognition Image API 操作。您可以使用[映像](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Image.html)輸入參數，將映像位元組傳遞至 Amazon Rekognition API 操作。在 `Image` 內，指定 `Bytes` 屬性，以傳遞 base64 編碼的映像位元組。

透過使用 `Bytes` 輸入參數傳遞至 Amazon Rekognition API 操作的映像，必須經過 Base64 編碼。這些範例使用的 AWS SDK，會自動以 base64 編碼映像。在呼叫 Amazon Rekognition API 操作前，您不需要再編碼映像位元組。如需詳細資訊，請參閱 [映像規格](images-information.md)。

在這個範例中，JSON 請求 `DetectLabels`，來源映像位元組以 `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 CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 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 ]

   下列[適用於 Python 的 AWS SDK](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 ]

   下列 Java 範例示範如何從本機檔案系統載入映像，並運用 `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 ]

   下列[適用於 PHP 的 AWS SDK](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 文件開發套件範例 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 身分池識別碼。如需詳細資訊，請參閱 [獲取 Amazon Cognito 身分池識別碼](#image-bytes-javascript-auth)。

1. 在範本程式碼的 `AnonLog` 函數中，變更 `IdentityPoolIdToUse` 與 `RegionToUse` 為您在 [獲取 Amazon Cognito 身分池識別碼](#image-bytes-javascript-auth) 步驟 9 中記下的值。

1. 在 `DetectFaces` 函數中，變更 `RegionToUse` 為您在之前的步驟中使用的值。

1. 將範例原始程式碼儲存為 `.html` 檔案。

1. 載入檔案到您的瀏覽器。

1. 選擇**瀏覽...** 按鈕，然後選擇其中包含一或多個人臉的映像。將顯示一個資料表，其中包含每個於映像中偵測到的人臉之估測年齡。

**注意**  
以下程式碼範例使用不再是 Amazon Cognito 一部分的兩個指令碼。若要取得這些檔案，請按[ 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 文件開發套件範例 GitHub 儲存庫中的範例。](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 Image 操作前無需解碼映像位元組。

```
//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 身分池識別碼
<a name="image-bytes-javascript-auth"></a>

為簡化程序，範例將使用匿名 Amazon Cognito 身分池來提供 Amazon Rekognition Image API 未經授權的存取。這可能符合您的需求。例如，您可以使用未經驗證的存取來提供使用者在註冊前的免費存取或試用存取您的網站。為了提供經驗證的存取，使用 Amazon Cognito 使用者集區。如需詳細資訊，請參閱 [Amazon Cognito 使用者集區](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html)。

下列程序說明如何建立身分池，以允許存取未經驗證的身分，以及如何取得在範本程式碼中所需的身分池識別碼。

**若要取得身分池識別碼**

1. 開啟 Amazon Cognito [主控台](https://console.aws.amazon.com/cognito/federated)。

1. 選擇 **Create new identity pool** (建立新的身分池)。

1. 在 **Identity pool name\$1** (身分池名稱\$1) 中，輸入您的身分池名稱。

1. 在 **Unauthenticated identites (未經驗證的身分)** 中，選擇 **Enable access to unauthenticated identities (允許存取未經驗證的身分)** 。

1. 選擇 **Create Pool** (建立集區)。

1. 選擇 **View Details** (檢視詳細資訊)，並記下未經驗證的身分之角色名稱。

1. 選擇 **Allow** (允許)。

1. 在 **Platform** (平台) 中，選擇 **JavaScript**。

1. 在 **Get AWS Credentials (取得 AWS 憑證)** 中，請記下程式碼片段中顯示的 `AWS.config.region` 和 `IdentityPooldId` 值。

1. 在以下網址開啟 IAM 主控台：[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在導覽窗格中，選擇**角色**。

1. 選擇您在步驟 6 記下的角色名稱。

1. 在 **Permissions (許可)** 索引標籤中，選擇 **Attach policies (連接政策)**。

1. 選擇 **AmazonRekognitionReadOnlyAccess**。

1. 選擇 **Attach Policy (連接政策)**。