

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

# 偵測與分析人臉
<a name="faces"></a>

Amazon Rekognition 為您提供 APIs可用於偵測和分析影像和影片中的臉部。本節提供臉部分析的非儲存操作概觀。這些操作包括偵測臉部標記、分析情緒和比較臉部等功能。

Amazon Rekognition 可以識別臉部特徵 （例如眼睛位置）、偵測情緒 （例如快樂或悲傷） 和其他屬性 （例如眼鏡存在、臉部遮蔽）。偵測到臉部時，系統會分析臉部屬性，並傳回每個屬性的可信度分數。

![\[微笑的女人戴著太陽眼鏡，在開放道路上駕駛一輛舊黃色汽車。\]](http://docs.aws.amazon.com/zh_tw/rekognition/latest/dg/images/sample-detect-faces.png)


本節包含影像和影片操作的範例。

如需使用 Rekognition 影像操作的詳細資訊，請參閱 [使用映像](images.md)。

如需使用 Rekognition 影片操作的詳細資訊，請參閱 [使用儲存的影片分析操作](video.md)。

請注意，這些操作是非儲存操作。您可以使用儲存操作和臉部集合，為影像中偵測到的臉部儲存臉部中繼資料。您之後可以搜尋存放在映像與影片中的人臉。例如，您可以在影片中搜尋特定人員。如需詳細資訊，請參閱[在集合中搜尋人臉](collections.md)。

如需詳細資訊，請參閱 [Amazon Rekognition FAQs](https://aws.amazon.com/rekognition/faqs/)的臉部一節。

**注意**  
Amazon Rekognition Image 和 Amazon Rekognition Video 使用的人臉偵測模型不支援偵測卡通/動畫人物或非人類實體。如果您想要偵測映像或影片中的卡通人物，我們建議您使用 Amazon Rekognition 自訂標籤。如需詳細資訊，請參閱 [Amazon Rekognition 自訂標籤開發人員指南》](https://docs.aws.amazon.com/rekognition/latest/customlabels-dg/what-is.html)。

**Topics**
+ [

# 人臉偵測和人臉辨比較的概觀
](face-feature-differences.md)
+ [

# 人臉屬性的準則
](guidance-face-attributes.md)
+ [

# 偵測映像中的人臉
](faces-detect-images.md)
+ [

# 比較映像中的人臉
](faces-comparefaces.md)
+ [

# 偵測已存放影片中的人臉
](faces-sqs-video.md)

# 人臉偵測和人臉辨比較的概觀
<a name="face-feature-differences"></a>

Amazon Rekognition 可讓使用者存取包含臉部影像的兩個主要機器學習應用程式：臉部偵測和臉部比較。它們賦予臉部分析和身分驗證等重要功能，使其對從安全到個人相片組織的各種應用程式至關重要。

**臉部偵測**

人臉偵測系統解決了以下問題：「下圖中有人臉嗎？」 臉部偵測的關鍵層面包括：
+ **位置和方向**：決定影像或影片影格中臉部的存在、位置、縮放和方向。
+ **臉部屬性**：偵測臉部，無論性別、年齡或臉部毛髮等屬性為何。
+ **其他資訊**：提供有關臉部遮蔽和注視方向的詳細資訊。

**臉部比較**

臉部比較系統著重於問題：「一個影像中的臉部是否與另一個影像中的臉部相符？」 人臉比較系統功能包括：
+ **臉部比對預測**：將影像中的臉部與所提供資料庫中的臉部進行比較，以預測比對。
+ **臉部屬性處理**：處理屬性以比較臉部，無論表情、臉部毛髮和年齡。

**可信度分數和遺漏的偵測**

臉部偵測和臉部比較系統都會利用可信度分數。可信度分數表示預測的可能性，例如臉部是否存在或臉部之間是否相符。分數越高表示可能性越大。例如，90% 可信度表示正確偵測或比對的機率高於 60%。

如果臉部偵測系統未正確偵測臉部，或對實際臉部提供低可信度預測，則這是遺漏的偵測/偽陰性。如果系統錯誤地預測臉部存在的高可信度層級，則這是誤報/誤報。

同樣地，臉部比較系統可能不符合屬於同一人的兩個臉部 （缺少偵測/偽陰性），或可能錯誤地預測來自不同人的兩個臉部是同一個人 （偽警示/偽陽性）。

**應用程式設計和閾值設定**
+ 您可以設定閾值，指定傳回結果所需的最低可信度層級。選擇適當的可信度閾值對於根據系統輸出進行應用程式設計和決策至關重要。
+ 您選擇的可信度等級應反映您的使用案例。一些使用案例和可信度閾值的範例：
+ 
  + **相片應用程式**：較低的閾值 （例如 80%) 可能足以識別相片中的家人。
  + **高風險案例**：在遺漏偵測或錯誤警示風險較高的使用案例中，例如安全應用程式，系統應該使用更高的可信度。在這種情況下，建議使用較高的閾值 （例如 99%) 進行準確的臉部配對。

如需設定和了解可信度閾值的詳細資訊，請參閱 [在集合中搜尋人臉](collections.md)。

# 人臉屬性的準則
<a name="guidance-face-attributes"></a>

以下是 Amazon Rekognition 如何處理和傳回臉部屬性的詳細資訊。
+ **FaceDetail 物件**：針對每個偵測到的臉部，會傳回 FaceDetail 物件。此 FaceDetail 包含臉部標記、品質、姿勢等資料。
+ **屬性預測**：預測情緒、性別、年齡等屬性。系統會為每個預測指派可信度層級，並以各自的可信度分數傳回預測。對於敏感的使用案例，建議使用 99% 的可信度閾值。對於年齡估算，預測年齡範圍的中點提供最佳的近似值。

請注意，性別和情緒預測是以身體外觀為基礎，不應用於判斷實際的性別身分或情緒狀態。性別二元論 (男性/女性) 預測是根據特定映像中人臉的實體外觀來判定。它不表示一個人的性別身分，而且您不應該使用 Rekognition 做出這種決定。我們不建議採用性別二元論預測來制定會影響個人權利、隱私或服務存取的決策。同樣地，情緒的預測並不表示一個人的實際內部情緒狀態，而且您不應該使用 Rekognition 做出這種決定。假裝照片中有快樂人臉的人可能看起來很快樂，但可能不會感到快樂。

**應用程式和使用案例**

以下是這些屬性的一些實際應用程式和使用案例：
+ **應用程式**：Smile、Pose 和 Sharpness 等屬性可用來選擇設定檔圖片或匿名估計人口統計特性。
+ **常見使用案例**：社交媒體應用程式和事件或零售商店的人口統計評估是典型的範例。

如需每個屬性的詳細資訊，請參閱 [FaceDetail](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceDetail.html)。

# 偵測映像中的人臉
<a name="faces-detect-images"></a>

Amazon Rekognition Image 提供 [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) 操作，這可尋找主要的人臉特徵 (例如眼睛、鼻子與嘴巴)，以偵測輸入映像中的人臉。Amazon Rekognition Image 可偵測映像中 100 張最大的臉孔。

您可以用映像位元組陣列 (Base64 編碼映像位元組) 的方式提供輸入映像，或指定 Amazon S3 物件。在此程序中，您會將映像 (JPEG 或 PNG) 上傳至您的 S3 儲存貯體，並指定物件索引碼名稱。

**偵測映像中的人臉**

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. 將 (含有一或多個人臉) 的映像上傳至您的 S3 儲存貯體。

   如需指示說明，請參閱《Amazon Simple Storage Service 使用者指南》**中的[上傳物件至 Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html)。

1. 使用下列範例以呼叫 `DetectFaces`。

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

   此範例顯示偵測到之人臉的估計年齡範圍，並列出所有偵測到之人臉屬性的 JSON。變更映像檔案名稱的 `photo` 值。變更儲存映像之 Amazon S3 儲存貯體的 `amzn-s3-demo-bucket` 值。

   ```
   //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 com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.AmazonRekognitionException;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.AgeRange;
   import com.amazonaws.services.rekognition.model.Attribute;
   import com.amazonaws.services.rekognition.model.DetectFacesRequest;
   import com.amazonaws.services.rekognition.model.DetectFacesResult;
   import com.amazonaws.services.rekognition.model.FaceDetail;
   import com.fasterxml.jackson.databind.ObjectMapper;
   import java.util.List;
   
   
   public class DetectFaces {
      
      
      public static void main(String[] args) throws Exception {
   
         String photo = "input.jpg";
         String bucket = "bucket";
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
   
         DetectFacesRequest request = new DetectFacesRequest()
            .withImage(new Image()
               .withS3Object(new S3Object()
                  .withName(photo)
                  .withBucket(bucket)))
            .withAttributes(Attribute.ALL);
         // Replace Attribute.ALL with Attribute.DEFAULT to get default values.
   
         try {
            DetectFacesResult result = rekognitionClient.detectFaces(request);
            List < FaceDetail > faceDetails = result.getFaceDetails();
   
            for (FaceDetail face: faceDetails) {
               if (request.getAttributes().contains("ALL")) {
                  AgeRange ageRange = face.getAgeRange();
                  System.out.println("The detected face is estimated to be between "
                     + ageRange.getLow().toString() + " and " + ageRange.getHigh().toString()
                     + " years old.");
                  System.out.println("Here's the complete set of attributes:");
               } else { // non-default attributes have null values.
                  System.out.println("Here's the default set of attributes:");
               }
   
               ObjectMapper objectMapper = new ObjectMapper();
               System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(face));
            }
   
         } catch (AmazonRekognitionException e) {
            e.printStackTrace();
         }
   
      }
   
   }
   ```

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

   此程式碼取自 AWS 文件開發套件範例 GitHub 儲存庫。請參閱[此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DetectFaces.java)的完整範例。

   ```
   import java.util.List;
   
   //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.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.S3Object;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.DetectFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.Attribute;
   import software.amazon.awssdk.services.rekognition.model.FaceDetail;
   import software.amazon.awssdk.services.rekognition.model.AgeRange;
   
   //snippet-end:[rekognition.java2.detect_labels.import]
   
   public class DetectFaces {
   
       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, ,amzn-s3-demo-bucket)." +
               "   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();
   
               DetectFacesRequest facesRequest = DetectFacesRequest.builder()
                       .attributes(Attribute.ALL)
                       .image(myImage)
                       .build();
   
                   DetectFacesResponse facesResponse = rekClient.detectFaces(facesRequest);
                   List<FaceDetail> faceDetails = facesResponse.faceDetails();
                   for (FaceDetail face : faceDetails) {
                       AgeRange ageRange = face.ageRange();
                       System.out.println("The detected face is estimated to be between "
                                   + ageRange.low().toString() + " and " + ageRange.high().toString()
                                   + " years old.");
   
                       System.out.println("There is a smile : "+face.smile().value().toString());
                   }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
    // snippet-end:[rekognition.java2.detect_labels.main]
   }
   ```

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

   此範例顯示來自 `detect-faces` AWS CLI 操作的 JSON 輸出。將 `file` 取代為映像檔案的名稱。將 `amzn-s3-demo-bucket` 取代為 Amazon S3 儲存貯體的名稱，其中包含映像檔案。

   ```
   aws rekognition detect-faces --image "{"S3Object":{"Bucket":"amzn-s3-demo-bucket,"Name":"image-name"}}"\
                                --attributes "ALL" --profile profile-name --region region-name
   ```

    如果您在 Windows 裝置上存取 CLI，請使用雙引號而非單引號，並以反斜線 (即\$1) 替代內部雙引號，以解決您可能遇到的任何剖析器錯誤。例如，請參閱下列內容：

   ```
   aws rekognition detect-faces --image "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"image-name\"}}" --attributes "ALL" 
   --profile profile-name --region region-name
   ```

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

   此範例顯示偵測到之人臉的估計年齡範圍，並列出所有偵測到之人臉屬性的 JSON。變更映像檔案名稱的 `photo` 值。變更儲存映像之 Amazon S3 儲存貯體的 `amzn-s3-demo-bucket` 值。將建立 Rekognition 工作階段的行中 `profile_name` 值取代為您開發人員設定檔的名稱。

   ```
   import boto3
   import json
   
   def detect_faces(photo, bucket, region):
       
       session = boto3.Session(profile_name='profile-name',
                               region_name=region)
       client = session.client('rekognition', region_name=region)
   
       response = client.detect_faces(Image={'S3Object':{'Bucket':bucket,'Name':photo}},
                                      Attributes=['ALL'])
   
       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')
   
           print('Here are the other attributes:')
           print(json.dumps(faceDetail, indent=4, sort_keys=True))
   
           # Access predictions for individual face details and print them
           print("Gender: " + str(faceDetail['Gender']))
           print("Smile: " + str(faceDetail['Smile']))
           print("Eyeglasses: " + str(faceDetail['Eyeglasses']))
           print("Face Occluded: " + str(faceDetail['FaceOccluded']))
           print("Emotions: " + str(faceDetail['Emotions'][0]))
   
       return len(response['FaceDetails'])
       
   def main():
       photo='photo'
       bucket='amzn-s3-demo-bucket'
       region='region'
       face_count=detect_faces(photo, bucket, region)
       print("Faces detected: " + str(face_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   此範例顯示偵測到之人臉的估計年齡範圍，並列出所有偵測到之人臉屬性的 JSON。變更映像檔案名稱的 `photo` 值。變更儲存映像之 Amazon S3 儲存貯體的 `amzn-s3-demo-bucket` 值。

   ```
   //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.Collections.Generic;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DetectFaces
   {
       public static void Example()
       {
           String photo = "input.jpg";
           String bucket = "amzn-s3-demo-bucket";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DetectFacesRequest detectFacesRequest = new DetectFacesRequest()
           {
               Image = new Image()
               {
                   S3Object = new S3Object()
                   {
                       Name = photo,
                       Bucket = bucket
                   },
               },
               // Attributes can be "ALL" or "DEFAULT". 
               // "DEFAULT": BoundingBox, Confidence, Landmarks, Pose, and Quality.
               // "ALL": See https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Rekognition/TFaceDetail.html
               Attributes = new List<String>() { "ALL" }
           };
   
           try
           {
               DetectFacesResponse detectFacesResponse = rekognitionClient.DetectFaces(detectFacesRequest);
               bool hasAll = detectFacesRequest.Attributes.Contains("ALL");
               foreach(FaceDetail face in detectFacesResponse.FaceDetails)
               {
                   Console.WriteLine("BoundingBox: top={0} left={1} width={2} height={3}", face.BoundingBox.Left,
                       face.BoundingBox.Top, face.BoundingBox.Width, face.BoundingBox.Height);
                   Console.WriteLine("Confidence: {0}\nLandmarks: {1}\nPose: pitch={2} roll={3} yaw={4}\nQuality: {5}",
                       face.Confidence, face.Landmarks.Count, face.Pose.Pitch,
                       face.Pose.Roll, face.Pose.Yaw, face.Quality);
                   if (hasAll)
                       Console.WriteLine("The detected face is estimated to be between " +
                           face.AgeRange.Low + " and " + face.AgeRange.High + " years old.");
               }
           }
           catch (Exception e)
           {
               Console.WriteLine(e.Message);
           }
       }
   }
   ```

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

   此範例顯示偵測到之人臉的估計年齡範圍，並列出各種人臉屬性。變更映像檔案名稱的 `photo` 值。變更儲存映像之 Amazon S3 儲存貯體的 `amzn-s3-demo-bucket` 值。

   ```
      # 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 bucketname without s3://
      photo  = 'input.jpg'# the name of file
      client   = Aws::Rekognition::Client.new credentials: credentials
      attrs = {
        image: {
          s3_object: {
            bucket: bucket,
            name: photo
          },
        },
        attributes: ['ALL']
      }
      response = client.detect_faces attrs
      puts "Detected faces for: #{photo}"
      response.face_details.each do |face_detail|
        low  = face_detail.age_range.low
        high = face_detail.age_range.high
        puts "The detected face is between: #{low} and #{high} years old"
        puts "All other attributes:"
        puts "  bounding_box.width:     #{face_detail.bounding_box.width}"
        puts "  bounding_box.height:    #{face_detail.bounding_box.height}"
        puts "  bounding_box.left:      #{face_detail.bounding_box.left}"
        puts "  bounding_box.top:       #{face_detail.bounding_box.top}"
        puts "  age.range.low:          #{face_detail.age_range.low}"
        puts "  age.range.high:         #{face_detail.age_range.high}"
        puts "  smile.value:            #{face_detail.smile.value}"
        puts "  smile.confidence:       #{face_detail.smile.confidence}"
        puts "  eyeglasses.value:       #{face_detail.eyeglasses.value}"
        puts "  eyeglasses.confidence:  #{face_detail.eyeglasses.confidence}"
        puts "  sunglasses.value:       #{face_detail.sunglasses.value}"
        puts "  sunglasses.confidence:  #{face_detail.sunglasses.confidence}"
        puts "  gender.value:           #{face_detail.gender.value}"
        puts "  gender.confidence:      #{face_detail.gender.confidence}"
        puts "  beard.value:            #{face_detail.beard.value}"
        puts "  beard.confidence:       #{face_detail.beard.confidence}"
        puts "  mustache.value:         #{face_detail.mustache.value}"
        puts "  mustache.confidence:    #{face_detail.mustache.confidence}"
        puts "  eyes_open.value:        #{face_detail.eyes_open.value}"
        puts "  eyes_open.confidence:   #{face_detail.eyes_open.confidence}"
        puts "  mout_open.value:        #{face_detail.mouth_open.value}"
        puts "  mout_open.confidence:   #{face_detail.mouth_open.confidence}"
        puts "  emotions[0].type:       #{face_detail.emotions[0].type}"
        puts "  emotions[0].confidence: #{face_detail.emotions[0].confidence}"
        puts "  landmarks[0].type:      #{face_detail.landmarks[0].type}"
        puts "  landmarks[0].x:         #{face_detail.landmarks[0].x}"
        puts "  landmarks[0].y:         #{face_detail.landmarks[0].y}"
        puts "  pose.roll:              #{face_detail.pose.roll}"
        puts "  pose.yaw:               #{face_detail.pose.yaw}"
        puts "  pose.pitch:             #{face_detail.pose.pitch}"
        puts "  quality.brightness:     #{face_detail.quality.brightness}"
        puts "  quality.sharpness:      #{face_detail.quality.sharpness}"
        puts "  confidence:             #{face_detail.confidence}"
        puts "------------"
        puts ""
      end
   ```

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

   此範例顯示偵測到之人臉的估計年齡範圍，並列出各種人臉屬性。變更映像檔案名稱的 `photo` 值。變更儲存映像之 Amazon S3 儲存貯體的 `amzn-s3-demo-bucket` 值。

    將建立 Rekognition 工作階段的行中 `profile_name` 值取代為您開發人員設定檔的名稱。

   如果您使用 TypeScript 定義，可能需要使用 `import AWS from 'aws-sdk'` 而不是 `const AWS = require('aws-sdk')`，以便使用 Node.js 執行該程序。您可以查閱[適用於 Javascript 的AWS 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  = 'photo-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
       },
     },
     Attributes: ['ALL']
   }
   
   client.detectFaces(params, function(err, response) {
       if (err) {
         console.log(err, err.stack); // an error occurred
       } else {
         console.log(`Detected faces for: ${photo}`)
         response.FaceDetails.forEach(data => {
           let low  = data.AgeRange.Low
           let high = data.AgeRange.High
           console.log(`The detected face is between: ${low} and ${high} years old`)
           console.log("All other attributes:")
           console.log(`  BoundingBox.Width:      ${data.BoundingBox.Width}`)
           console.log(`  BoundingBox.Height:     ${data.BoundingBox.Height}`)
           console.log(`  BoundingBox.Left:       ${data.BoundingBox.Left}`)
           console.log(`  BoundingBox.Top:        ${data.BoundingBox.Top}`)
           console.log(`  Age.Range.Low:          ${data.AgeRange.Low}`)
           console.log(`  Age.Range.High:         ${data.AgeRange.High}`)
           console.log(`  Smile.Value:            ${data.Smile.Value}`)
           console.log(`  Smile.Confidence:       ${data.Smile.Confidence}`)
           console.log(`  Eyeglasses.Value:       ${data.Eyeglasses.Value}`)
           console.log(`  Eyeglasses.Confidence:  ${data.Eyeglasses.Confidence}`)
           console.log(`  Sunglasses.Value:       ${data.Sunglasses.Value}`)
           console.log(`  Sunglasses.Confidence:  ${data.Sunglasses.Confidence}`)
           console.log(`  Gender.Value:           ${data.Gender.Value}`)
           console.log(`  Gender.Confidence:      ${data.Gender.Confidence}`)
           console.log(`  Beard.Value:            ${data.Beard.Value}`)
           console.log(`  Beard.Confidence:       ${data.Beard.Confidence}`)
           console.log(`  Mustache.Value:         ${data.Mustache.Value}`)
           console.log(`  Mustache.Confidence:    ${data.Mustache.Confidence}`)
           console.log(`  EyesOpen.Value:         ${data.EyesOpen.Value}`)
           console.log(`  EyesOpen.Confidence:    ${data.EyesOpen.Confidence}`)
           console.log(`  MouthOpen.Value:        ${data.MouthOpen.Value}`)
           console.log(`  MouthOpen.Confidence:   ${data.MouthOpen.Confidence}`)
           console.log(`  Emotions[0].Type:       ${data.Emotions[0].Type}`)
           console.log(`  Emotions[0].Confidence: ${data.Emotions[0].Confidence}`)
           console.log(`  Landmarks[0].Type:      ${data.Landmarks[0].Type}`)
           console.log(`  Landmarks[0].X:         ${data.Landmarks[0].X}`)
           console.log(`  Landmarks[0].Y:         ${data.Landmarks[0].Y}`)
           console.log(`  Pose.Roll:              ${data.Pose.Roll}`)
           console.log(`  Pose.Yaw:               ${data.Pose.Yaw}`)
           console.log(`  Pose.Pitch:             ${data.Pose.Pitch}`)
           console.log(`  Quality.Brightness:     ${data.Quality.Brightness}`)
           console.log(`  Quality.Sharpness:      ${data.Quality.Sharpness}`)
           console.log(`  Confidence:             ${data.Confidence}`)
           console.log("------------")
           console.log("")
         }) // for response.faceDetails
       } // if
     });
   ```

------

## DetectFaces 操作要求
<a name="detectfaces-request"></a>

`DetectFaces` 的輸入是映像。在此範例中，映像是從 Amazon S3 儲存貯體載入的。`Attributes` 參數指定所有臉部屬性應該要傳回。如需詳細資訊，請參閱 [使用映像](images.md)。

```
{
    "Image": {
        "S3Object": {
            "Bucket": "amzn-s3-demo-bucket",
            "Name": "input.jpg"
        }
    },
    "Attributes": [
        "ALL"
    ]
}
```

## DetectFaces 操作回應
<a name="detectfaces-response"></a>

 `DetectFaces` 針對每個偵測到的臉孔傳回以下資訊：


+ **週框方塊**：人臉周圍的週框方塊座標。
+ **可信度**：週框方塊包含人臉的可信度。
+ **人臉特徵點**：人臉特徵點的陣列。對於每個特徵點 (例如左眼、右眼與嘴巴)，回應均會提供 x 和 y 座標。
+ **人臉屬性**：一組人臉屬性，例如人臉是否被遮擋，以 `FaceDetail` 的物件形式傳回。該組合包括：年齡範圍、絡腮鬍、表情、目視方向、眼鏡、眼睛張開、人臉遮擋、性別、嘴巴張開、八字胡、微笑和太陽鏡。對於每個這類屬性，該回應均會提供一個值。該值的類型可能不同，例如布林值類型 (此人是否戴著太陽眼鏡) 或字串類型 (此人是男性或女性) 或 (眼睛注視方向的俯仰/偏移) 的角度值類型。此外，對於大部分屬性，該回應也會提供偵測到之屬性值的可信度。請注意，雖然使用 `DetectFaces` 時支援人臉遮擋和目視方向屬性，但使用 `StartFaceDetection` 和 `GetFaceDetection` 分析視訊時不支援這些屬性。
+ **畫質**：描述人臉的亮度與銳利度。如需盡可能確保最佳臉部偵測的資訊，請參閱 [人臉比較輸入映像的建議](recommendations-facial-input-images.md)。
+ **姿態**：描述映像內人臉的旋轉。

要求可以描繪您想要傳回的人臉屬性陣列。人臉屬性的 `DEFAULT` 子集：始終傳回 `BoundingBox` `Confidence`、`Pose`、`Quality` 和 `Landmarks`。您可以請求傳回特定的人臉屬性 (除了預設清單)，透過使用 `["DEFAULT", "FACE_OCCLUDED", "EYE_DIRECTION"]` 或僅使用一個屬性，例如 `["FACE_OCCLUDED"]`。您可以使用 `["ALL"]` 要求所有人臉屬性。要求更多屬性可能會增加回應時間。

以下是 `DetectFaces` API 呼叫的回應範例。

```
{
  "FaceDetails": [
    {
      "BoundingBox": {
        "Width": 0.7919622659683228,
        "Height": 0.7510867118835449,
        "Left": 0.08881539851427078,
        "Top": 0.151064932346344
      },
      "AgeRange": {
        "Low": 18,
        "High": 26
      },
      "Smile": {
        "Value": false,
        "Confidence": 89.77348327636719
      },
      "Eyeglasses": {
        "Value": true,
        "Confidence": 99.99996948242188
      },
      "Sunglasses": {
        "Value": true,
        "Confidence": 93.65237426757812
      },
      "Gender": {
        "Value": "Female",
        "Confidence": 99.85968780517578
      },
      "Beard": {
        "Value": false,
        "Confidence": 77.52591705322266
      },
      "Mustache": {
        "Value": false,
        "Confidence": 94.48904418945312
      },
      "EyesOpen": {
        "Value": true,
        "Confidence": 98.57169342041016
      },
      "MouthOpen": {
        "Value": false,
        "Confidence": 74.33953094482422
      },
      "Emotions": [
        {
          "Type": "SAD",
          "Confidence": 65.56403350830078
        },
        {
          "Type": "CONFUSED",
          "Confidence": 31.277774810791016
        },
        {
          "Type": "DISGUSTED",
          "Confidence": 15.553778648376465
        },
        {
          "Type": "ANGRY",
          "Confidence": 8.012762069702148
        },
        {
          "Type": "SURPRISED",
          "Confidence": 7.621500015258789
        },
        {
          "Type": "FEAR",
          "Confidence": 7.243380546569824
        },
        {
          "Type": "CALM",
          "Confidence": 5.8196024894714355
        },
        {
          "Type": "HAPPY",
          "Confidence": 2.2830512523651123
        }
      ],
      "Landmarks": [
        {
          "Type": "eyeLeft",
          "X": 0.30225440859794617,
          "Y": 0.41018882393836975
        },
        {
          "Type": "eyeRight",
          "X": 0.6439348459243774,
          "Y": 0.40341562032699585
        },
        {
          "Type": "mouthLeft",
          "X": 0.343580037355423,
          "Y": 0.6951127648353577
        },
        {
          "Type": "mouthRight",
          "X": 0.6306480765342712,
          "Y": 0.6898072361946106
        },
        {
          "Type": "nose",
          "X": 0.47164231538772583,
          "Y": 0.5763645172119141
        },
        {
          "Type": "leftEyeBrowLeft",
          "X": 0.1732882857322693,
          "Y": 0.34452149271965027
        },
        {
          "Type": "leftEyeBrowRight",
          "X": 0.3655243515968323,
          "Y": 0.33231860399246216
        },
        {
          "Type": "leftEyeBrowUp",
          "X": 0.2671719491481781,
          "Y": 0.31669262051582336
        },
        {
          "Type": "rightEyeBrowLeft",
          "X": 0.5613729953765869,
          "Y": 0.32813435792922974
        },
        {
          "Type": "rightEyeBrowRight",
          "X": 0.7665090560913086,
          "Y": 0.3318614959716797
        },
        {
          "Type": "rightEyeBrowUp",
          "X": 0.6612788438796997,
          "Y": 0.3082450032234192
        },
        {
          "Type": "leftEyeLeft",
          "X": 0.2416982799768448,
          "Y": 0.4085965156555176
        },
        {
          "Type": "leftEyeRight",
          "X": 0.36943578720092773,
          "Y": 0.41230902075767517
        },
        {
          "Type": "leftEyeUp",
          "X": 0.29974061250686646,
          "Y": 0.3971870541572571
        },
        {
          "Type": "leftEyeDown",
          "X": 0.30360740423202515,
          "Y": 0.42347756028175354
        },
        {
          "Type": "rightEyeLeft",
          "X": 0.5755768418312073,
          "Y": 0.4081145226955414
        },
        {
          "Type": "rightEyeRight",
          "X": 0.7050536870956421,
          "Y": 0.39924031496047974
        },
        {
          "Type": "rightEyeUp",
          "X": 0.642906129360199,
          "Y": 0.39026668667793274
        },
        {
          "Type": "rightEyeDown",
          "X": 0.6423097848892212,
          "Y": 0.41669243574142456
        },
        {
          "Type": "noseLeft",
          "X": 0.4122826159000397,
          "Y": 0.5987403392791748
        },
        {
          "Type": "noseRight",
          "X": 0.5394935011863708,
          "Y": 0.5960900187492371
        },
        {
          "Type": "mouthUp",
          "X": 0.478581964969635,
          "Y": 0.6660456657409668
        },
        {
          "Type": "mouthDown",
          "X": 0.483366996049881,
          "Y": 0.7497162818908691
        },
        {
          "Type": "leftPupil",
          "X": 0.30225440859794617,
          "Y": 0.41018882393836975
        },
        {
          "Type": "rightPupil",
          "X": 0.6439348459243774,
          "Y": 0.40341562032699585
        },
        {
          "Type": "upperJawlineLeft",
          "X": 0.11031254380941391,
          "Y": 0.3980775475502014
        },
        {
          "Type": "midJawlineLeft",
          "X": 0.19301874935626984,
          "Y": 0.7034031748771667
        },
        {
          "Type": "chinBottom",
          "X": 0.4939905107021332,
          "Y": 0.8877836465835571
        },
        {
          "Type": "midJawlineRight",
          "X": 0.7990140914916992,
          "Y": 0.6899225115776062
        },
        {
          "Type": "upperJawlineRight",
          "X": 0.8548634648323059,
          "Y": 0.38160091638565063
        }
      ],
      "Pose": {
        "Roll": -5.83309268951416,
        "Yaw": -2.4244730472564697,
        "Pitch": 2.6216139793395996
      },
      "Quality": {
        "Brightness": 96.16363525390625,
        "Sharpness": 95.51618957519531
      },
      "Confidence": 99.99872589111328,
      "FaceOccluded": {
        "Value": true,
        "Confidence": 99.99726104736328
      },
      "EyeDirection": {
        "Yaw": 16.299732,
        "Pitch": -6.407457,
        "Confidence": 99.968704
      }
    }
  ],
  "ResponseMetadata": {
    "RequestId": "8bf02607-70b7-4f20-be55-473fe1bba9a2",
    "HTTPStatusCode": 200,
    "HTTPHeaders": {
      "x-amzn-requestid": "8bf02607-70b7-4f20-be55-473fe1bba9a2",
      "content-type": "application/x-amz-json-1.1",
      "content-length": "3409",
      "date": "Wed, 26 Apr 2023 20:18:50 GMT"
    },
    "RetryAttempts": 0
  }
}
```

注意下列事項：
+ `Pose` 資料描述偵測到之臉部的旋轉。您可以使用 `BoundingBox` 與 `Pose` 資料的組合，在您的應用程式所顯示的臉部周圍繪製週框方塊。
+ `Quality` 描述臉部的亮度與銳利度。您可能會發現這有助於在映像之間比較人臉，並找出最佳人臉。
+ 上述回應顯示服務可偵測到的所有臉部 `landmarks`、所有臉部屬性與情緒。若要在回應中取得所有專案，您必須將 `attributes` 參數的值指定為 `ALL`。根據預設，`DetectFaces` API 只會傳回下列五個臉部屬性：`BoundingBox`、`Confidence`、`Pose`、`Quality` 和 `landmarks`。傳回的預設特徵點如下：`eyeLeft`、`eyeRight`、`nose`、`mouthLeft` 和 `mouthRight`。

  

# 比較映像中的人臉
<a name="faces-comparefaces"></a>

使用 Rekognition，您可以使用 [CompareFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CompareFaces.html) 操作在兩個影像之間比較臉部。此功能適用於身分驗證或相片比對等應用程式。

CompareFaces 會將*來源*影像中的臉部與*目標*影像中的每個臉部進行比較。影像會以下列其中一種方式傳遞至 CompareFaces：
+ 影像的 base64 編碼表示法。
+ Amazon S3 物件。

**臉部偵測與臉部比較 **

臉部比較與臉部偵測不同。臉部偵測 （使用 DetectFaces) 只會識別影像或影片中臉部的存在和位置。相反地，臉部比較涉及將來源影像中偵測到的臉部與目標影像中的臉部進行比較，以尋找相符項目。

**相似性閾值**

使用 `similarityThreshold` 參數來定義要包含在回應中相符項目的最低可信度層級。根據預設，回應中只會傳回相似度分數大於或等於 80% 的臉部。

**注意**  
`CompareFaces` 使用機器學習演算法，這是概率性的。假陰性指的是不正確的預測，指出目標映像中的人臉與來源映像中的人臉相比具有較低的相似度置信度分數。為了減少偽陰性的可能性，建議您將目標映像與多個來源映像進行比較。如果您打算使用 `CompareFaces` 做出會影響個人權利、隱私權或服務存取權的決定，我們建議您在採取行動之前，將結果傳遞給人員進行審查並進一步驗證。

 

下列程式碼範例示範如何針對各種 AWS SDKs 使用 CompareFaces 操作。在此 AWS CLI 範例中，您會將兩個 JPEG 影像上傳至 Amazon S3 儲存貯體，並指定物件金鑰名稱。在其他範例中，您會從本機檔案系統載入兩個檔案，並以映像位元組陣列的方式加以輸入。

**比較臉部**

1. 如果您尚未執行：

   1. 建立或更新具有 `AmazonRekognitionFullAccess`和 `AmazonS3ReadOnlyAccess`（僅限AWS CLI 範例） 許可的使用者。如需詳細資訊，請參閱[步驟 1：設定 AWS 帳戶並建立使用者](setting-up.md#setting-up-iam)。

   1. 安裝和設定 AWS CLI 和 AWS SDKs。如需詳細資訊，請參閱[步驟 2：設定 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用下列程式碼範例來呼叫 `CompareFaces` 操作。

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

   此範例顯示有關來源和目標映像 (從本機檔案系統載入) 中相符臉孔的資訊。

   將 `sourceImage` 與 `targetImage` 的值取代為來源和目標映像的路徑和檔案名稱。

   ```
   //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 com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.BoundingBox;
   import com.amazonaws.services.rekognition.model.CompareFacesMatch;
   import com.amazonaws.services.rekognition.model.CompareFacesRequest;
   import com.amazonaws.services.rekognition.model.CompareFacesResult;
   import com.amazonaws.services.rekognition.model.ComparedFace;
   import java.util.List;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.InputStream;
   import java.nio.ByteBuffer;
   import com.amazonaws.util.IOUtils;
   
   public class CompareFaces {
   
      public static void main(String[] args) throws Exception{
          Float similarityThreshold = 70F;
          String sourceImage = "source.jpg";
          String targetImage = "target.jpg";
          ByteBuffer sourceImageBytes=null;
          ByteBuffer targetImageBytes=null;
   
          AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
          //Load source and target images and create input parameters
          try (InputStream inputStream = new FileInputStream(new File(sourceImage))) {
             sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
          }
          catch(Exception e)
          {
              System.out.println("Failed to load source image " + sourceImage);
              System.exit(1);
          }
          try (InputStream inputStream = new FileInputStream(new File(targetImage))) {
              targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
          }
          catch(Exception e)
          {
              System.out.println("Failed to load target images: " + targetImage);
              System.exit(1);
          }
   
          Image source=new Image()
               .withBytes(sourceImageBytes);
          Image target=new Image()
               .withBytes(targetImageBytes);
   
          CompareFacesRequest request = new CompareFacesRequest()
                  .withSourceImage(source)
                  .withTargetImage(target)
                  .withSimilarityThreshold(similarityThreshold);
   
          // Call operation
          CompareFacesResult compareFacesResult=rekognitionClient.compareFaces(request);
   
   
          // Display results
          List <CompareFacesMatch> faceDetails = compareFacesResult.getFaceMatches();
          for (CompareFacesMatch match: faceDetails){
            ComparedFace face= match.getFace();
            BoundingBox position = face.getBoundingBox();
            System.out.println("Face at " + position.getLeft().toString()
                  + " " + position.getTop()
                  + " matches with " + match.getSimilarity().toString()
                  + "% confidence.");
   
          }
          List<ComparedFace> uncompared = compareFacesResult.getUnmatchedFaces();
   
          System.out.println("There was " + uncompared.size()
               + " face(s) that did not match");
      }
   }
   ```

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

   此程式碼取自 AWS 文件開發套件範例 GitHub 儲存庫。請參閱[此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CompareFaces.java)的完整範例。

   ```
   import java.util.List;
   
   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.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.BoundingBox;
   import software.amazon.awssdk.services.rekognition.model.CompareFacesMatch;
   import software.amazon.awssdk.services.rekognition.model.CompareFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.CompareFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.ComparedFace;
   import software.amazon.awssdk.core.SdkBytes;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   
   // snippet-end:[rekognition.java2.detect_faces.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 CompareFaces {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <pathSource> <pathTarget>\n\n" +
               "Where:\n" +
               "   pathSource - The path to the source image (for example, C:\\AWS\\pic1.png). \n " +
               "   pathTarget - The path to the target image (for example, C:\\AWS\\pic2.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           Float similarityThreshold = 70F;
           String sourceImage = args[0];
           String targetImage = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           compareTwoFaces(rekClient, similarityThreshold, sourceImage, targetImage);
           rekClient.close();
      }
   
       // snippet-start:[rekognition.java2.compare_faces.main]
       public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, String targetImage) {
           try {
               InputStream sourceStream = new FileInputStream(sourceImage);
               InputStream tarStream = new FileInputStream(targetImage);
               SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
               SdkBytes targetBytes = SdkBytes.fromInputStream(tarStream);
   
               // Create an Image object for the source image.
               Image souImage = Image.builder()
                   .bytes(sourceBytes)
                   .build();
   
               Image tarImage = Image.builder()
                   .bytes(targetBytes)
                   .build();
   
               CompareFacesRequest facesRequest = CompareFacesRequest.builder()
                   .sourceImage(souImage)
                   .targetImage(tarImage)
                   .similarityThreshold(similarityThreshold)
                   .build();
   
               // Compare the two images.
               CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest);
               List<CompareFacesMatch> faceDetails = compareFacesResult.faceMatches();
               for (CompareFacesMatch match: faceDetails){
                   ComparedFace face= match.face();
                   BoundingBox position = face.boundingBox();
                   System.out.println("Face at " + position.left().toString()
                           + " " + position.top()
                           + " matches with " + face.confidence().toString()
                           + "% confidence.");
   
               }
               List<ComparedFace> uncompared = compareFacesResult.unmatchedFaces();
               System.out.println("There was " + uncompared.size() + " face(s) that did not match");
               System.out.println("Source image rotation: " + compareFacesResult.sourceImageOrientationCorrection());
               System.out.println("target image rotation: " + compareFacesResult.targetImageOrientationCorrection());
   
           } catch(RekognitionException | FileNotFoundException e) {
               System.out.println("Failed to load source image " + sourceImage);
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.compare_faces.main]
   }
   ```

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

   此範例顯示來自 `compare-faces` AWS CLI 操作的 JSON 輸出。

   將 `amzn-s3-demo-bucket` 取代為 Amazon S3 儲存貯體的名稱，其中包含來源和目標映像。將 `source.jpg` 和 `target.jpg` 取代為來源和目標映像的檔案名稱。

   ```
   aws rekognition compare-faces --target-image \
   "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"image-name"}}" \
   --source-image "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"image-name"}}" 
   --profile profile-name
   ```

    如果您在 Windows 裝置上存取 CLI，請使用雙引號而非單引號，並以反斜線 (即\$1) 替代內部雙引號，以解決您可能遇到的任何剖析器錯誤。例如，請參閱下列內容：

   ```
   aws rekognition compare-faces --target-image "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"image-name\"}}" \ 
   --source-image "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"image-name\"}}" --profile profile-name
   ```

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

   此範例顯示有關來源和目標映像 (從本機檔案系統載入) 中相符臉孔的資訊，表面載入在從本機檔案系統。

   將 `source_file` 與 `target_file` 的值取代為來源和目標映像的路徑和檔案名稱。將建立 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 compare_faces(sourceFile, targetFile):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       imageSource = open(sourceFile, 'rb')
       imageTarget = open(targetFile, 'rb')
   
       response = client.compare_faces(SimilarityThreshold=80,
                                       SourceImage={'Bytes': imageSource.read()},
                                       TargetImage={'Bytes': imageTarget.read()})
   
       for faceMatch in response['FaceMatches']:
           position = faceMatch['Face']['BoundingBox']
           similarity = str(faceMatch['Similarity'])
           print('The face at ' +
                 str(position['Left']) + ' ' +
                 str(position['Top']) +
                 ' matches with ' + similarity + '% confidence')
   
       imageSource.close()
       imageTarget.close()
       return len(response['FaceMatches'])
   
   def main():
       source_file = 'source-file-name'
       target_file = 'target-file-name'
       face_matches = compare_faces(source_file, target_file)
       print("Face matches: " + str(face_matches))
   
   if __name__ == "__main__":
       main()
   ```

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

   此範例顯示有關來源和目標映像 (從本機檔案系統載入) 中相符臉孔的資訊。

   將 `sourceImage` 與 `targetImage` 的值取代為來源和目標映像的路徑和檔案名稱。

   ```
   //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 CompareFaces
   {
       public static void Example()
       {
           float similarityThreshold = 70F;
           String sourceImage = "source.jpg";
           String targetImage = "target.jpg";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image();
           try
           {
               using (FileStream fs = new FileStream(sourceImage, FileMode.Open, FileAccess.Read))
               {
                   byte[] data = new byte[fs.Length];
                   fs.Read(data, 0, (int)fs.Length);
                   imageSource.Bytes = new MemoryStream(data);
               }
           }
           catch (Exception)
           {
               Console.WriteLine("Failed to load source image: " + sourceImage);
               return;
           }
   
           Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image();
           try
           {
               using (FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read))
               {
                   byte[] data = new byte[fs.Length];
                   data = new byte[fs.Length];
                   fs.Read(data, 0, (int)fs.Length);
                   imageTarget.Bytes = new MemoryStream(data);
               }
           }
           catch (Exception)
           {
               Console.WriteLine("Failed to load target image: " + targetImage);
               return;
           }
   
           CompareFacesRequest compareFacesRequest = new CompareFacesRequest()
           {
               SourceImage = imageSource,
               TargetImage = imageTarget,
               SimilarityThreshold = similarityThreshold
           };
   
           // Call operation
           CompareFacesResponse compareFacesResponse = rekognitionClient.CompareFaces(compareFacesRequest);
   
           // Display results
           foreach(CompareFacesMatch match in compareFacesResponse.FaceMatches)
           {
               ComparedFace face = match.Face;
               BoundingBox position = face.BoundingBox;
               Console.WriteLine("Face at " + position.Left
                     + " " + position.Top
                     + " matches with " + match.Similarity
                     + "% confidence.");
           }
   
           Console.WriteLine("There was " + compareFacesResponse.UnmatchedFaces.Count + " face(s) that did not match");
   
       }
   }
   ```

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

   此範例顯示有關來源和目標映像 (從本機檔案系統載入) 中相符臉孔的資訊，表面載入在從本機檔案系統。

   將 `photo_source` 與 `photo_target` 的值取代為來源和目標映像的路徑和檔案名稱。

   ```
     # 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 bucketname without s3://
      photo_source  = 'source.jpg'
      photo_target  = 'target.jpg'
      client   = Aws::Rekognition::Client.new credentials: credentials
      attrs = {
        source_image: {
          s3_object: {
            bucket: bucket,
            name: photo_source
          },
        },
        target_image: {
          s3_object: {
            bucket: bucket,
            name: photo_target
          },
        },
        similarity_threshold: 70
      }
      response = client.compare_faces attrs
      response.face_matches.each do |face_match|
        position   = face_match.face.bounding_box
        similarity = face_match.similarity
        puts "The face at: #{position.left}, #{position.top} matches with #{similarity} % confidence"
      end
   ```

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

   此範例顯示有關來源和目標映像 (從本機檔案系統載入) 中相符臉孔的資訊，表面載入在從本機檔案系統。

   將 `photo_source` 與 `photo_target` 的值取代為來源和目標映像的路徑和檔案名稱。將建立 Rekognition 工作階段的行中 `profile_name` 值取代為您開發人員設定檔的名稱。

   ```
   // Load the SDK
   var AWS = require('aws-sdk');
   const bucket = 'bucket-name' // the bucket name without s3://
   const photo_source  = 'photo-source-name' // path and the name of file
   const photo_target = 'photo-target-name'
   
   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 = {
        SourceImage: {
          S3Object: {
            Bucket: bucket,
            Name: photo_source
          },
        },
        TargetImage: {
          S3Object: {
            Bucket: bucket,
            Name: photo_target
          },
        },
        SimilarityThreshold: 70
      }
      client.compareFaces(params, function(err, response) {
        if (err) {
          console.log(err, err.stack); // an error occurred
        } else {
          response.FaceMatches.forEach(data => {
            let position   = data.Face.BoundingBox
            let similarity = data.Similarity
            console.log(`The face at: ${position.Left}, ${position.Top} matches with ${similarity} % confidence`)
          }) // for response.faceDetails
        } // if
      });
   ```

------

## CompareFaces 操作要求
<a name="comparefaces-request"></a>

`CompareFaces` 的輸入是映像。在此範例中，來源和目標映像從本機檔案系統載入。`SimilarityThreshold` 輸入參數指定比較臉孔必須符合的最低可信度應包含在回應中。如需詳細資訊，請參閱 [使用映像](images.md)。

```
{
    "SourceImage": {
        "Bytes": "/9j/4AAQSk2Q==..."
    },
    "TargetImage": {
        "Bytes": "/9j/4O1Q==..."
    },
    "SimilarityThreshold": 70
}
```

## CompareFaces 操作回應
<a name="comparefaces-response"></a>

回應包括：
+ 臉部比對的陣列：每個比對臉部具有相似度分數和中繼資料的相符臉部清單。如果多個臉部相符， `faceMatches`

   陣列包含所有臉部配對。
+ 臉部配對詳細資訊：每個配對的臉部也提供週框方塊、可信度值、指標位置和相似度分數。
+ 不相符的臉部清單：回應也包含目標影像中不符合來源影像臉部的臉部。包含每個不相符臉部的週框方塊。
+ 來源臉部資訊：包括用於比較之來源影像的臉部相關資訊，包括週框方塊和可信度值。

此範例顯示在目標影像中找到一個臉部相符項目。對於該相符的人臉，該回應會提供週框方塊與可信度值 (Amazon Rekognition 對週框方塊包含人臉的可信度)。99.99 的相似度分數表示臉部的相似度。此範例也顯示 Amazon Rekognition 在目標映像中找到的臉部與來源映像中分析的臉部不相符。

```
{
    "FaceMatches": [{
        "Face": {
            "BoundingBox": {
                "Width": 0.5521978139877319,
                "Top": 0.1203877404332161,
                "Left": 0.23626373708248138,
                "Height": 0.3126954436302185
            },
            "Confidence": 99.98751068115234,
            "Pose": {
                "Yaw": -82.36799621582031,
                "Roll": -62.13221740722656,
                "Pitch": 0.8652129173278809
            },
            "Quality": {
                "Sharpness": 99.99880981445312,
                "Brightness": 54.49755096435547
            },
            "Landmarks": [{
                    "Y": 0.2996366024017334,
                    "X": 0.41685718297958374,
                    "Type": "eyeLeft"
                },
                {
                    "Y": 0.2658946216106415,
                    "X": 0.4414493441581726,
                    "Type": "eyeRight"
                },
                {
                    "Y": 0.3465650677680969,
                    "X": 0.48636093735694885,
                    "Type": "nose"
                },
                {
                    "Y": 0.30935320258140564,
                    "X": 0.6251809000968933,
                    "Type": "mouthLeft"
                },
                {
                    "Y": 0.26942989230155945,
                    "X": 0.6454493403434753,
                    "Type": "mouthRight"
                }
            ]
        },
        "Similarity": 100.0
    }],
    "SourceImageOrientationCorrection": "ROTATE_90",
    "TargetImageOrientationCorrection": "ROTATE_90",
    "UnmatchedFaces": [{
        "BoundingBox": {
            "Width": 0.4890109896659851,
            "Top": 0.6566604375839233,
            "Left": 0.10989011079072952,
            "Height": 0.278298944234848
        },
        "Confidence": 99.99992370605469,
        "Pose": {
            "Yaw": 51.51519012451172,
            "Roll": -110.32493591308594,
            "Pitch": -2.322134017944336
        },
        "Quality": {
            "Sharpness": 99.99671173095703,
            "Brightness": 57.23163986206055
        },
        "Landmarks": [{
                "Y": 0.8288310766220093,
                "X": 0.3133862614631653,
                "Type": "eyeLeft"
            },
            {
                "Y": 0.7632885575294495,
                "X": 0.28091415762901306,
                "Type": "eyeRight"
            },
            {
                "Y": 0.7417283654212952,
                "X": 0.3631140887737274,
                "Type": "nose"
            },
            {
                "Y": 0.8081989884376526,
                "X": 0.48565614223480225,
                "Type": "mouthLeft"
            },
            {
                "Y": 0.7548204660415649,
                "X": 0.46090251207351685,
                "Type": "mouthRight"
            }
        ]
    }],
    "SourceImageFace": {
        "BoundingBox": {
            "Width": 0.5521978139877319,
            "Top": 0.1203877404332161,
            "Left": 0.23626373708248138,
            "Height": 0.3126954436302185
        },
        "Confidence": 99.98751068115234
    }
}
```

# 偵測已存放影片中的人臉
<a name="faces-sqs-video"></a>

Amazon Rekognition Video 可以偵測存放在 Amazon S3 儲存貯體之影片中的人臉，並提供下列資訊：
+ 在影片中偵測到臉部的次數。
+ 偵測到臉部時臉部在影片影格中的位置。
+ 臉部特徵點，例如左眼的位置。
+ 其他屬性，如 [人臉屬性的準則](guidance-face-attributes.md) 頁面上所述。

Amazon Rekognition Video 已儲存影片中的人臉偵測是一項非同步操作。若要開始在影片中偵測人臉，請呼叫 [StartFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceDetection.html)。Amazon Rekognition Video 會將影片分析的完成状态发布至 Amazon Simple Notification Service (Amazon SNS) 主题。如果影片分析成功，您可以呼叫 [GetFaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GetFaceDetection.html) 取得影片分析的結果。如需開始影片分析並取得結果的詳細資訊，請參閱 [呼叫 Amazon Rekognition Video 操作](api-video.md)。

此程序會展開 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md) 中的程式碼，該操作使用 Amazon Simple Queue Service (Amazon SQS) 佇列來取得影片分析要求的完成狀態。

**偵測存放在 Amazon S3 儲存貯體 (SDK) 之影片中的人臉**

1. 執行 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md)。

1. 將下列程式碼新增至您在步驟 1 中建立的類別 `VideoDetect`。

------
#### [ AWS CLI ]
   + 在以下程式碼範例中，將 `amzn-s3-demo-bucket` 與 `video-name` 變更為您在步驟 2 中指定的 Amazon S3 儲存貯體與文檔名稱。
   + 將 `region-name` 變更為您正在使用的 AWS 區域。使用您開發人員設定檔的名稱取代 `profile_name` 的值。
   + 將 `TopicARN` 變更為您在 [設定 Amazon Rekognition Video](api-video-roles.md) 步驟 3 建立的 Amazon SNS 主題 ARN。
   + 將 `RoleARN` 變更為您在步驟 7 建立的 [設定 Amazon Rekognition Video](api-video-roles.md) IAM 服務角色的 ARN。

   ```
   aws rekognition start-face-detection --video "{"S3Object":{"Bucket":"amzn-s3-demo-bucket","Name":"Video-Name"}}" --notification-channel
   "{"SNSTopicArn":"Topic-ARN","RoleArn":"Role-ARN"}" --region region-name --profile profile-name
   ```

   如果您在 Windows 裝置上存取 CLI，請使用雙引號而非單引號，並以反斜線 (即\$1) 替代內部雙引號，以解決您可能遇到的任何剖析器錯誤。例如，請參閱下列內容：

   ```
   aws rekognition start-face-detection --video "{\"S3Object\":{\"Bucket\":\"amzn-s3-demo-bucket\",\"Name\":\"Video-Name\"}}" --notification-channel
   "{\"SNSTopicArn\":\"Topic-ARN\",\"RoleArn\":\"Role-ARN\"}" --region region-name --profile profile-name
   ```

   執行 `StartFaceDetection` 操作，並取得工作 ID 編號之後，請執行下列 `GetFaceDetection` 作業並提供工作 ID 號碼：

   ```
   aws rekognition get-face-detection --job-id job-id-number  --profile profile-name
   ```

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

   ```
   //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.)
   
   
   private static void StartFaceDetection(String bucket, String video) throws Exception{
            
       NotificationChannel channel= new NotificationChannel()
               .withSNSTopicArn(snsTopicArn)
               .withRoleArn(roleArn);
       
       StartFaceDetectionRequest req = new StartFaceDetectionRequest()
               .withVideo(new Video()
                       .withS3Object(new S3Object()
                           .withBucket(bucket)
                           .withName(video)))
               .withNotificationChannel(channel);
                           
                           
       
       StartFaceDetectionResult startLabelDetectionResult = rek.startFaceDetection(req);
       startJobId=startLabelDetectionResult.getJobId();
       
   } 
   
   private static void GetFaceDetectionResults() throws Exception{
       
       int maxResults=10;
       String paginationToken=null;
       GetFaceDetectionResult faceDetectionResult=null;
       
       do{
           if (faceDetectionResult !=null){
               paginationToken = faceDetectionResult.getNextToken();
           }
       
           faceDetectionResult = rek.getFaceDetection(new GetFaceDetectionRequest()
                .withJobId(startJobId)
                .withNextToken(paginationToken)
                .withMaxResults(maxResults));
       
           VideoMetadata videoMetaData=faceDetectionResult.getVideoMetadata();
               
           System.out.println("Format: " + videoMetaData.getFormat());
           System.out.println("Codec: " + videoMetaData.getCodec());
           System.out.println("Duration: " + videoMetaData.getDurationMillis());
           System.out.println("FrameRate: " + videoMetaData.getFrameRate());
               
               
           //Show faces, confidence and detection times
           List<FaceDetection> faces= faceDetectionResult.getFaces();
        
           for (FaceDetection face: faces) { 
               long seconds=face.getTimestamp()/1000;
               System.out.print("Sec: " + Long.toString(seconds) + " ");
               System.out.println(face.getFace().toString());
               System.out.println();           
           }
       } while (faceDetectionResult !=null && faceDetectionResult.getNextToken() != null);
         
           
   }
   ```

   在函數 `main` 中，將下行: 

   ```
           StartLabelDetection(amzn-s3-demo-bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetLabelDetectionResults();
   ```

   取代為：

   ```
           StartFaceDetection(amzn-s3-demo-bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetFaceDetectionResults();
   ```

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

   此程式碼取自 AWS 文件開發套件範例 GitHub 儲存庫。請參閱[此處](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoDetectFaces.java)的完整範例。

   ```
   //snippet-start:[rekognition.java2.recognize_video_faces.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.*;
   import java.util.List;
   //snippet-end:[rekognition.java2.recognize_video_faces.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 VideoDetectFaces {
   
    private static String startJobId ="";
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <bucket> <video> <topicArn> <roleArn>\n\n" +
            "Where:\n" +
            "   bucket - The name of the bucket in which the video is located (for example, (for example, amzn-s3-demo-bucket). \n\n"+
            "   video - The name of video (for example, people.mp4). \n\n" +
            "   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic. \n\n" +
            "   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use. \n\n" ;
   
        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
   
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        NotificationChannel channel = NotificationChannel.builder()
            .snsTopicArn(topicArn)
            .roleArn(roleArn)
            .build();
   
        StartFaceDetection(rekClient, channel, bucket, video);
        GetFaceResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.recognize_video_faces.main]
    public static void StartFaceDetection(RekognitionClient rekClient,
                                          NotificationChannel channel,
                                          String bucket,
                                          String video) {
   
        try {
            S3Object s3Obj = S3Object.builder()
                .bucket(bucket)
                .name(video)
                .build();
   
            Video vidOb = Video.builder()
                .s3Object(s3Obj)
                .build();
   
            StartFaceDetectionRequest  faceDetectionRequest = StartFaceDetectionRequest.builder()
                .jobTag("Faces")
                .faceAttributes(FaceAttributes.ALL)
                .notificationChannel(channel)
                .video(vidOb)
                .build();
   
            StartFaceDetectionResponse startLabelDetectionResult = rekClient.startFaceDetection(faceDetectionRequest);
            startJobId=startLabelDetectionResult.jobId();
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
   
    public static void GetFaceResults(RekognitionClient rekClient) {
   
        try {
            String paginationToken=null;
            GetFaceDetectionResponse faceDetectionResponse=null;
            boolean finished = false;
            String status;
            int yy=0 ;
   
            do{
                if (faceDetectionResponse !=null)
                    paginationToken = faceDetectionResponse.nextToken();
   
                GetFaceDetectionRequest recognitionRequest = GetFaceDetectionRequest.builder()
                    .jobId(startJobId)
                    .nextToken(paginationToken)
                    .maxResults(10)
                    .build();
   
                // Wait until the job succeeds
                while (!finished) {
   
                    faceDetectionResponse = rekClient.getFaceDetection(recognitionRequest);
                    status = faceDetectionResponse.jobStatusAsString();
   
                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }
   
                finished = false;
   
                // Proceed when the job is done - otherwise VideoMetadata is null
                VideoMetadata videoMetaData=faceDetectionResponse.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");
   
                // Show face information
                List<FaceDetection> faces= faceDetectionResponse.faces();
   
                for (FaceDetection face: faces) {
                    String age = face.face().ageRange().toString();
                    String smile = face.face().smile().toString();
                    System.out.println("The detected face is estimated to be"
                                + age + " years old.");
                    System.out.println("There is a smile : "+smile);
                }
   
            } while (faceDetectionResponse !=null && faceDetectionResponse.nextToken() != null);
   
        } catch(RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.recognize_video_faces.main]
   }
   ```

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

   ```
   #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.)
   
       # ============== Faces===============
       def StartFaceDetection(self):
           response=self.rek.start_face_detection(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}},
               NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn})
   
           self.startJobId=response['JobId']
           print('Start Job Id: ' + self.startJobId)
   
       def GetFaceDetectionResults(self):
           maxResults = 10
           paginationToken = ''
           finished = False
   
           while finished == False:
               response = self.rek.get_face_detection(JobId=self.startJobId,
                                               MaxResults=maxResults,
                                               NextToken=paginationToken)
   
               print('Codec: ' + response['VideoMetadata']['Codec'])
               print('Duration: ' + str(response['VideoMetadata']['DurationMillis']))
               print('Format: ' + response['VideoMetadata']['Format'])
               print('Frame rate: ' + str(response['VideoMetadata']['FrameRate']))
               print()
   
               for faceDetection in response['Faces']:
                   print('Face: ' + str(faceDetection['Face']))
                   print('Confidence: ' + str(faceDetection['Face']['Confidence']))
                   print('Timestamp: ' + str(faceDetection['Timestamp']))
                   print()
   
               if 'NextToken' in response:
                   paginationToken = response['NextToken']
               else:
                   finished = True
   ```

   在函數 `main` 中，將下行: 

   ```
       analyzer.StartLabelDetection()
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetLabelDetectionResults()
   ```

   取代為：

   ```
       analyzer.StartFaceDetection()
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetFaceDetectionResults()
   ```

------
**注意**  
如果您已執行 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md) 以外的影片範例，要取代的函數名稱會不同。

1. 執行程式碼。影片中偵測到之臉部的資訊便會顯示。

## GetFaceDetection 操作回應
<a name="getfacedetection-operation-response"></a>

`GetFaceDetection` 會傳回陣列 (`Faces`)，其中包含影片中偵測到之臉孔的相關資訊。每當在影片中偵測到人臉時，就會有一個陣列元素 [FaceDetection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceDetection.html)。傳回的陣列元素會依從影片開頭起的時間 (以毫秒為單位) 順序排序。

下列範例是 `GetFaceDetection` 的部分 JSON 回應。在回應中，請注意下列事項：
+ **週框方塊**：人臉周圍的週框方塊座標。
+ **可信度**：週框方塊包含人臉的可信度。
+ **人臉特徵點**：人臉特徵點的陣列。對於每個特徵點 (例如左眼、右眼與嘴巴)，回應均會提供 `x` 和 `y` 座標。
+ **人臉屬性**：一組面部屬性，其中包括：年齡範圍、絡腮鬍、表情、目視方向、眼鏡、眼睛張開、人臉遮擋、性別、嘴巴張開、八字胡、微笑和太陽鏡。該值的類型可能不同，例如布林值類型 (此人是否戴著太陽眼鏡) 或字串 (此人是男性或女性)。此外，對於大部分屬性，該回應也會提供偵測到之屬性值的可信度。請注意，雖然使用 `DetectFaces` 時支援人臉遮擋和目視方向屬性，但使用 `StartFaceDetection` 和 `GetFaceDetection` 分析視訊時不支援這些屬性。
+ **時間戳記**：在影片中偵測到臉孔的時間。
+ **分頁資訊**：該範例顯示一頁人臉偵測資訊。您可以在 `GetFaceDetection` 的 `MaxResults` 輸入參數中指定要傳回的人物元素數目。如果結果數目超過 `MaxResults`，`GetFaceDetection` 會傳回用來取得下一頁結果的字符 (`NextToken`)。如需詳細資訊，請參閱 [取得 Amazon Rekognition Video 分析結果](api-video.md#api-video-get)。
+ **影片資訊**：回應包含 `GetFaceDetection` 所傳回之每頁資訊中影片格式 (`VideoMetadata`) 的相關資訊。
+ **畫質**：描述人臉的亮度與銳利度。
+ **姿態**：描述映像內人臉的旋轉角度。

```
{
    "Faces": [
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.23000000417232513,
                    "Left": 0.42500001192092896,
                    "Top": 0.16333332657814026,
                    "Width": 0.12937499582767487
                },
                "Confidence": 99.97504425048828,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.46415066719055176,
                        "Y": 0.2572723925113678
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.5068183541297913,
                        "Y": 0.23705792427062988
                    },
                    {
                        "Type": "nose",
                        "X": 0.49765899777412415,
                        "Y": 0.28383663296699524
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.487221896648407,
                        "Y": 0.3452930748462677
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.5142884850502014,
                        "Y": 0.33167609572410583
                    }
                ],
                "Pose": {
                    "Pitch": 15.966927528381348,
                    "Roll": -15.547388076782227,
                    "Yaw": 11.34195613861084
                },
                "Quality": {
                    "Brightness": 44.80223083496094,
                    "Sharpness": 99.95819854736328
                }
            },
            "Timestamp": 0
        },
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.20000000298023224,
                    "Left": 0.029999999329447746,
                    "Top": 0.2199999988079071,
                    "Width": 0.11249999701976776
                },
                "Confidence": 99.85971069335938,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.06842322647571564,
                        "Y": 0.3010137975215912
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.10543643683195114,
                        "Y": 0.29697132110595703
                    },
                    {
                        "Type": "nose",
                        "X": 0.09569807350635529,
                        "Y": 0.33701086044311523
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.0732642263174057,
                        "Y": 0.3757539987564087
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.10589495301246643,
                        "Y": 0.3722417950630188
                    }
                ],
                "Pose": {
                    "Pitch": -0.5589138865470886,
                    "Roll": -5.1093974113464355,
                    "Yaw": 18.69594955444336
                },
                "Quality": {
                    "Brightness": 43.052337646484375,
                    "Sharpness": 99.68138885498047
                }
            },
            "Timestamp": 0
        },
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.2177777737379074,
                    "Left": 0.7593749761581421,
                    "Top": 0.13333334028720856,
                    "Width": 0.12250000238418579
                },
                "Confidence": 99.63436889648438,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.8005779385566711,
                        "Y": 0.20915353298187256
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.8391435146331787,
                        "Y": 0.21049551665782928
                    },
                    {
                        "Type": "nose",
                        "X": 0.8191410899162292,
                        "Y": 0.2523227035999298
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.8093273043632507,
                        "Y": 0.29053622484207153
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.8366993069648743,
                        "Y": 0.29101791977882385
                    }
                ],
                "Pose": {
                    "Pitch": 3.165884017944336,
                    "Roll": 1.4182015657424927,
                    "Yaw": -11.151537895202637
                },
                "Quality": {
                    "Brightness": 28.910892486572266,
                    "Sharpness": 97.61507415771484
                }
            },
            "Timestamp": 0
        }.......

    ],
    "JobStatus": "SUCCEEDED",
    "NextToken": "i7fj5XPV/fwviXqz0eag9Ow332Jd5G8ZGWf7hooirD/6V1qFmjKFOQZ6QPWUiqv29HbyuhMNqQ==",
    "VideoMetadata": {
        "Codec": "h264",
        "DurationMillis": 67301,
        "FileExtension": "mp4",
        "Format": "QuickTime / MOV",
        "FrameHeight": 1080,
        "FrameRate": 29.970029830932617,
        "FrameWidth": 1920
    }
}
```