

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 얼굴을 사용자에 연결
<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 명령은 `associate-faces` CLI 작업을 사용하여 얼굴을 사용자와 연결합니다.

   ```
   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`에 요청을 제출한 후 작업을 완료하는 데 1분 정도 걸릴 수 있습니다.

이러한 이유로 다음과 같은 값을 가질 수 있는 UserStatus가 반환됩니다.
+ CREATED - 'User'가 성공적으로 생성되었으며 현재 연결된 얼굴이 없음을 나타냅니다. 'AssociateFaces' 직접 호출이 성공적으로 이루어지기 전에는 'User'가 이 상태에 있게 됩니다.
+ UPDATING - 'User'가 새로 연결되었거나 연결 해제된 얼굴을 반영하도록 업데이트되고 있으며 몇 초 후에 ACTIVE 상태가 될 것을 나타냅니다. 이 상태에서는 검색 결과에 'User'가 포함될 수 있으며 고객은 반환된 결과에서 해당 사용자를 무시하도록 선택할 수 있습니다.
+ ACTIVE - **'**User**'**가 연결되거나 연결 해제된 모든 얼굴을 반영하도록 업데이트되었으며 검색 가능한 상태임을 나타냅니다.

```
{
    "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"
        }
    ]
}
```