

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

# 將人臉與使用者產生關聯
<a name="associate-faces"></a>

您可以使用 [AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociatingFaces.html) 操作來將多個人臉與單一使用者關聯。若要將人臉與使用者建立關聯，必須先建立集合和使用者。請注意，人臉向量必須位於使用者向量所在的同一個集合中。

**若要關聯人臉 (SDK)**

1. 如果您尚未執行：

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

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

1. 使用下列範例來呼叫 `AssociateFaces` 操作。

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

   此 Java 程式碼範例將一個人臉與使用者相關聯。

   ```
   import java.util.Arrays;
   import java.util.List;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.AssociateFacesRequest;
   import com.amazonaws.services.rekognition.model.AssociateFacesResult;
   
   
   public class AssociateFaces {
   
       public static void main(String[] args) throws Exception {
   
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           /* Replace the below configurations to allow you successfully run the example
   
              @collectionId: The collection where user and faces are stored
              @userId: The user which faces will get associated to
              @faceIds: The list of face IDs that will get associated to the given user
              @userMatchThreshold: Minimum User match confidence required for the face to
                                  be associated with a User that has at least one faceID already associated
            */
   
           String collectionId = "MyCollection";
           String userId = "demoUser";
           String faceId1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
           String faceId2 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
           List<String> faceIds = Arrays.asList(faceid1,faceid2);
   
           float userMatchThreshold = 0f;
           System.out.println("Associating faces to the existing user: " +
                   userId);
   
           AssociateFacesRequest request = new AssociateFacesRequest()
                   .withCollectionId(collectionId)
                   .withUserId(userId)
                   .withFaceIds(faceIds)
                   .withUserMatchThreshold(userMatchThreshold);
   
           AssociateFacesResult result = rekognitionClient.associateFaces(request);
   
           System.out.println("Successful face associations: " + result.getAssociatedFaces().size());
           System.out.println("Unsuccessful face associations: " + result.getUnsuccessfulFaceAssociations().size());
       }
   
   }
   ```

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

   此 AWS CLI 命令會使用 CLI `associate-faces` 操作，將臉部與使用者建立關聯。

   ```
   aws rekognition associate-faces --user-id {{user-id}} --face-ids {{face-id-1}} {{face-id-2}}
   --collection-id {{collection-name}} 
   --region {{region-name}}
   ```

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

   這個 Python 程式碼範例將一個人臉與使用者相關聯。

   ```
   from botocore.exceptions import ClientError
   import boto3
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def associate_faces(collection_id, user_id, face_ids):
       """
       Associate stored faces within collection to the given user
   
       :param collection_id: The ID of the collection where user and faces are stored.
       :param user_id: The ID of the user that we want to associate faces to
       :param face_ids: The list of face IDs to be associated to the given user
   
       :return: response of AssociateFaces API
       """
       logger.info(f'Associating faces to user: {user_id}, {face_ids}')
       try:
           response = client.associate_faces(
               CollectionId=collection_id,
               UserId=user_id,
               FaceIds=face_ids
           )
           print(f'- associated {len(response["AssociatedFaces"])} faces')
       except ClientError:
           logger.exception("Failed to associate faces to the given user")
           raise
       else:
           print(response)
           return response
   
   def main():
       face_ids = ["faceId1", "faceId2"]
       collection_id = "collection-id"
       user_id = "user-id"
       associate_faces(collection_id, user_id, face_ids)
   
   if __name__ == "__main__":
       main()
   ```

------

## AssociateFaces 操作回應
<a name="associatefaces-operation-response"></a>

`AssociateFaces` 的回應包括 `UserStatus`，也就是解除關聯要求的狀態，以及要關聯的 `FaceIds` 清單。也會傳回 `UnsuccessfulFaceAssociations` 的清單。將請求提交給 `AssociateFaces` 之後，操作可能需要一分鐘左右的時間才能完成。

基於這個原因，UserStatus 會傳回，取值如下：
+ 已建立：表示「使用者」已成功建立，且目前沒有與其相關聯的任何人臉。在「AssociateFaces」的任何成功呼叫之前，「使用者」將處於此狀態。
+ 更新：表示「使用者」正在更新以反映新關聯/取消關聯的人臉，並在幾秒鐘內變為作用中狀態。此狀態下的搜尋結果可能包含「使用者」，客戶可以選擇從傳回的結果中忽略這些結果。
+ 作用中：表示****「使用者」****已更新，以反映所有關聯/已取消關聯的人臉，且處於可搜尋狀態。

```
{
    "UnsuccessfulFaceAssociations": [
        {
            "Reasons": [
                "LOW_MATCH_CONFIDENCE"
            ], 
            "FaceId": "f5817d37-94f6-0000-bfee-1a2b3c4d5e6f", 
            "Confidence": 0.9375374913215637
        }, 
        {
            "Reasons": [
                "ASSOCIATED_TO_A_DIFFERENT_IDENTITY"
            ], 
            "FaceId": "851cb847-dccc-1111-bfee-1a2b3c4d5e6f", 
            "UserId": "demoUser2"
        }
    ], 
    "UserStatus": "UPDATING", 
    "AssociatedFaces": [
        {
            "FaceId": "35ebbb41-7f67-2222-bfee-1a2b3c4d5e6f"
        }
    ]
}
```