

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

# 컬렉션에서 얼굴 검색
<a name="collections"></a>

Amazon Rekognition을 사용하면 입력된 얼굴을 사용하여 저장된 얼굴 컬렉션에서 일치하는 얼굴을 검색할 수 있습니다. 먼저 탐지된 얼굴에 대한 정보를 "컬렉션"이라는 서버 측 컨테이너에 저장합니다. 컬렉션에는 개별 얼굴과 사용자(동일한 사람의 여러 얼굴)가 모두 저장됩니다. 개별 얼굴은 (얼굴의 실제 이미지가 아닌) 얼굴을 수학적으로 표현한 얼굴 벡터로 저장됩니다. 동일한 사람의 다양한 이미지를 사용하여 동일한 컬렉션에 여러 개의 얼굴 벡터를 만들고 저장할 수 있습니다. 그런 다음 동일한 사람의 여러 얼굴 벡터를 집계하여 사용자 벡터를 만들 수 있습니다. 사용자 벡터는 여러 정도의 조명, 선명도, 포즈, 외양 등을 포함하는 보다 강력한 묘사를 통해 더 정확한 얼굴 검색을 제공할 수 있습니다.

컬렉션을 만든 후에는 입력된 얼굴을 사용하여 컬렉션에서 일치하는 사용자 벡터 또는 얼굴 벡터를 검색할 수 있습니다. 사용자 벡터를 기준으로 검색하면 개별 얼굴 벡터로 검색하는 것보다 정확도를 크게 향상시킬 수 있습니다. 이미지, 저장된 비디오 및 스트리밍 비디오에서 감지된 얼굴을 사용하여 저장된 얼굴 벡터를 검색할 수 있습니다. 이미지에서 감지된 얼굴을 사용하여 저장된 사용자 벡터를 검색할 수 있습니다.

얼굴 정보를 저장하려면 다음 과정을 수행해야 합니다.

1. 컬렉션 생성 - 얼굴 정보를 저장하려면 먼저 계정의 AWS 리전 중 하나에 얼굴 컬렉션을 생성([CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html))해야 합니다. `IndexFaces` 작업을 호출할 때 이 얼굴 모음을 지정합니다.

1. 얼굴 인덱싱 - [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 작업은 이미지에서 얼굴을 감지하고 얼굴 벡터를 추출하여 컬렉션에 저장합니다. 이 작업을 사용하여 이미지에서 얼굴을 감지하고, 감지된 얼굴 특징에 대한 정보를 모음으로 유지할 수 있습니다. 이것이 *스토리지 기반* API 작업의 예인 이유는 서비스가 얼굴 벡터 정보를 서버에 저장하기 때문입니다.

사용자를 생성하고 여러 개의 얼굴 벡터를 사용자와 연결하려면 다음 작업을 수행해야 합니다.

1. 사용자 생성 - 먼저 [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html)를 사용하여 사용자를 생성해야 합니다. 같은 인물의 여러 얼굴 벡터를 하나의 사용자 벡터로 집계하여 얼굴 일치의 정확도를 높일 수 있습니다. 최대 100개의 얼굴 벡터를 하나의 사용자 벡터와 연결할 수 있습니다.

1. 얼굴 연결 - 사용자를 생성한 후 [AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateFaces.html) 작업을 통해 기존 얼굴 벡터를 해당 사용자에 추가할 수 있습니다. 얼굴 벡터가 사용자 벡터와 연결되려면 해당 사용자 벡터와 같은 컬렉션에 있어야 합니다.

컬렉션을 생성하고 얼굴 및 사용자 벡터를 저장한 후에는 다음 작업을 사용하여 일치하는 얼굴을 검색할 수 있습니다.
+ [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) - 이미지에 있는 얼굴로 저장된 개별 얼굴을 검색합니다.
+ [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) - 제공된 얼굴 ID로 저장된 개별 얼굴을 검색합니다.
+ [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html) - 제공된 얼굴 ID 또는 사용자 ID를 사용하여 저장된 사용자를 검색합니다.
+ [SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html) - 이미지에 있는 얼굴로 저장된 사용자를 검색합니다.
+ [StartFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceSearch.html) - 저장된 비디오에서 얼굴을 검색합니다.
+ [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) - 스트리밍 비디오에서 얼굴을 검색합니다.

**참고**  
컬렉션에는 얼굴의 수학적 표현인 얼굴 벡터가 저장됩니다. 컬렉션에는 얼굴 이미지가 저장되지 않습니다.

다음 다이어그램은 컬렉션 사용 목표에 따른 직접 호출 작업의 순서를 보여줍니다.

**사용자 벡터와 최대 정확도로 매칭:**

![\[컬렉션에 사용자 얼굴 벡터를 저장하고 검색하는 것을 보여주는 다이어그램에는 CreateCollection, IndexFaces, CreateUser, AssociateFaces, SearchUsersByImage, SearchUsers와 같은 작업이 나열됩니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/uservectorsCollection.png)


**개별 얼굴 벡터와 높은 정확도로 매칭:**

![\[컬렉션에 얼굴을 저장하고 검색하는 것을 보여주는 다이어그램에는 CreateCollection, IndexFaces, StartFaceSearch, CreateStreamProcessor, SearchFacesByImage, SearchFaces와 같은 작업이 나열됩니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/facevectorsCollection.png)


여러 가지 일반적인 사용자 시나리오를 위한 자습서 모음. 예를 들어, `IndexFaces` 및 `AssociateFaces` 작업을 사용하여 스캔한 직원 배지 이미지와 정부에서 발급한 ID에서 탐지된 얼굴을 저장하는 얼굴 컬렉션을 만들 수 있습니다. 직원이 건물에 들어오면 직원 얼굴 이미지가 캡처되어 `SearchUsersByImage` 작업으로 전송됩니다. 얼굴 일치에서 충분히 높은 유사성 점수(가령 99%)가 나오면 직원을 인증할 수 있습니다.

# 얼굴 컬렉션, 얼굴 및 사용자 관리
<a name="managing-face-collections"></a>

 얼굴 컬렉션은 Amazon Rekognition에서 얼굴 및 사용자와 관련된 정보를 포함하는 데 사용하는 리소스입니다. 다양한 Rekognition API 작업을 사용하여 컬렉션 자체와 컬렉션에 저장된 얼굴 또는 얼굴 벡터를 관리합니다.

## 컬렉션 관리
<a name="managing-collections"></a>

얼굴 컬렉션은 기본 Amazon Rekognition 리소스이며, 생성되는 각각의 얼굴 컬렉션에는 고유의 Amazon 리소스 이름(ARN)이 있습니다. 계정의 특정 AWS 리전에서 각 얼굴 모음을 생성합니다. 모음을 만들면, 최신 버전의 얼굴 감지 모델에 연결됩니다. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.

컬렉션에서 다음 관리 작업을 수행할 수 있습니다.
+ [CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html)을 사용하여 컬렉션을 생성합니다. 자세한 내용은 [컬렉션 생성](create-collection-procedure.md) 단원을 참조하십시오.
+ [ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html)를 사용하여 사용 가능한 컬렉션을 조회합니다. 자세한 내용은 [컬렉션 나열](list-collection-procedure.md) 단원을 참조하십시오.
+ [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html)으로 컬렉션을 설명합니다. 자세한 내용은 [컬렉션 설명](describe-collection-procedure.md) 단원을 참조하십시오.
+ [DeleteCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteCollection.html)을 사용하여 컬렉션을 삭제합니다. 자세한 내용은 [컬렉션 삭제](delete-collection-procedure.md) 단원을 참조하십시오.

## 컬렉션에서 얼굴 관리
<a name="collections-index-faces"></a>

얼굴 컬렉션을 만든 후에는 그 안에 얼굴을 저장할 수 있습니다. Amazon Rekognition은 컬렉션의 얼굴 관리를 위해 다음 작업을 제공합니다.
+  [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 작업은 입력 이미지(JPEG 또는 PNG)에서 얼굴을 감지하여 지정된 얼굴 컬렉션에 추가합니다. 이미지에서 감지된 각 얼굴에 대해 고유한 얼굴 ID가 반환됩니다. 얼굴을 유지한 후 얼굴 모음에서 얼굴 일치를 검색할 수 있습니다. 자세한 내용은 [컬렉션에 얼굴 추가](add-faces-to-collection-procedure.md) 단원을 참조하십시오.
+ [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) 작업은 컬렉션에 있는 얼굴을 나열합니다. 자세한 내용은 [컬렉션에 얼굴 추가](add-faces-to-collection-procedure.md) 단원을 참조하십시오.
+ [DeleteFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteFaces.html) 작업은 컬렉션에서 얼굴을 삭제합니다. 자세한 내용은 [컬렉션에서 얼굴 삭제](delete-faces-procedure.md) 단원을 참조하십시오.

## 컬렉션의 사용자 관리
<a name="collections-manage-users"></a>

같은 사람의 얼굴 벡터를 여러 개 저장한 후에는 이러한 모든 얼굴 벡터를 하나의 사용자 벡터로 연결하여 정확도를 높일 수 있습니다. 다음 작업을 통해 사용자를 관리할 수 있습니다.
+ [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html) - 이 작업은 제공된 고유한 사용자 ID를 사용하여 컬렉션에 새 사용자를 생성합니다.
+ [AssociateUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateUsers.html) - 하나의 사용자 ID에 1\$1100개의 고유한 얼굴 ID를 추가합니다. 최소 한 개의 얼굴 ID를 사용자와 연결한 후에는 컬렉션에서 해당 사용자와 일치하는 항목을 검색할 수 있습니다.
+ [ListUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListUsers.html) - 컬렉션에 있는 사용자를 나열합니다.
+ [DeleteUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteUsers.html) - 제공된 사용자 ID를 이용하여 컬렉션에서 사용자를 삭제합니다.
+ [DisassociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DisassociateFaces.html) - 사용자로부터 하나 이상의 얼굴 ID를 제거합니다.

# 얼굴 연결 및 매칭을 위한 유사성 임곗값 사용
<a name="thresholds-collections"></a>

유사성 임곗값은 얼굴을 연결하고 일치시키는 데 사용됩니다. 다음은 두 사용 사례에 대해 유사성 임곗값을 사용하기 위한 지침입니다.

## 얼굴 연결을 위한 유사성 임계값 사용
<a name="thresholds-collections-associating-faces"></a>

[AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateFaces.html) 작업을 사용하여 얼굴을 연결할 때 사용자와 연결된 얼굴이 모두 동일한 사람인지 확인하는 것이 중요합니다. `UserMatchThreshold` 파라미터는 이를 돕기 위해 새 얼굴이 최소 하나 이상의 `FaceID`를 이미 포함하는 `UserID`와 연결될 때 필요한 최소 사용자 일치 신뢰도를 지정합니다. 이렇게 하면 `FaceIds`가 올바른 `UserID`와 연결되도록 할 수 있습니다. 이 값의 범위는 0\$1100이고 기본값은 75입니다.

## 유사성 임계값을 사용하여 얼굴 일치
<a name="thresholds-face-match-similarity"></a>

유사성 임계값을 입력 파라미터로 제공하여 모든 검색 작업([CompareFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CompareFaces.html), [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html), [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html), [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html), [SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html))의 결과를 제어할 수 있습니다.

`FaceMatchThreshold`는 `SearchFaces` 및 `SearchFacesByImage`에 대한 유사성 임계값 입력 속성이며 일치를 수행 중인 얼굴의 유사성에 따라 반환되는 결과의 수를 제어합니다. `SearchUsers` 및 `SearchUsersByImage`에 대한 유사성 임계값 입력 속성은 `UserMatchThreshold`이며 일치를 수행 중인 사용자 벡터의 유사성에 따라 반환되는 결과의 수를 제어합니다. `CompareFaces`의 임계값 속성은 `SimilarityThreshold`입니다.

`Similarity` 응답 속성 값이 임계값보다 낮은 응답은 반환되지 않습니다. 이 임계값은 일치 결과에 포함된 가양성의 수를 결정할 수 있기 때문에 사용 사례에 맞게 보정하기 위해 중요합니다. 이 값은 검색 결과의 재현율을 제어합니다. 임계값이 낮을수록 재현율은 높아집니다.

모든 기계 학습 시스템은 확률론적입니다. 사용 사례에 따라 적절한 유사성 임계값을 설정할 때에는 본인의 판단을 활용해야 합니다. 예를 들어 비슷하게 생긴 가족을 식별하는 포토 앱을 만들려는 경우 임계값을 낮게(예:80%) 선택할 수 있습니다. 반면, 많은 법 집행 사용 사례의 경우, 실수로 잘못 식별되는 경우를 줄이기 위해 99% 이상의 높은 임계값을 사용하는 것이 좋습니다.

`FaceMatchThreshold`와 `UserMatchThreshold` 외에, 실수로 잘못 식별되는 경우를 줄이기 위한 수단으로 `Similarity` 응답 속성을 사용할 수 있습니다. 예를 들어 낮은 임계값(80%)을 사용하기로 선택하여 더 많은 결과를 반환할 수 있습니다. 그런 다음 유사성 응답 속성(유사성의 정도 %)를 사용하여 선택 범위를 좁히고 해당 애플리케이션에서 올바른 응답을 필터링할 수 있습니다. 다시 유사성을 높이면(예: 99% 이상) 잘못된 식별이 줄어들 것입니다.

# 일반적인 시나리오에서 얼굴 인덱싱 지침
<a name="guidance-index-faces"></a>

다음은 일반적인 시나리오에서 `IndexFaces`를 사용하기 위한 지침입니다.

## 중요 또는 공공 안전 애플리케이션
<a name="guidance-index-faces-critical"></a>
+ 각 이미지에 얼굴이 하나씩만 포함된 이미지를 사용하여 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html)를 직접 호출하고 반환된 얼굴 ID를 이미지 내 인물의 식별자와 연결합니다.
+ 인덱싱 전에 [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html)를 사용하여 이미지에 얼굴이 하나뿐인지 확인할 수 있습니다. 얼굴이 여러 개 감지된 경우 검토 후 얼굴이 하나만 있는 이미지를 다시 제출합니다. 이는 잘못하여 복수의 얼굴을 인덱싱하고 같은 사람에 연결하는 것을 방지합니다.

## 사진 공유 및 소셜 미디어 애플리케이션
<a name="guidance-index-faces-social"></a>
+ 가족 앨범과 같은 사용 사례에서는 여러 얼굴이 포함된 이미지에 대한 제한 없이 `IndexFaces`를 호출해야 합니다. 이런 경우, 모든 사진에서 각 개인을 식별하고 해당 정보를 사용하여 사진 안의 사람들에 따라 사진을 그룹화해야 합니다.

## 일반 사용 사례
<a name="guidance-index-faces-general"></a>
+ 같은 사람의 여러 이미지, 특히 다양한 얼굴 속성(얼굴 포즈, 얼굴의 털 등)을 가진 이미지를 인덱싱하고 사용자를 생성하여 해당 사용자와 다양한 얼굴을 연결함으로써 일치 품질을 개선하세요.
+ 실패한 일치를 올바른 얼굴 식별자로 인덱싱하여 이후의 얼굴 일치 기능을 개선할 수 있도록 검토 프로세스를 포함시킵니다.
+ 이미지 품질에 대한 자세한 내용은 [얼굴 비교 입력 이미지에 대한 권장 사항](recommendations-facial-input-images.md) 단원을 참조하십시오.

# 컬렉션 내의 얼굴 및 사용자 검색
<a name="collections-search-faces"></a>

얼굴 컬렉션을 만들고 얼굴 벡터 및/또는 사용자 벡터를 저장한 후에는 얼굴 컬렉션에서 얼굴 일치를 검색할 수 있습니다. Amazon Rekognition에서는 다음과 일치하는 얼굴을 컬렉션에서 검색할 수 있습니다.
+ 제공된 얼굴 ID([SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html)). 자세한 내용은 [얼굴 ID로 얼굴 검색](search-face-with-id-procedure.md) 단원을 참조하십시오.
+ 제공된 이미지 내에서 가장 큰 얼굴([SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html)). 자세한 내용은 [이미지를 사용하여 얼굴 검색](search-face-with-image-procedure.md) 단원을 참조하십시오.
+ 저장된 비디오의 얼굴. 자세한 내용은 [저장된 비디오에서 얼굴 검색](procedure-person-search-videos.md) 단원을 참조하십시오.
+ 스트리밍 비디오의 얼굴. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

`CompareFaces` 작업을 사용해 원본 이미지의 얼굴과 대상 이미지의 얼굴을 비교할 수 있습니다. 이 비교의 범위는 대상 이미지에서 감지된 얼굴로 제한됩니다. 자세한 내용은 [이미지에 있는 얼굴 비교](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)를 참조하세요.

다음 목록에 나와 있는 다양한 검색 작업은 특정 얼굴(`FaceId` 또는 입력 이미지로 식별됨)을 지정된 얼굴 컬렉션에 저장된 모든 얼굴과 비교합니다.
+ [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html)
+ [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html)
+ [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html)
+ [SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html)

# 공공 안전 관련 사용 사례
<a name="considerations-public-safety-use-cases"></a>

 공공 안전과 관련된 사용 사례에서 얼굴 감지 및 비교 시스템을 배포하는 경우 [센서, 입력 이미지 및 비디오 모범 사례](best-practices.md) 및 [일반적인 시나리오에서 얼굴 인덱싱 지침](guidance-index-faces.md)에 나열된 권장 사항 이외에 다음 모범 사례를 따라야 합니다. 첫째, 오류 및 오탐을 줄이기 위해 99% 이상의 신뢰도 임계값을 사용해야 합니다. 둘째, 인간 검토자가 얼굴 감지 또는 비교 시스템이 제공한 결과를 확인해야 하며, 인간에 의한 추가 검토 없이 시스템 출력에 기반하여 의사 결정을 하면 안 됩니다. 얼굴 감지 및 비교 시스템은 검토 범위를 좁혀 인간 작업자가 신속하게 검토하고 옵션을 고려할 수 있게 해주는 도구로 사용해야 합니다. 셋째, 가능할 경우 최종 사용자 및 피사 인물에게 이러한 시스템의 사용을 고지하고, 사용에 대한 동의를 얻고, 최종 사용자 및 피사 인물이 시스템 개선을 위한 피드백을 제공할 수 있는 메커니즘을 제공하는 등 이러한 사용 사례에서 얼굴 감지 및 비교 시스템을 투명하게 사용해야 합니다.

 귀하가 범죄 수사와 관련하여 Amazon Rekognition 얼굴 비교 기능을 사용하는 법 집행 기관인 경우 [AWS 서비스 약관](https://aws.amazon.com/service-terms/)에 명시된 요구 사항을 준수해야 합니다. 다음 내용이 해당됩니다.
+ 적절한 교육을 받은 사람이 개인의 시민적 자유 또는 동등한 인권에 영향을 줄 수 있는 조치를 취하기 위해 모든 결정을 검토합니다.
+ 얼굴 인식 시스템의 책임 있는 사용에 대해 직원을 교육합니다.
+ 얼굴 인식 시스템 사용에 대한 공개 정보를 제공합니다.
+ 독립적인 검토가 없거나 급박한 상황이 아닌 경우 개인의 지속적인 감시에 Amazon Rekognition을 사용해서는 안 됩니다.

얼굴 비교 일치 결과는 항상 다른 결정적인 증거와 함께 고려되어야 하며 조치를 취할 때 유일한 결정 요인으로 사용되어서는 안 됩니다. 하지만 얼굴 비교가 법 집행과 무관한 상황에서 사용될 경우(예: 전화를 잠금 해제하거나 보안 시스템이 적용된 개인 건물에 액세스하기 위해 피고용인의 ID를 인증하는 경우), 개인의 시민적 자유 또는 동등한 인권에 영향을 미치지 않으므로 이러한 결정을 내릴 때 수동 감사가 필요하지 않습니다.

공공 안전과 관련된 사용 사례에서 얼굴 감지 또는 얼굴 비교 시스템을 사용하려는 경우 앞서 언급한 모범 사례를 사용해야 합니다. 또한 얼굴 비교 사용에 대해 발표된 리소스를 참고해야 합니다. 여기에는 미 법무부 법무지원국에서 제공하는 [Face Recognition Policy Development Template For Use In Criminal Intelligence and Investigative Activities(범죄 정보 및 수사 활동에 활용하기 위한 얼굴 인식 정책 개발 템플릿)](https://www.bja.gov/Publications/Face-Recognition-Policy-Development-Template-508-compliant.pdf)가 포함됩니다. 이 템플릿은 다양한 얼굴 비교 및 생체 인식 관련 리소스를 제공하며, 법 집행 및 공공 안전 기관에 관계법을 준수하고 프라이버시 침해 위험을 낮추며 책임 및 감독을 확립하는 얼굴 비교 정책을 개발하기 위한 프레임워크를 제공하도록 고안되었습니다. 추가 리소스로는 미 통신정보관리청의 [ Best Privacy Practices for Commercial Use of Facial Recognition(얼굴 인식의 상업적 활용을 위한 개인정보보호 모범 사례)](https://www.ntia.doc.gov/files/ntia/publications/privacy_best_practices_recommendations_for_commercial_use_of_facial_recogntion.pdf)과 미 연방통상위원회의 [ Best Practices for Common Uses of Facial Recognition(얼굴 인식의 일반적 사용을 위한 모범 사례)](https://www.ftc.gov/sites/default/files/documents/reports/facing-facts-best-practices-common-uses-facial-recognition-technologies/121022facialtechrpt.pdf)가 포함됩니다. 향후 다른 리소스가 개발 및 공개될 수 있으므로 이 중요한 주제에 지속적으로 관심을 기울여야 합니다.

AWS 서비스를 사용하는 고객은 모든 관계법을 준수해야 하며, AWS 서비스를 다른 사람의 권리를 침해하거나 다른 사람에게 피해를 줄 수 있는 방식으로 사용할 수 없습니다. 이는 공공 안전을 위한 AWS 서비스를 불법적으로 특정 개인을 차별하거나 개인의 정당한 프로세스, 프라이버시 또는 시민적 자유를 침해하는 방식으로 사용할 수 없다는 의미입니다. 필요에 따라 적절한 법률 조언을 받아 사용 사례에 대한 법적 요건 등을 검토해야 합니다.

## 공공 안전을 위한 Amazon Rekognition 사용
<a name="public-safety"></a>

Amazon Rekognition은 미아 찾기, 인신매매 단속 또는 범죄 예방과 같은 공공 안전 및 법 집행 시나리오에서 도움이 될 수 있습니다. 공공 안전 및 법 집행 시나리오에서 다음을 고려하십시오.
+ 가능성 있는 일치 인물을 찾기 위한 첫 단계로 Amazon Rekognition을 사용합니다. Amazon Rekognition 얼굴 작업의 응답을 통해 향후 고려할 잠재적인 일치 세트를 빠르게 얻을 수 있습니다.
+ 인간의 분석을 필요로 하는 시나리오에서 자율적 결정을 내리는 데 Amazon Rekognition 응답을 사용하지 마십시오. 귀하가 범죄 수사와 관련하여 개인을 식별하는 데 도움을 받기 위해 Amazon Rekognition을 사용하는 법 집행 기관이며, 식별 결과를 근거로 해당 개인의 시민적 자유 또는 그에 동등한 인권에 영향을 줄 수 있는 조치를 취할 경우, 해당 조치의 결정은 적절한 훈련을 받은 사람이 독립적으로 조사한 신원 증빙의 근거에 기반하여 내려야 합니다.
+ 매우 정확한 얼굴 유사성 일치가 필요한 시나리오의 경우 99% 유사성 임계값을 사용합니다. 빌딩 액세스 인증을 예로 들 수 있습니다.
+ 법 집행을 위한 사용 시나리오 등 시민의 권리를 고려해야 할 경우 99% 이상의 신뢰도 임계값을 사용하고 개인의 권리를 침해하지 않도록 얼굴 비교 예측 내용에 대한 인간의 검토를 도입해야 합니다.
+ 대규모의 잠재적 일치 세트를 통해 이점을 얻게 되는 시나리오의 경우 99% 미만의 유사성 임계값을 사용합니다. 실종된 사람을 찾는 것을 예로 들 수 있습니다. 필요한 경우 유사성 응답 속성을 사용하여 잠재적 일치가 인식하고자 하는 사람과 어느 정도로 유사한지 판단할 수 있습니다. 
+ Amazon Rekognition에서 반환하는 가양성 얼굴 일치에 대한 계획을 마련하세요. 예를 들어 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 작업을 사용하여 인덱스를 구축할 때 동일한 사람의 이미지를 여러 개 사용하여 일치를 개선합니다. 자세한 내용은 [일반적인 시나리오에서 얼굴 인덱싱 지침](guidance-index-faces.md) 단원을 참조하십시오.

다른 사용 사례에서는(예: 소셜 미디어), 최선의 판단을 통해 Amazon Rekognition 결과에 인간의 검토가 필요한지 여부를 평가하는 것이 좋습니다. 또한 애플리케이션 요구 사항에 따라 유사성 임계값이 낮아질 수 있습니다.

# 컬렉션 생성
<a name="create-collection-procedure"></a>

[CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html) 작업을 사용하여 컬렉션을 생성할 수 있습니다.

자세한 내용은 [컬렉션 관리](managing-face-collections.md#managing-collections) 단원을 참조하십시오.

**모음을 만들려면(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. 다음 예제를 사용하여 `CreateCollection` 작업을 호출합니다.

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

   다음 예제는 모음을 만들고 Amazon Resource Name(ARN)을 표시합니다.

   `collectionId`의 값을, 만들려는 모음의 이름으로 변경합니다.

   ```
   //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.CreateCollectionRequest;
   import com.amazonaws.services.rekognition.model.CreateCollectionResult;
   
   
   public class CreateCollection {
   
      public static void main(String[] args) throws Exception {
   
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         
         String collectionId = "MyCollection";
               System.out.println("Creating collection: " +
            collectionId );
               
           CreateCollectionRequest request = new CreateCollectionRequest()
                       .withCollectionId(collectionId);
              
         CreateCollectionResult createCollectionResult = rekognitionClient.createCollection(request); 
         System.out.println("CollectionArn : " +
            createCollectionResult.getCollectionArn());
         System.out.println("Status code : " +
            createCollectionResult.getStatusCode().toString());
   
      } 
   
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java)에서 확인하세요.

    Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   //snippet-start:[rekognition.java2.create_collection.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.CreateCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.CreateCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   //snippet-end:[rekognition.java2.create_collection.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 CreateCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <collectionName> \n\n" +
            "Where:\n" +
            "   collectionName - The name of the collection. \n\n";
   
        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionId = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        System.out.println("Creating collection: " +collectionId);
        createMyCollection(rekClient, collectionId );
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.create_collection.main]
    public static void createMyCollection(RekognitionClient rekClient,String collectionId ) {
   
        try {
            CreateCollectionRequest collectionRequest = CreateCollectionRequest.builder()
                .collectionId(collectionId)
                .build();
   
            CreateCollectionResponse collectionResponse = rekClient.createCollection(collectionRequest);
            System.out.println("CollectionArn: " + collectionResponse.collectionArn());
            System.out.println("Status code: " + collectionResponse.statusCode().toString());
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.create_collection.main]
   ```

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

   이 AWS CLI 명령은 `create-collection` CLI 작업에 대한 JSON 출력을 표시합니다.

   `collection-id`의 값을, 만들려는 모음의 이름으로 바꿉니다.

    `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

   ```
   aws rekognition create-collection --profile profile-name --collection-id "collection-name"
   ```

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

   다음 예제는 모음을 만들고 Amazon Resource Name(ARN)을 표시합니다.

   `collection_id`의 값을, 만들려는 모음의 이름으로 변경합니다. 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 create_collection(collection_id):
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       # Create a collection
       print('Creating collection:' + collection_id)
       response = client.create_collection(CollectionId=collection_id)
       print('Collection ARN: ' + response['CollectionArn'])
       print('Status code: ' + str(response['StatusCode']))
       print('Done...')
   
   def main():
       collection_id = "collection-id"
       create_collection(collection_id)
   
   if __name__ == "__main__":
       main()
   ```

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

   다음 예제는 모음을 만들고 Amazon Resource Name(ARN)을 표시합니다.

   `collectionId`의 값을, 만들려는 모음의 이름으로 변경합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class CreateCollection
   {
       public static void Example()
       {
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           String collectionId = "MyCollection";
           Console.WriteLine("Creating collection: " + collectionId);
   
           CreateCollectionRequest createCollectionRequest = new CreateCollectionRequest()
           {
               CollectionId = collectionId
           };
   
           CreateCollectionResponse createCollectionResponse = rekognitionClient.CreateCollection(createCollectionRequest);
           Console.WriteLine("CollectionArn : " + createCollectionResponse.CollectionArn);
           Console.WriteLine("Status code : " + createCollectionResponse.StatusCode);
   
       }
   }
   ```

------
#### [ Node.JS ]

   다음 예시에서는 `region` 값을 계정과 연결된 리전 이름으로 바꾸고 `collectionName` 값을 원하는 컬렉션 이름으로 바꿉니다.

    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 { CreateCollectionCommand} from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const collectionName = "collection-name"
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   const createCollection = async (collectionName) => {
       try {
          console.log(`Creating collection: ${collectionName}`)
          const data = await rekogClient.send(new CreateCollectionCommand({CollectionId: collectionName}));
          console.log("Collection ARN:")
          console.log(data.CollectionARN)
          console.log("Status Code:")
          console.log(String(data.StatusCode))
          console.log("Success.",  data);
          return data;
       } catch (err) {
         console.log("Error", err.stack);
       }
     };
   
    createCollection(collectionName)
   ```

------

## CreateCollection 작업 요청
<a name="createcollection-request"></a>

`CreationCollection`에 대한 입력은 생성하려는 모음의 이름입니다.

```
{
    "CollectionId": "MyCollection"
}
```

## CreateCollection 작업 응답
<a name="createcollection-operation-response"></a>

Amazon Rekognition은 컬렉션을 만들고 새로 만든 컬렉션의 Amazon 리소스 이름(ARN)을 반환합니다.

```
{
   "CollectionArn": "aws:rekognition:us-east-1:acct-id:collection/examplecollection",
   "StatusCode": 200
}
```

# 컬렉션 태그 지정
<a name="tag-collections"></a>

태그를 사용하여 Amazon Rekognition 컬렉션을 식별, 구성, 검색 및 필터링할 수 있습니다. 각 태그는 사용자 정의 키와 값으로 구성된 레이블입니다.

Identity and Access Management(IAM)을 통해 태그를 사용하여 컬렉션에 대한 액세스를 제어할 수도 있습니다. 자세한 내용은 [AWS 리소스 태그를 사용하여 리소스에 대한 액세스 제어를](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html) 참조하세요.

**Topics**
+ [새 컬렉션에 태그 추가](#add-tag-new-collection)
+ [기존 컬렉션에 태그 추가](#add-tag-existing-collection)
+ [컬렉션의 태그 나열](#list-tags-collection)
+ [컬렉션에서 태그 삭제](#delete-tag-collection)

## 새 컬렉션에 태그 추가
<a name="add-tag-new-collection"></a>

`CreateCollection` 작업을 사용하여 컬렉션을 생성할 때 태그를 추가할 수 있습니다. `Tags` 배열 입력 파라미터에 하나 이상의 태그를 지정합니다.

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

 `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

```
aws rekognition create-collection --collection-id "collection-name" --tags "{"key1":"value1","key2":"value2"}" --profile profile-name 
```

Windows 디바이스의 경우는 다음과 같이 하십시오.

```
aws rekognition create-collection --collection-id "collection-name" --tags "{\"key1\":\"value1\",\"key2\":\"value2\"}" --profile profile-name
```

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

 Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

```
import boto3

def create_collection(collection_id):
    client = boto3.client('rekognition')

    # Create a collection
    print('Creating collection:' + collection_id)
    response = client.create_collection(CollectionId=collection_id)
    print('Collection ARN: ' + response['CollectionArn'])
    print('Status code: ' + str(response['StatusCode']))
    print('Done...')

def main():
    collection_id = 'NewCollectionName'
    create_collection(collection_id)

if __name__ == "__main__":
    main()
```

------

## 기존 컬렉션에 태그 추가
<a name="add-tag-existing-collection"></a>

기존 컬렉션에 하나 이상의 태그를 추가하려면 `TagResource` 작업을 사용합니다. 컬렉션의 Amazon 리소스 이름(ARN)(`ResourceArn`)과 추가할 태그(`Tags`)를 지정합니다. 다음 예제는 태그 2개를 추가하는 방법을 보여줍니다.

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

 `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

```
aws rekognition tag-resource --resource-arn collection-arn --tags "{"key1":"value1","key2":"value2"}" --profile profile-name 
```

 Windows 디바이스의 경우는 다음과 같이 하십시오.

```
aws rekognition tag-resource --resource-arn collection-arn --tags "{\"key1\":\"value1\",\"key2\":\"value2\"}" --profile profile-name
```

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

 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 create_tag(collection_id):
    session = boto3.Session(profile_name='default')
    client = session.client('rekognition')
    response = client.tag_resource(ResourceArn=collection_id,
                                   Tags={
                                       "KeyName": "ValueName"
                                   })
    print(response)
    if "'HTTPStatusCode': 200" in str(response):
        print("Success!!")

def main():
    collection_arn = "collection-arn"
    create_tag(collection_arn)

if __name__ == "__main__":
    main()
```

------

**참고**  
컬렉션의 Amazon 리소스 이름을 모르는 경우 `DescribeCollection` 작업을 사용할 수 있습니다.

## 컬렉션의 태그 나열
<a name="list-tags-collection"></a>

컬렉션에 연결된 태그를 나열하려면 `ListTagsForResource` 작업을 사용하고 컬렉션의 ARN(`ResourceArn`)을 명시하세요. 응답은 지정된 컬렉션에 연결된 태그 키 및 값의 맵입니다.

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

 `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

```
aws rekognition list-tags-for-resource --resource-arn resource-arn --profile profile-name
```

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

 Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

```
import boto3

def list_tags():
    client = boto3.client('rekognition')
    response = client.list_tags_for_resource(ResourceArn="arn:aws:rekognition:region-name:5498347593847598:collection/NewCollectionName")
    print(response)

def main():
    list_tags()

if __name__ == "__main__":
    main()
```

------

출력된 결과에 컬렉션에 연결된 태그 목록이 표시됩니다.

```
                {
    "Tags": {
        "Dept": "Engineering",
        "Name": "Ana Silva Carolina",
        "Role": "Developer"
    }
}
```

## 컬렉션에서 태그 삭제
<a name="delete-tag-collection"></a>

컬렉션에서 하나 이상의 태그를 삭제하려면 `UntagResource` 작업을 사용합니다. 제거하려는 모델의 ARN(`ResourceArn`)과 태그 키(`Tag-Keys`)를 지정합니다.

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

`profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

```
aws rekognition untag-resource --resource-arn resource-arn --profile profile-name --tag-keys "key1" "key2"
```

또는 다음 형식으로 tag-key를 지정할 수도 있습니다.

```
--tag-keys key1,key2
```

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

 Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

```
import boto3

def list_tags():
    client = boto3.client('rekognition')
    response = client.untag_resource(ResourceArn="arn:aws:rekognition:region-name:5498347593847598:collection/NewCollectionName", TagKeys=['KeyName'])
    print(response)

def main():
    list_tags()

if __name__ == "__main__":
    main()
```

------

# 컬렉션 나열
<a name="list-collection-procedure"></a>

[ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html) 작업을 사용하여 현재 사용하는 리전의 컬렉션을 나열할 수 있습니다.

자세한 내용은 [컬렉션 관리](managing-face-collections.md#managing-collections) 단원을 참조하십시오.



**모음을 나열하려면(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. 다음 예제를 사용하여 `ListCollections` 작업을 호출합니다.

------
#### [ 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.)
   
   package aws.example.rekognition.image;
   
   import java.util.List;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.ListCollectionsRequest;
   import com.amazonaws.services.rekognition.model.ListCollectionsResult;
   
   public class ListCollections {
   
      public static void main(String[] args) throws Exception {
   
   
         AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();
    
   
         System.out.println("Listing collections");
         int limit = 10;
         ListCollectionsResult listCollectionsResult = null;
         String paginationToken = null;
         do {
            if (listCollectionsResult != null) {
               paginationToken = listCollectionsResult.getNextToken();
            }
            ListCollectionsRequest listCollectionsRequest = new ListCollectionsRequest()
                    .withMaxResults(limit)
                    .withNextToken(paginationToken);
            listCollectionsResult=amazonRekognition.listCollections(listCollectionsRequest);
            
            List < String > collectionIds = listCollectionsResult.getCollectionIds();
            for (String resultId: collectionIds) {
               System.out.println(resultId);
            }
         } while (listCollectionsResult != null && listCollectionsResult.getNextToken() !=
            null);
        
      } 
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/ListCollections.java)에서 확인하세요.

   ```
   //snippet-start:[rekognition.java2.list_collections.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.ListCollectionsRequest;
   import software.amazon.awssdk.services.rekognition.model.ListCollectionsResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   //snippet-end:[rekognition.java2.list_collections.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 ListCollections {
   
    public static void main(String[] args) {
   
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        System.out.println("Listing collections");
        listAllCollections(rekClient);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.list_collections.main]
    public static void listAllCollections(RekognitionClient rekClient) {
        try {
            ListCollectionsRequest listCollectionsRequest = ListCollectionsRequest.builder()
                .maxResults(10)
                .build();
   
            ListCollectionsResponse response = rekClient.listCollections(listCollectionsRequest);
            List<String> collectionIds = response.collectionIds();
            for (String resultId : collectionIds) {
                System.out.println(resultId);
            }
   
        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.list_collections.main]
   }
   ```

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

   이 AWS CLI 명령은 `list-collections` CLI 작업에 대한 JSON 출력을 표시합니다. `profile_name`의 값을 개발자 프로필 이름으로 바꿉니다.

   ```
   aws rekognition list-collections --profile profile-name
   ```

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

   다음 예제는 현재 리전의 모음을 나열합니다.

    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 list_collections():
   
       max_results=2
       
       client=boto3.client('rekognition')
   
       #Display all the collections
       print('Displaying collections...')
       response=client.list_collections(MaxResults=max_results)
       collection_count=0
       done=False
       
       while done==False:
           collections=response['CollectionIds']
   
           for collection in collections:
               print (collection)
               collection_count+=1
           if 'NextToken' in response:
               nextToken=response['NextToken']
               response=client.list_collections(NextToken=nextToken,MaxResults=max_results)
               
           else:
               done=True
   
       return collection_count   
   
   def main():
   
       collection_count=list_collections()
       print("collections: " + str(collection_count))
   if __name__ == "__main__":
       main()
   ```

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

   다음 예제는 현재 리전의 모음을 나열합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class ListCollections
   {
       public static void Example()
       {
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           Console.WriteLine("Listing collections");
           int limit = 10;
   
           ListCollectionsResponse listCollectionsResponse = null;
           String paginationToken = null;
           do
           {
               if (listCollectionsResponse != null)
                   paginationToken = listCollectionsResponse.NextToken;
   
               ListCollectionsRequest listCollectionsRequest = new ListCollectionsRequest()
               {
                   MaxResults = limit,
                   NextToken = paginationToken
               };
   
               listCollectionsResponse = rekognitionClient.ListCollections(listCollectionsRequest);
   
               foreach (String resultId in listCollectionsResponse.CollectionIds)
                   Console.WriteLine(resultId);
           } while (listCollectionsResponse != null && listCollectionsResponse.NextToken != null);
       }
   }
   ```

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

    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 { ListCollectionsCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   const listCollection = async () => {
     var max_results = 10
     console.log("Displaying collections:")
     var response = await rekogClient.send(new ListCollectionsCommand({MaxResults: max_results}))
     var collection_count = 0
     var done = false
     while (done == false){
         var collections = response.CollectionIds
         collections.forEach(collection => {
             console.log(collection)
             collection_count += 1
         });
         return collection_count
     }
   }
   
   var collect_list = await listCollection()
   console.log(collect_list)
   ```

------

## ListCollections 작업 요청
<a name="listcollections-request"></a>

`ListCollections`에 대한 입력은 반환될 최대 모음 수입니다.

```
{
    "MaxResults": 2
}
```

응답의 컬렉션이 `MaxResults`가 요청한 것보다 많으면 후속 `ListCollections` 직접 호출에서 다음 결과 집합을 가져오는 데 사용할 수 있는 토큰이 반환됩니다. 예제:

```
{
    "NextToken": "MGYZLAHX1T5a....",
    "MaxResults": 2
}
```

## ListCollections 작업 응답
<a name="listcollections-operation-response"></a>

Amazon Rekognition은 컬렉션의 배열(`CollectionIds`)을 반환합니다. 각 모음의 얼굴을 분석하는 데 사용된 얼굴 모델 버전은 별도의 배열(`FaceModelVersions`)로 제공됩니다. 예를 들어 다음 JSON 응답에서 `MyCollection` 모음은 얼굴 모델 버전 2.0을 사용하여 얼굴을 분석합니다. `AnotherCollection`모음은 얼굴 모델 버전 3.0을 사용합니다. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.

`NextToken`은 `ListCollections`에 대한 후속 호출에서 다음 결과 집합을 가져오는 데 사용되는 토큰입니다.

```
{
    "CollectionIds": [
        "MyCollection",
        "AnotherCollection"
    ],
    "FaceModelVersions": [
        "2.0",
        "3.0"
    ],
    "NextToken": "MGYZLAHX1T5a...."
}
```

# 컬렉션 설명
<a name="describe-collection-procedure"></a>

[DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html) 작업을 사용하여 컬렉션에 관한 다음 정보를 얻을 수 있습니다.
+ 모음에 인덱싱된 얼굴의 수.
+ 컬렉션과 함께 사용되는 모델 버전. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.
+ 모음의 Amazon 리소스 이름(ARN).
+ 모음의 생성 날짜 및 시간.

**모음을 설명하려면(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. 다음 예제를 사용하여 `DescribeCollection` 작업을 호출합니다.

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

   이 예제는 모음을 설명합니다.

   `collectionId`의 값을 원하는 모음의 ID로 변경합니다.

   ```
   //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 com.amazonaws.samples;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.DescribeCollectionRequest;
   import com.amazonaws.services.rekognition.model.DescribeCollectionResult;
   
   
   public class DescribeCollection {
   
      public static void main(String[] args) throws Exception {
   
         String collectionId = "CollectionID";
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
               
         System.out.println("Describing collection: " +
            collectionId );
            
               
           DescribeCollectionRequest request = new DescribeCollectionRequest()
                       .withCollectionId(collectionId);
              
         DescribeCollectionResult describeCollectionResult = rekognitionClient.describeCollection(request); 
         System.out.println("Collection Arn : " +
            describeCollectionResult.getCollectionARN());
         System.out.println("Face count : " +
            describeCollectionResult.getFaceCount().toString());
         System.out.println("Face model version : " +
            describeCollectionResult.getFaceModelVersion());
         System.out.println("Created : " +
            describeCollectionResult.getCreationTimestamp().toString());
   
      } 
   
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java)에서 확인하세요.

   ```
   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.DescribeCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   //snippet-end:[rekognition.java2.describe_collection.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 DescribeCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <collectionName>\n\n" +
            "Where:\n" +
            "   collectionName - The name of the Amazon Rekognition collection. \n\n";
   
        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionName = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        describeColl(rekClient, collectionName);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.describe_collection.main]
    public static void describeColl(RekognitionClient rekClient, String collectionName) {
   
        try {
            DescribeCollectionRequest describeCollectionRequest = DescribeCollectionRequest.builder()
                .collectionId(collectionName)
                .build();
   
            DescribeCollectionResponse describeCollectionResponse = rekClient.describeCollection(describeCollectionRequest);
            System.out.println("Collection Arn : " + describeCollectionResponse.collectionARN());
            System.out.println("Created : " + describeCollectionResponse.creationTimestamp().toString());
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.describe_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `describe-collection` CLI 작업에 대한 JSON 출력을 표시합니다. `collection-id`의 값을 원하는 모음의 ID로 변경합니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition describe-collection --collection-id collection-name --profile profile-name
   ```

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

   이 예제는 모음을 설명합니다.

   `collection_id`의 값을 원하는 모음의 ID로 변경합니다. 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
   from botocore.exceptions import ClientError
   
   def describe_collection(collection_id):
   
       print('Attempting to describe collection ' + collection_id)
       
       session = boto3.Session(profile_name='default')
       client = session.client('rekognition')
       
       try:
       response = client.describe_collection(CollectionId=collection_id)
       print("Collection Arn: " + response['CollectionARN'])
       print("Face Count: " + str(response['FaceCount']))
       print("Face Model Version: " + response['FaceModelVersion'])
       print("Timestamp: " + str(response['CreationTimestamp']))
       
       except ClientError as e:
       if e.response['Error']['Code'] == 'ResourceNotFoundException':
       print('The collection ' + collection_id + ' was not found ')
       else:
       print('Error other than Not Found occurred: ' + e.response['Error']['Message'])
       print('Done...')
   
   def main():
       collection_id = 'collection-name'
       describe_collection(collection_id)
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 모음을 설명합니다.

   `collectionId`의 값을 원하는 모음의 ID로 변경합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DescribeCollection
   {
       public static void Example()
       {
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           String collectionId = "CollectionID";
           Console.WriteLine("Describing collection: " + collectionId);
   
           DescribeCollectionRequest describeCollectionRequest = new DescribeCollectionRequest()
           {
               CollectionId = collectionId
           };
   
           DescribeCollectionResponse describeCollectionResponse = rekognitionClient.DescribeCollection(describeCollectionRequest);
           Console.WriteLine("Collection ARN: " + describeCollectionResponse.CollectionARN);
           Console.WriteLine("Face count: " + describeCollectionResponse.FaceCount);
           Console.WriteLine("Face model version: " + describeCollectionResponse.FaceModelVersion);
           Console.WriteLine("Created: " + describeCollectionResponse.CreationTimestamp);
       }
   }
   ```

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

   ```
   //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 { DescribeCollectionCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   // Name the collection
   const collection_name = "collection-name"
   
   const describeCollection = async (collectionName) => {
     try {
        console.log(`Attempting to describe collection named - ${collectionName}`)
        var response = await rekogClient.send(new DescribeCollectionCommand({CollectionId: collectionName}))
        console.log('Collection Arn:')
        console.log(response.CollectionARN)
        console.log('Face Count:')
        console.log(response.FaceCount)
        console.log('Face Model Version:')
        console.log(response.FaceModelVersion)
        console.log('Timestamp:')
        console.log(response.CreationTimestamp)
        return response; // For unit tests.
     } catch (err) {
       console.log("Error", err.stack);
     }
   };
   
   describeCollection(collection_name)
   ```

------

## DescribeCollection 작업 요청
<a name="describe-collection-request"></a>

`DescribeCollection`에 대한 입력은 원하는 모음의 ID입니다. 다음 JSON 예제를 참조하십시오.

```
{
    "CollectionId": "MyCollection"
}
```

## DescribeCollection 작업 응답
<a name="describe-collection-operation-response"></a>

응답에는 다음이 포함됩니다.
+ 모음에 인덱싱된 얼굴의 수, `FaceCount`.
+ 컬렉션과 함께 사용되는 얼굴 모델 버전, `FaceModelVersion`. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.
+ 모음의 Amazon 리소스 이름, `CollectionARN`.
+ 모음의 생성 날짜 및 시간, `CreationTimestamp`. `CreationTimestamp`의 값은 밀리초인데 모음 생성까지의 Unix epoch 시간 때문입니다. Unix epoch 시간은 1970년 1월 1일, 목요일 00:00:00 협정 세계시(UTC)입니다. 자세한 내용은 [Unix Time](https://en.wikipedia.org/wiki/Unix_time)을 참조하십시오.

```
{
    "CollectionARN": "arn:aws:rekognition:us-east-1:nnnnnnnnnnnn:collection/MyCollection",
    "CreationTimestamp": 1.533422155042E9,
    "FaceCount": 200,
    "UserCount" : 20,
    "FaceModelVersion": "1.0"
}
```

# 컬렉션 삭제
<a name="delete-collection-procedure"></a>

[DeleteCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteCollection.html) 작업을 사용하여 컬렉션을 삭제할 수 있습니다.

자세한 내용은 [컬렉션 관리](managing-face-collections.md#managing-collections) 단원을 참조하십시오.



**모음을 삭제하려면(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. 다음 예제를 사용하여 `DeleteCollection` 작업을 호출합니다.

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

   이 예제는 모음을 삭제합니다.

   `collectionId` 값을, 삭제하려는 모음으로 변경합니다.

   ```
   //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.DeleteCollectionRequest;
   import com.amazonaws.services.rekognition.model.DeleteCollectionResult;
   
   
   public class DeleteCollection {
   
      public static void main(String[] args) throws Exception {
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         String collectionId = "MyCollection";
   
         System.out.println("Deleting collections");
         
         DeleteCollectionRequest request = new DeleteCollectionRequest()
            .withCollectionId(collectionId);
         DeleteCollectionResult deleteCollectionResult = rekognitionClient.deleteCollection(request);        
     
         System.out.println(collectionId + ": " + deleteCollectionResult.getStatusCode()
            .toString());
   
      } 
   
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java)에서 확인하세요.

   ```
   // snippet-start:[rekognition.java2.delete_collection.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.DeleteCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.DeleteCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   // snippet-end:[rekognition.java2.delete_collection.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 DeleteCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> \n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection to delete. \n\n";
   
           if (args.length != 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Deleting collection: " + collectionId);
           deleteMyCollection(rekClient, collectionId);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.delete_collection.main]
       public static void deleteMyCollection(RekognitionClient rekClient,String collectionId ) {
   
           try {
               DeleteCollectionRequest deleteCollectionRequest = DeleteCollectionRequest.builder()
                   .collectionId(collectionId)
                   .build();
   
               DeleteCollectionResponse deleteCollectionResponse = rekClient.deleteCollection(deleteCollectionRequest);
               System.out.println(collectionId + ": " + deleteCollectionResponse.statusCode().toString());
   
           } catch(RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.delete_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `delete-collection` CLI 작업에 대한 JSON 출력을 표시합니다. `collection-id`의 값을, 삭제하려는 모음의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition delete-collection --collection-id collection-name --profile profile-name
   ```

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

   이 예제는 모음을 삭제합니다.

   `collection_id` 값을, 삭제하려는 모음으로 변경합니다. 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
   from botocore.exceptions import ClientError
   
   def delete_collection(collection_id):
   
       print('Attempting to delete collection ' + collection_id)
       session = boto3.Session(profile_name='default')
       client = session.client('rekognition')
   
       status_code = 0
   
       try:
           response = client.delete_collection(CollectionId=collection_id)
           status_code = response['StatusCode']
   
       except ClientError as e:
           if e.response['Error']['Code'] == 'ResourceNotFoundException':
               print('The collection ' + collection_id + ' was not found ')
           else:
               print('Error other than Not Found occurred: ' + e.response['Error']['Message'])
           status_code = e.response['ResponseMetadata']['HTTPStatusCode']
       return (status_code)
   
   def main():
   
       collection_id = 'collection-name'
       status_code = delete_collection(collection_id)
       print('Status code: ' + str(status_code))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 모음을 삭제합니다.

   `collectionId` 값을, 삭제하려는 모음으로 변경합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class DeleteCollection
   {
       public static void Example()
       {
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           String collectionId = "MyCollection";
           Console.WriteLine("Deleting collection: " + collectionId);
   
           DeleteCollectionRequest deleteCollectionRequest = new DeleteCollectionRequest()
           {
               CollectionId = collectionId
           };
   
           DeleteCollectionResponse deleteCollectionResponse = rekognitionClient.DeleteCollection(deleteCollectionRequest);
           Console.WriteLine(collectionId + ": " + deleteCollectionResponse.StatusCode);
       }
   }
   ```

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

    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 { DeleteCollectionCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   // Name the collection
   const collection_name = "collection-name"
   
   const deleteCollection = async (collectionName) => {
       try {
          console.log(`Attempting to delete collection named - ${collectionName}`)
          var response = await rekogClient.send(new DeleteCollectionCommand({CollectionId: collectionName}))
          var status_code = response.StatusCode
          if (status_code = 200){
              console.log("Collection successfully deleted.")
          }
          return response; // For unit tests.
       } catch (err) {
         console.log("Error", err.stack);
       }
     };
   
   deleteCollection(collection_name)
   ```

------

## DeleteCollection 작업 요청
<a name="deletecollection-request"></a>

`DeleteCollection`에 대한 입력은 삭제할 모음의 ID입니다. 다음 JSON 예제를 참조하십시오.

```
{
    "CollectionId": "MyCollection"
}
```

## DeleteCollection 작업 응답
<a name="deletecollection-operation-response"></a>

`DeleteCollection` 응답에는 작업의 성공 또는 실패를 나타내는 HTTP 상태 코드가 들어 있습니다. 모음이 성공적으로 삭제되면 `200`이 반환됩니다.

```
{"StatusCode":200}
```

# 컬렉션에 얼굴 추가
<a name="add-faces-to-collection-procedure"></a>

[IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 작업을 사용하여 이미지에서 얼굴을 감지하고 컬렉션에 추가할 수 있습니다. Amazon Rekognition은 감지된 각 얼굴에서 얼굴 특성을 추출하여 데이터베이스에 이 특성 정보를 저장합니다. 또한 이 명령은 감지된 각 얼굴의 메타데이터를 지정된 얼굴 컬렉션에 저장합니다. Amazon Rekognition은 실제 이미지 바이트를 저장하지 않습니다.

인덱싱에 적합한 얼굴 제공에 대한 자세한 내용은 [얼굴 비교 입력 이미지에 대한 권장 사항](recommendations-facial-input-images.md) 단원을 참조하십시오.

`IndexFaces` 작업은 각 얼굴에 대해 다음의 정보를 유지합니다.
+ **다차원 얼굴 특성** - `IndexFaces`는 얼굴 분석을 사용하여 얼굴 특성에 대한 다차원 정보를 추출하고, 이 정보를 얼굴 컬렉션에 저장합니다. 이 정보를 직접 액세스할 수는 없습니다. 그러나 Amazon Rekognition은 얼굴 컬렉션에서 얼굴 일치를 검색할 때 이 정보를 사용합니다.

   
+ **메타데이터** – 각 얼굴의 메타데이터에는 경계 상자, 신뢰도 수준(경계 상자에 얼굴이 포함될 신뢰도 수준), Amazon Rekognition이 할당한 ID(얼굴 ID 및 이미지 ID), 요청 내 외부 이미지 ID(제공한 경우)가 포함됩니다. 이 정보는 `IndexFaces` API 호출에 대한 응답으로 반환됩니다. 관련 예제는 다음 응답 예의 `face` 요소를 참조하십시오.

  이 서비스는 다음 API 호출에 대한 응답으로 이 메타데이터를 반환합니다.

   
  +  `[ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html)` 
  + 얼굴 검색 작업 – [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) 및 [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html)에 대한 응답은 일치하는 얼굴의 일치 신뢰도와 함께 일치한 얼굴의 이 메타데이터를 반환합니다.

`IndexFaces`에서 인덱스를 생성하는 얼굴 수는 입력 모음과 연결된 얼굴 감지 모델의 버전에 따라 다릅니다. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.

인덱싱된 얼굴에 대한 정보는 [FaceRecord](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceRecord.html) 객체의 배열로 반환됩니다.

감지된 이미지와 인덱싱된 얼굴을 연결해야 합니다. 예를 들어 이미지와 이미지의 얼굴에서 클라이언트 측 인덱스를 유지해야 합니다. 얼굴을 이미지와 연결하려면, `ExternalImageId` 요청 파라미터에서 이미지 ID를 지정합니다. 이미지 ID는 만드는 파일 이름이나 다른 ID일 수 있습니다.

이 API는 얼굴 모음에서 유지하는 위의 정보 외에, 모음에 유지되지 않는 얼굴 세부 정보도 반환합니다. 다음 예제 응답에서 `faceDetail` 요소를 참조하십시오.

**참고**  
`DetectFaces`는 동일한 정보를 반환하므로 같은 이미지에 대해 `DetectFaces`와 `IndexFaces`를 모두 호출할 필요는 없습니다.

## 얼굴 필터링
<a name="index-faces-filtering"></a>

IndexFaces 작업을 통해 이미지에서 인덱싱된 얼굴을 필터링할 수 있습니다. `IndexFaces`를 통해 최대 얼굴 수를 인덱스로 지정하거나, 고화질로 감지된 얼굴만 인덱싱하도록 선택할 수 있습니다.

`MaxFaces` 입력 파라미터를 사용하여 `IndexFaces`로 인덱싱되는 최대 얼굴 수를 지정할 수 있습니다. 이는 이미지에서 가장 큰 얼굴을 인덱싱하고자 하며 작은 얼굴(예: 배경에 서 있는 사람들의 얼굴)은 인덱싱하지 않고자 할 때 유용합니다.

기본적으로 `IndexFaces`는 얼굴을 필터링하는 데 사용되는 화질 막대를 선택합니다. `QualityFilter` 입력 파라미터를 사용하여 화질 막대를 명시적으로 설정할 수 있습니다. 값은 다음과 같습니다.
+ `AUTO` - Amazon Rekognition이 얼굴을 필터링하는 데 사용되는 화질 막대를 선택합니다(기본값).
+ `LOW` - 가장 낮은 화질의 얼굴을 제외한 모든 얼굴이 인덱싱됩니다.
+ `MEDIUM`
+ `HIGH` - 가장 높은 화질의 얼굴만 인덱싱됩니다.
+ `NONE` - 화질에 따라 얼굴이 필터링되지 않습니다.

`IndexFaces`는 다음과 같은 이유로 얼굴을 필터링합니다.
+ 얼굴이 이미지 크기와 비교하여 너무 작습니다.
+ 얼굴이 너무 흐릿합니다.
+ 이미지가 너무 어둡습니다.
+ 얼굴이 극단적인 포즈입니다.
+ 얼굴에는 얼굴 검색에 적합한 세부 정보가 충분하지 않습니다.

**참고**  
화질 필터링을 사용하려면 얼굴 모델 버전 3 이상과 연결된 모음이 필요합니다. 컬렉션과 연결된 얼굴 모델 버전을 가져오려면 [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html)을 직접 호출하세요.

`IndexFaces`로 인덱싱되지 않은 얼굴에 대한 정보는 [UnindexedFace](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UnindexedFace.html) 객체의 배열로 반환됩니다. `Reasons` 배열에는 얼굴이 인덱싱되지 않은 이유 목록이 포함되어 있습니다. 예를 들어 `MaxFaces`로 지정된 얼굴 수가 이미 감지되었으므로 `EXCEEDS_MAX_FACES` 값은 인덱싱되지 않은 얼굴입니다.

자세한 내용은 [컬렉션에서 얼굴 관리](managing-face-collections.md#collections-index-faces) 단원을 참조하십시오.



**모음에 얼굴을 추가하려면(SDK)**

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. (하나 이상의 얼굴이 포함된) 이미지를 Amazon S3 버킷에 업로드합니다.

   이에 관한 지침은 *Amazon Simple Storage Service 사용 설명서*에서 [Amazon S3에 객체 업로드](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html)를 참조하세요.

1. 다음 예제를 사용하여 `IndexFaces` 작업을 호출합니다.

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

   이 예제는 모음에 추가된 얼굴의 얼굴 식별자를 표시합니다.

   `collectionId`의 값을, 얼굴을 추가하려는 모음의 이름으로 변경합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. `.withMaxFaces(1)` 파라미터는 인덱싱되는 얼굴 수를 1로 제한합니다. 요구에 맞게 값을 제거하거나 변경합니다.

   ```
   //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.FaceRecord;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.IndexFacesRequest;
   import com.amazonaws.services.rekognition.model.IndexFacesResult;
   import com.amazonaws.services.rekognition.model.QualityFilter;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.UnindexedFace;
   import java.util.List;
   
   public class AddFacesToCollection {
       public static final String collectionId = "MyCollection";
       public static final String bucket = "bucket";
       public static final String photo = "input.jpg";
   
       public static void main(String[] args) throws Exception {
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           Image image = new Image()
                   .withS3Object(new S3Object()
                   .withBucket(bucket)
                   .withName(photo));
           
           IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
                   .withImage(image)
                   .withQualityFilter(QualityFilter.AUTO)
                   .withMaxFaces(1)
                   .withCollectionId(collectionId)
                   .withExternalImageId(photo)
                   .withDetectionAttributes("DEFAULT");
   
           IndexFacesResult indexFacesResult = rekognitionClient.indexFaces(indexFacesRequest);
           
           System.out.println("Results for " + photo);
           System.out.println("Faces indexed:");
           List<FaceRecord> faceRecords = indexFacesResult.getFaceRecords();
           for (FaceRecord faceRecord : faceRecords) {
               System.out.println("  Face ID: " + faceRecord.getFace().getFaceId());
               System.out.println("  Location:" + faceRecord.getFaceDetail().getBoundingBox().toString());
           }
           
           List<UnindexedFace> unindexedFaces = indexFacesResult.getUnindexedFaces();
           System.out.println("Faces not indexed:");
           for (UnindexedFace unindexedFace : unindexedFaces) {
               System.out.println("  Location:" + unindexedFace.getFaceDetail().getBoundingBox().toString());
               System.out.println("  Reasons:");
               for (String reason : unindexedFace.getReasons()) {
                   System.out.println("   " + reason);
               }
           }
       }
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java)에서 확인하세요.

   ```
   //snippet-start:[rekognition.java2.add_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   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.IndexFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.IndexFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.QualityFilter;
   import software.amazon.awssdk.services.rekognition.model.Attribute;
   import software.amazon.awssdk.services.rekognition.model.FaceRecord;
   import software.amazon.awssdk.services.rekognition.model.UnindexedFace;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.Reason;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   //snippet-end:[rekognition.java2.add_faces_collection.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 AddFacesToCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "    <collectionId> <sourceImage>\n\n" +
            "Where:\n" +
            "    collectionName - The name of the collection.\n" +
            "    sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionId = args[0];
        String sourceImage = args[1];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        addToCollection(rekClient, collectionId, sourceImage);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.add_faces_collection.main]
    public static void addToCollection(RekognitionClient rekClient, String collectionId, String sourceImage) {
   
        try {
            InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
            Image souImage = Image.builder()
                .bytes(sourceBytes)
                .build();
   
            IndexFacesRequest facesRequest = IndexFacesRequest.builder()
                .collectionId(collectionId)
                .image(souImage)
                .maxFaces(1)
                .qualityFilter(QualityFilter.AUTO)
                .detectionAttributes(Attribute.DEFAULT)
                .build();
   
            IndexFacesResponse facesResponse = rekClient.indexFaces(facesRequest);
            System.out.println("Results for the image");
            System.out.println("\n Faces indexed:");
            List<FaceRecord> faceRecords = facesResponse.faceRecords();
            for (FaceRecord faceRecord : faceRecords) {
                System.out.println("  Face ID: " + faceRecord.face().faceId());
                System.out.println("  Location:" + faceRecord.faceDetail().boundingBox().toString());
            }
   
            List<UnindexedFace> unindexedFaces = facesResponse.unindexedFaces();
            System.out.println("Faces not indexed:");
            for (UnindexedFace unindexedFace : unindexedFaces) {
                System.out.println("  Location:" + unindexedFace.faceDetail().boundingBox().toString());
                System.out.println("  Reasons:");
                for (Reason reason : unindexedFace.reasons()) {
                    System.out.println("Reason:  " + reason);
                }
            }
   
        } catch (RekognitionException | FileNotFoundException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.add_faces_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `index-faces` CLI 작업에 대한 JSON 출력을 표시합니다.

   `collection-id`의 값을, 얼굴을 저장할 모음 이름으로 바꿉니다. `Bucket` 및 `Name`의 값을, 2단계에서 사용한 Amazon S3 버킷과 이미지 파일로 바꿉니다. `max-faces` 파라미터는 인덱싱되는 얼굴 수를 1로 제한합니다. 요구에 맞게 값을 제거하거나 변경합니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition index-faces --image '{"S3Object":{"Bucket":"bucket-name","Name":"file-name"}}' --collection-id "collection-id" \
                                   --max-faces 1 --quality-filter "AUTO" --detection-attributes "ALL" \ 
                                   --external-image-id "example-image.jpg" --profile profile-name
   ```

    Windows 디바이스에서 CLI에 액세스하는 경우 작은따옴표 대신 큰따옴표를 사용하고 내부 큰따옴표는 백슬래시(즉 \$1)로 이스케이프 처리하여 발생할 수 있는 구문 분석 오류를 해결합니다. 예를 들어 다음을 참조하세요.

   ```
   aws rekognition index-faces --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"image-name\"}}" \
   --collection-id "collection-id" --max-faces 1 --quality-filter "AUTO" --detection-attributes "ALL" \ 
   --external-image-id "example-image.jpg" --profile profile-name
   ```

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

   이 예제는 모음에 추가된 얼굴의 얼굴 식별자를 표시합니다.

   `collectionId`의 값을, 얼굴을 추가하려는 모음의 이름으로 변경합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다. `MaxFaces` 입력 파라미터는 인덱싱되는 얼굴 수를 1로 제한합니다. 요구에 맞게 값을 제거하거나 변경합니다. 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 add_faces_to_collection(bucket, photo, collection_id):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.index_faces(CollectionId=collection_id,
                                     Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
                                     ExternalImageId=photo,
                                     MaxFaces=1,
                                     QualityFilter="AUTO",
                                     DetectionAttributes=['ALL'])
   
       print('Results for ' + photo)
       print('Faces indexed:')
       for faceRecord in response['FaceRecords']:
           print('  Face ID: ' + faceRecord['Face']['FaceId'])
           print('  Location: {}'.format(faceRecord['Face']['BoundingBox']))
   
       print('Faces not indexed:')
       for unindexedFace in response['UnindexedFaces']:
           print(' Location: {}'.format(unindexedFace['FaceDetail']['BoundingBox']))
           print(' Reasons:')
           for reason in unindexedFace['Reasons']:
               print('   ' + reason)
       return len(response['FaceRecords'])
   
   def main():
       bucket = 'amzn-s3-demo-bucket'
       collection_id = 'collection-id'
       photo = 'photo-name'
   
       indexed_faces_count = add_faces_to_collection(bucket, photo, collection_id)
       print("Faces indexed count: " + str(indexed_faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 모음에 추가된 얼굴의 얼굴 식별자를 표시합니다.

   `collectionId`의 값을, 얼굴을 추가하려는 모음의 이름으로 변경합니다. `bucket` 및 `photo`의 값을 2단계에서 사용한 Amazon S3 버킷과 이미지의 이름으로 바꿉니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using System.Collections.Generic;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class AddFaces
   {
       public static void Example()
       {
           String collectionId = "MyCollection";
           String bucket = "amzn-s3-demo-bucket";
           String photo = "input.jpg";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           Image image = new Image()
           {
               S3Object = new S3Object()
               {
                   Bucket = bucket,
                   Name = photo
               }
           };
   
           IndexFacesRequest indexFacesRequest = new IndexFacesRequest()
           {
               Image = image,
               CollectionId = collectionId,
               ExternalImageId = photo,
               DetectionAttributes = new List<String>(){ "ALL" }
           };
   
           IndexFacesResponse indexFacesResponse = rekognitionClient.IndexFaces(indexFacesRequest);
   
           Console.WriteLine(photo + " added");
           foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
               Console.WriteLine("Face detected: Faceid is " +
                  faceRecord.Face.FaceId);
       }
   }
   ```

------

## IndexFaces 작업 요청
<a name="indexfaces-request"></a>

`IndexFaces`에 대한 입력은 인덱스를 생성할 이미지와, 얼굴을 추가할 모음입니다.

```
{
    "CollectionId": "MyCollection",
    "Image": {
        "S3Object": {
            "Bucket": "bucket",
            "Name": "input.jpg"
        }
    },
    "ExternalImageId": "input.jpg",
    "DetectionAttributes": [
        "DEFAULT"
    ],
    "MaxFaces": 1,
    "QualityFilter": "AUTO"
}
```

## IndexFaces 작업 응답
<a name="indexfaces-operation-response"></a>

`IndexFaces`는 이미지에서 감지된 얼굴에 대한 정보를 반환합니다. 예를 들어 다음 JSON 응답에는 입력 이미지에서 감지된 얼굴의 기본 감지 속성이 포함됩니다. 이 예제에서는 `MaxFaces` 입력 파라미터의 값이 초과되어 인덱싱되지 않은 얼굴도 보여줍니다. `Reasons` 배열에는 *EXCEEDS\$1MAX\$1FACES*가 포함되어 있습니다. 화질로 인해 얼굴이 인덱싱되지 않은 경우 `Reasons`에는 *LOW\$1SHARPNESS* 또는 *LOW\$1BRIGHTNESS* 등의 값이 포함되어 있습니다. 자세한 내용은 [UnindexedFace](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UnindexedFace.html)를 참조하십시오.

```
{
    "FaceModelVersion": "3.0",
    "FaceRecords": [
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.3247932195663452,
                    "Left": 0.5055555701255798,
                    "Top": 0.2743072211742401,
                    "Width": 0.21444444358348846
                },
                "Confidence": 99.99998474121094,
                "ExternalImageId": "input.jpg",
                "FaceId": "b86e2392-9da1-459b-af68-49118dc16f87",
                "ImageId": "09f43d92-02b6-5cea-8fbd-9f187db2050d"
            },
            "FaceDetail": {
                "BoundingBox": {
                    "Height": 0.3247932195663452,
                    "Left": 0.5055555701255798,
                    "Top": 0.2743072211742401,
                    "Width": 0.21444444358348846
                },
                "Confidence": 99.99998474121094,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.5751981735229492,
                        "Y": 0.4010535478591919
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.6511467099189758,
                        "Y": 0.4017036259174347
                    },
                    {
                        "Type": "nose",
                        "X": 0.6314528584480286,
                        "Y": 0.4710812568664551
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.5879443287849426,
                        "Y": 0.5171778798103333
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.6444502472877502,
                        "Y": 0.5164633989334106
                    }
                ],
                "Pose": {
                    "Pitch": -10.313642501831055,
                    "Roll": -1.0316886901855469,
                    "Yaw": 18.079818725585938
                },
                "Quality": {
                    "Brightness": 71.2919921875,
                    "Sharpness": 78.74752044677734
                }
            }
        }
    ],
    "OrientationCorrection": "",
    "UnindexedFaces": [
        {
            "FaceDetail": {
                "BoundingBox": {
                    "Height": 0.1329464465379715,
                    "Left": 0.5611110925674438,
                    "Top": 0.6832437515258789,
                    "Width": 0.08777777850627899
                },
                "Confidence": 92.37225341796875,
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.5796897411346436,
                        "Y": 0.7452847957611084
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.6078574657440186,
                        "Y": 0.742687463760376
                    },
                    {
                        "Type": "nose",
                        "X": 0.597953200340271,
                        "Y": 0.7620673179626465
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.5884202122688293,
                        "Y": 0.7920381426811218
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.60627681016922,
                        "Y": 0.7919750809669495
                    }
                ],
                "Pose": {
                    "Pitch": 15.658954620361328,
                    "Roll": -4.583454608917236,
                    "Yaw": 10.558992385864258
                },
                "Quality": {
                    "Brightness": 42.54612350463867,
                    "Sharpness": 86.93206024169922
                }
            },
            "Reasons": [
                "EXCEEDS_MAX_FACES"
            ]
        }
    ]
}
```

모든 얼굴 정보를 가져오려면 `DetectionAttributes` 요청 파라미터에서 'ALL'을 지정합니다. 예를 들어 다음 예제 응답에서 `faceDetail` 요소의 추가 정보에 유의해야 하며 이것은 서버에서 지속되지 않습니다.
+ 25개의 얼굴 표식(앞의 예의 단 5개와 비교)
+ 10개의 얼굴 속성(안경, 수염, 오클루전, 시선 방향 등) 
+ 감정(`emotion` 요소 참조)

`face` 요소는 서버에서 유지되는 메타데이터를 제공합니다.

 `FaceModelVersion`은 모음과 연결된 얼굴 모델의 버전입니다. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.

`OrientationCorrection`은 이미지의 예상 방향입니다. 버전 3보다 높은 얼굴 감지 모델을 사용하는 경우 방향 보정 정보가 반환되지 않습니다. 자세한 내용은 [이미지 방향 및 경계 상자 좌표 가져오기](images-orientation.md) 단원을 참조하십시오.

다음 샘플 응답은 ["ALL"] 을 지정할 때 반환된 JSON을 보여줍니다.

```
{
    "FaceModelVersion": "3.0",
    "FaceRecords": [
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.06333333253860474,
                    "Left": 0.17185185849666595,
                    "Top": 0.7366666793823242,
                    "Width": 0.11061728745698929
                },
                "Confidence": 99.99999237060547,
                "ExternalImageId": "input.jpg",
                "FaceId": "578e2e1b-d0b0-493c-aa39-ba476a421a34",
                "ImageId": "9ba38e68-35b6-5509-9d2e-fcffa75d1653"
            },
            "FaceDetail": {
                "AgeRange": {
                    "High": 25,
                    "Low": 15
                },
                "Beard": {
                    "Confidence": 99.98077392578125,
                    "Value": false
                },
                "BoundingBox": {
                    "Height": 0.06333333253860474,
                    "Left": 0.17185185849666595,
                    "Top": 0.7366666793823242,
                    "Width": 0.11061728745698929
                },
                "Confidence": 99.99999237060547,
                "Emotions": [
                    {
                        "Confidence": 95.40877532958984,
                        "Type": "HAPPY"
                    },
                    {
                        "Confidence": 6.6088080406188965,
                        "Type": "CALM"
                    },
                    {
                        "Confidence": 0.7385611534118652,
                        "Type": "SAD"
                    }
                ],
                 "EyeDirection": {
                    "yaw": 16.299732,
                    "pitch": -6.407457,
                    "confidence": 99.968704
                              }
                "Eyeglasses": {
                    "Confidence": 99.96795654296875,
                    "Value": false
                },
                "EyesOpen": {
                    "Confidence": 64.0671157836914,
                    "Value": true
                },
                "Gender": {
                    "Confidence": 100,
                    "Value": "Female"
                },
                "Landmarks": [
                    {
                        "Type": "eyeLeft",
                        "X": 0.21361233294010162,
                        "Y": 0.757106363773346
                    },
                    {
                        "Type": "eyeRight",
                        "X": 0.2518567442893982,
                        "Y": 0.7599404454231262
                    },
                    {
                        "Type": "nose",
                        "X": 0.2262365221977234,
                        "Y": 0.7711842060089111
                    },
                    {
                        "Type": "mouthLeft",
                        "X": 0.2050037682056427,
                        "Y": 0.7801263332366943
                    },
                    {
                        "Type": "mouthRight",
                        "X": 0.2430567592382431,
                        "Y": 0.7836716771125793
                    },
                    {
                        "Type": "leftPupil",
                        "X": 0.2161938101053238,
                        "Y": 0.756662905216217
                    },
                    {
                        "Type": "rightPupil",
                        "X": 0.2523181438446045,
                        "Y": 0.7603650689125061
                    },
                    {
                        "Type": "leftEyeBrowLeft",
                        "X": 0.20066319406032562,
                        "Y": 0.7501518130302429
                    },
                    {
                        "Type": "leftEyeBrowUp",
                        "X": 0.2130996286869049,
                        "Y": 0.7480520606040955
                    },
                    {
                        "Type": "leftEyeBrowRight",
                        "X": 0.22584207355976105,
                        "Y": 0.7504606246948242
                    },
                    {
                        "Type": "rightEyeBrowLeft",
                        "X": 0.24509544670581818,
                        "Y": 0.7526801824569702
                    },
                    {
                        "Type": "rightEyeBrowUp",
                        "X": 0.2582615911960602,
                        "Y": 0.7516844868659973
                    },
                    {
                        "Type": "rightEyeBrowRight",
                        "X": 0.26881539821624756,
                        "Y": 0.7554477453231812
                    },
                    {
                        "Type": "leftEyeLeft",
                        "X": 0.20624476671218872,
                        "Y": 0.7568746209144592
                    },
                    {
                        "Type": "leftEyeRight",
                        "X": 0.22105035185813904,
                        "Y": 0.7582521438598633
                    },
                    {
                        "Type": "leftEyeUp",
                        "X": 0.21401576697826385,
                        "Y": 0.7553104162216187
                    },
                    {
                        "Type": "leftEyeDown",
                        "X": 0.21317370235919952,
                        "Y": 0.7584449648857117
                    },
                    {
                        "Type": "rightEyeLeft",
                        "X": 0.24393919110298157,
                        "Y": 0.7600628137588501
                    },
                    {
                        "Type": "rightEyeRight",
                        "X": 0.2598416209220886,
                        "Y": 0.7605880498886108
                    },
                    {
                        "Type": "rightEyeUp",
                        "X": 0.2519053518772125,
                        "Y": 0.7582084536552429
                    },
                    {
                        "Type": "rightEyeDown",
                        "X": 0.25177454948425293,
                        "Y": 0.7612871527671814
                    },
                    {
                        "Type": "noseLeft",
                        "X": 0.2185886949300766,
                        "Y": 0.774715781211853
                    },
                    {
                        "Type": "noseRight",
                        "X": 0.23328955471515656,
                        "Y": 0.7759330868721008
                    },
                    {
                        "Type": "mouthUp",
                        "X": 0.22446128726005554,
                        "Y": 0.7805567383766174
                    },
                    {
                        "Type": "mouthDown",
                        "X": 0.22087252140045166,
                        "Y": 0.7891407608985901
                    }
                ],
                "MouthOpen": {
                    "Confidence": 95.87068939208984,
                    "Value": false
                },
                "Mustache": {
                    "Confidence": 99.9828109741211,
                    "Value": false
                },
                "Pose": {
                    "Pitch": -0.9409101605415344,
                    "Roll": 7.233824253082275,
                    "Yaw": -2.3602254390716553
                },
                "Quality": {
                    "Brightness": 32.01998519897461,
                    "Sharpness": 93.67259216308594
                },
                "Smile": {
                    "Confidence": 86.7142105102539,
                    "Value": true
                },
                "Sunglasses": {
                    "Confidence": 97.38925170898438,
                    "Value": false
                }
            }
        }
    ],
    "OrientationCorrection": "ROTATE_0"
    "UnindexedFaces": []
}
```

# 컬렉션의 얼굴 및 연결된 사용자 나열
<a name="list-faces-in-collection-procedure"></a>

[ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) 작업을 사용하여 컬렉션의 얼굴과 그에 연결된 사용자를 나열할 수 있습니다.

자세한 내용은 [컬렉션에서 얼굴 관리](managing-face-collections.md#collections-index-faces) 단원을 참조하십시오.



**모음에 있는 얼굴을 나열하려면(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. 다음 예제를 사용하여 `ListFaces` 작업을 호출합니다.

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

   이 예제는 모음의 얼굴 목록을 표시합니다.

   `collectionId`의 값을 원하는 모음으로 변경합니다.

   ```
   //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.Face;
   import com.amazonaws.services.rekognition.model.ListFacesRequest;
   import com.amazonaws.services.rekognition.model.ListFacesResult;
   import java.util.List;
   import com.fasterxml.jackson.databind.ObjectMapper;
   
   
   
   public class ListFacesInCollection {
       public static final String collectionId = "MyCollection";
   
      public static void main(String[] args) throws Exception {
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         ObjectMapper objectMapper = new ObjectMapper();
   
         ListFacesResult listFacesResult = null;
         System.out.println("Faces in collection " + collectionId);
   
         String paginationToken = null;
         do {
            if (listFacesResult != null) {
               paginationToken = listFacesResult.getNextToken();
            }
            
            ListFacesRequest listFacesRequest = new ListFacesRequest()
                    .withCollectionId(collectionId)
                    .withMaxResults(1)
                    .withNextToken(paginationToken);
           
            listFacesResult =  rekognitionClient.listFaces(listFacesRequest);
            List < Face > faces = listFacesResult.getFaces();
            for (Face face: faces) {
               System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                  .writeValueAsString(face));
            }
         } while (listFacesResult != null && listFacesResult.getNextToken() !=
            null);
      }
   
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/ListFacesInCollection.java)에서 확인하세요.

   ```
   // snippet-start:[rekognition.java2.list_faces_collection.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.Face;
   import software.amazon.awssdk.services.rekognition.model.ListFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.ListFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   // snippet-end:[rekognition.java2.list_faces_collection.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 ListFacesInCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId>\n\n" +
               "Where:\n" +
               "   collectionId - The name of the collection. \n\n";
   
           if (args.length < 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Faces in collection " + collectionId);
           listFacesCollection(rekClient, collectionId) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.list_faces_collection.main]
       public static void listFacesCollection(RekognitionClient rekClient, String collectionId ) {
           try {
               ListFacesRequest facesRequest = ListFacesRequest.builder()
                   .collectionId(collectionId)
                   .maxResults(10)
                   .build();
   
               ListFacesResponse facesResponse = rekClient.listFaces(facesRequest);
               List<Face> faces = facesResponse.faces();
               for (Face face: faces) {
                   System.out.println("Confidence level there is a face: "+face.confidence());
                   System.out.println("The face Id value is "+face.faceId());
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
            }
         }
       // snippet-end:[rekognition.java2.list_faces_collection.main]
     }
   ```

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

   이 AWS CLI 명령은 `list-faces` CLI 작업에 대한 JSON 출력을 표시합니다. `collection-id`의 값을, 목록을 조회할 모음의 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition list-faces --collection-id "collection-id"  --profile profile-name
   ```

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

   이 예제는 모음의 얼굴 목록을 표시합니다.

   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 list_faces_in_collection(collection_id):
       maxResults = 2
       faces_count = 0
       tokens = True
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
       response = client.list_faces(CollectionId=collection_id,
                                    MaxResults=maxResults)
   
       print('Faces in collection ' + collection_id)
   
       while tokens:
   
           faces = response['Faces']
   
           for face in faces:
               print(face)
               faces_count += 1
           if 'NextToken' in response:
               nextToken = response['NextToken']
               response = client.list_faces(CollectionId=collection_id,
                                            NextToken=nextToken, MaxResults=maxResults)
           else:
               tokens = False
       return faces_count
   
   def main():
       collection_id = 'collection-id'
       faces_count = list_faces_in_collection(collection_id)
       print("faces count: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 모음의 얼굴 목록을 표시합니다.

   `collectionId`의 값을 원하는 모음으로 변경합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class ListFaces
   {
       public static void Example()
       {
           String collectionId = "MyCollection";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           ListFacesResponse listFacesResponse = null;
           Console.WriteLine("Faces in collection " + collectionId);
   
           String paginationToken = null;
           do
           {
               if (listFacesResponse != null)
                   paginationToken = listFacesResponse.NextToken;
   
               ListFacesRequest listFacesRequest = new ListFacesRequest()
               {
                   CollectionId = collectionId,
                   MaxResults = 1,
                   NextToken = paginationToken
               };
   
               listFacesResponse = rekognitionClient.ListFaces(listFacesRequest);
               foreach(Face face in listFacesResponse.Faces)
                   Console.WriteLine(face.FaceId);
           } while (listFacesResponse != null && !String.IsNullOrEmpty(listFacesResponse.NextToken));
       }
   }
   ```

------

## ListFaces 작업 요청
<a name="listfaces-request"></a>

`ListFaces`에 대한 입력은 얼굴 목록을 조회하려는 모음의 ID입니다. `MaxResults`는 반환할 최대 얼굴 수입니다. 또한 ListFaces는 결과를 필터링할 때 사용할 얼굴 ID 목록과 지정된 사용자와 연결된 얼굴만 나열하기 위해 제공된 사용자 ID를 가져옵니다.

```
{
    "CollectionId": "MyCollection",
    "MaxResults": 1
}
```

응답의 얼굴이, `MaxResults`가 요청한 것보다 많으면 후속 `ListFaces` 호출에서 다음 결과 집합을 가져오는 데 사용할 수 있는 토큰이 반환됩니다. 예제:

```
{
    "CollectionId": "MyCollection",
    "NextToken": "sm+5ythT3aeEVIR4WA....",
    "MaxResults": 1
}
```

## ListFaces 작업 응답
<a name="listfaces-response"></a>

`ListFaces`의 응답은 지정한 모음에 저장된 얼굴 메타데이터에 대한 정보입니다.
+ **FaceModelVersion** – 컬렉션과 연결된 얼굴 모델의 버전입니다. 자세한 내용은 [모델 버전 관리 이해](face-detection-model.md) 단원을 참조하십시오.
+  **Faces** – 컬렉션에 있는 얼굴에 대한 정보입니다. 이에는 [BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html), 신뢰도, 이미지 식별자 및 얼굴 ID에 관한 정보가 포함됩니다. 자세한 내용은 [Face](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Face.html)를 참조하십시오.
+  **NextToken** – 다음 결과 집합을 가져오는 데 사용되는 토큰입니다.

```
{
    "FaceModelVersion": "6.0", 
    "Faces": [  
        {
            "Confidence": 99.76940155029297, 
            "IndexFacesModelVersion": "6.0", 
            "UserId": "demoUser2", 
            "ImageId": "56a0ca74-1c83-39dd-b363-051a64168a65", 
            "BoundingBox": {
                "Width": 0.03177810087800026, 
                "Top": 0.36568498611450195, 
                "Left": 0.3453829884529114, 
                "Height": 0.056759100407361984
            }, 
            "FaceId": "c92265d4-5f9c-43af-a58e-12be0ce02bc3"
        },
        {
            "BoundingBox": {
                "Width": 0.03254450112581253, 
                "Top": 0.6080359816551208, 
                "Left": 0.5160620212554932, 
                "Height": 0.06347999721765518
            }, 
            "IndexFacesModelVersion": "6.0", 
            "FaceId": "851cb847-dccc-4fea-9309-9f4805967855", 
            "Confidence": 99.94369506835938, 
            "ImageId": "a8aed589-ceec-35f7-9c04-82e0b546b024"
        },
        {
            "BoundingBox": {
                "Width": 0.03094629943370819, 
                "Top": 0.4218429923057556, 
                "Left": 0.6513839960098267, 
                "Height": 0.05266290158033371
            }, 
            "IndexFacesModelVersion": "6.0", 
            "FaceId": "c0eb3b65-24a0-41e1-b23a-1908b1aaeac1", 
            "Confidence": 99.82969665527344, 
            "ImageId": "56a0ca74-1c83-39dd-b363-051a64168a65"
        }
    ]
}
```

# 컬렉션에서 얼굴 삭제
<a name="delete-faces-procedure"></a>

[DeleteFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteFaces.html) 작업을 사용하여 컬렉션에서 얼굴을 삭제할 수 있습니다. 자세한 내용은 [컬렉션에서 얼굴 관리](managing-face-collections.md#collections-index-faces) 단원을 참조하십시오.



**컬렉션에서 얼굴 삭제**

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. 다음 예제를 사용하여 `DeleteFaces` 작업을 호출합니다.

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

   이 예제는 모음에서 한 개의 얼굴을 삭제합니다.

   `collectionId`의 값을, 삭제하려는 얼굴을 포함하는 모음으로 변경합니다. `faces`의 값을, 삭제하려는 얼굴 ID로 변경합니다. 여러 얼굴을 삭제하려면 `faces` 배열에 얼굴 ID를 추가합니다.

   ```
   //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.DeleteFacesRequest;
   import com.amazonaws.services.rekognition.model.DeleteFacesResult;
   
   import java.util.List;
   
   
   public class DeleteFacesFromCollection {
      public static final String collectionId = "MyCollection";
      public static final String faces[] = {"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"};
   
      public static void main(String[] args) throws Exception {
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
        
         
         DeleteFacesRequest deleteFacesRequest = new DeleteFacesRequest()
                 .withCollectionId(collectionId)
                 .withFaceIds(faces);
        
         DeleteFacesResult deleteFacesResult=rekognitionClient.deleteFaces(deleteFacesRequest);
         
        
         List < String > faceRecords = deleteFacesResult.getDeletedFaces();
         System.out.println(Integer.toString(faceRecords.size()) + " face(s) deleted:");
         for (String face: faceRecords) {
            System.out.println("FaceID: " + face);
         }
      }
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java)에서 확인하세요.

   ```
   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.DeleteFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   // snippet-end:[rekognition.java2.delete_faces_collection.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 DeleteFacesFromCollection {
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <faceId> \n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection from which faces are deleted. \n\n" +
               "   faceId - The id of the face to delete. \n\n";
   
           if (args.length != 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String faceId = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Deleting collection: " + collectionId);
           deleteFacesCollection(rekClient, collectionId, faceId);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.delete_faces_collection.main]
       public static void deleteFacesCollection(RekognitionClient rekClient,
                                                String collectionId,
                                                String faceId) {
   
           try {
               DeleteFacesRequest deleteFacesRequest = DeleteFacesRequest.builder()
                   .collectionId(collectionId)
                   .faceIds(faceId)
                   .build();
   
               rekClient.deleteFaces(deleteFacesRequest);
               System.out.println("The face was deleted from the collection.");
   
           } catch(RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.delete_faces_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `delete-faces` CLI 작업에 대한 JSON 출력을 표시합니다. `collection-id`의 값을, 삭제하려는 얼굴을 포함하는 모음의 이름으로 바꿉니다. `face-ids`의 값을, 삭제하려는 얼굴 ID 배열로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition delete-faces --collection-id "collection-id" --face-ids "faceid" --profile profile-name
   ```

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

   이 예제는 모음에서 한 개의 얼굴을 삭제합니다.

   `collectionId`의 값을, 삭제하려는 얼굴을 포함하는 모음으로 변경합니다. `faces`의 값을, 삭제하려는 얼굴 ID로 변경합니다. 여러 얼굴을 삭제하려면 `faces` 배열에 얼굴 ID를 추가합니다. 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 delete_faces_from_collection(collection_id, faces):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
       response = client.delete_faces(CollectionId=collection_id,
                                      FaceIds=faces)
   
       print(str(len(response['DeletedFaces'])) + ' faces deleted:')
       for faceId in response['DeletedFaces']:
           print(faceId)
       return len(response['DeletedFaces'])
   
   
   def main():
       collection_id = 'collection-id'
       faces = []
       faces.append("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
   
       faces_count = delete_faces_from_collection(collection_id, faces)
       print("deleted faces count: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 모음에서 한 개의 얼굴을 삭제합니다.

   `collectionId`의 값을, 삭제하려는 얼굴을 포함하는 모음으로 변경합니다. `faces`의 값을, 삭제하려는 얼굴 ID로 변경합니다. 여러 얼굴을 삭제하려면 `faces` 목록에 얼굴 ID를 추가합니다.

   ```
   //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 DeleteFaces
   {
       public static void Example()
       {
           String collectionId = "MyCollection";
           List<String> faces = new List<String>() { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" };
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           DeleteFacesRequest deleteFacesRequest = new DeleteFacesRequest()
           {
               CollectionId = collectionId,
               FaceIds = faces
           };
   
           DeleteFacesResponse deleteFacesResponse = rekognitionClient.DeleteFaces(deleteFacesRequest);
           foreach (String face in deleteFacesResponse.DeletedFaces)
               Console.WriteLine("FaceID: " + face);
       }
   }
   ```

------

## DeleteFaces 작업 요청
<a name="deletefaces-request"></a>

`DeleteFaces`에 대한 입력은 얼굴을 포함하는 모음의 ID와, 삭제할 얼굴의 얼굴 ID 배열입니다.

```
{
    "CollectionId": "MyCollection",
    "FaceIds": [
        "daf29cac-f910-41e9-851f-6eeb0e08f973"
    ]
}
```

## DeleteFaces 작업 응답
<a name="deletefaces-operation-response"></a>

`DeleteFaces` 응답에는 삭제된 얼굴의 얼굴 ID 배열이 들어 있습니다.

```
{
    "DeletedFaces": [
        "daf29cac-f910-41e9-851f-6eeb0e08f973"
    ]
}
```

 입력에 제공된 얼굴 ID가 현재 사용자와 연결되어 있는 경우 타당한 이유가 있는 UnsuccessfulFaceDeletions의 일부로 반환됩니다.

```
{
   "DeletedFaces": [
        "daf29cac-f910-41e9-851f-6eeb0e08f973"
    ],
     "UnsuccessfulFaceDeletions" : [
        {
           "FaceId" : "0b683aed-a0f1-48b2-9b5e-139e9cc2a757",
           "UserId" : "demoUser1",
           "Reason" : ["ASSOCIATED_TO_AN_EXISTING_USER"]
        }
     ]
}
```

# 사용자 생성
<a name="create-user"></a>

[CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html) 작업을 사용하여 귀하가 제공하는 고유한 사용자 ID로 컬렉션에 새 사용자를 생성할 수 있습니다. 그런 다음 새로 만든 사용자와 얼굴 여러 개를 연결할 수 있습니다.

**사용자를 생성하려면(SDK)**

1. 아직 설정하지 않았다면 다음과 같이 하세요.

   1. `AmazonRekognitionFullAccess` 권한이 있는 IAM 사용자 계정을 생성하거나 업데이트합니다. 자세한 내용은 [1단계: AWS 계정 설정 및 사용자 생성](setting-up.md#setting-up-iam) 단원을 참조하십시오.

   1.  AWS CLI 및 AWS SDKs를 설치하고 구성합니다. 자세한 내용은 [2단계: AWS CLI 및 AWS SDKs 설정](setup-awscli-sdk.md) 단원을 참조하십시오.

1. 다음 예제를 사용하여 `CreateUser` 작업을 호출합니다.

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

   이 Java 코드 예제는 사용자를 생성합니다.

   ```
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.CreateUserRequest;
   import com.amazonaws.services.rekognition.model.CreateUserResult;
   
   
   public class CreateUser {
   
       public static void main(String[] args) throws Exception {
   
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           //Replace collectionId and userId with the name of the user that you want to create in that target collection.
   
           String collectionId = "MyCollection";
           String userId = "demoUser";
           System.out.println("Creating new user: " +
                   userId);
   
           CreateUserRequest request = new CreateUserRequest()
                   .withCollectionId(collectionId)
                   .withUserId(userId);
   
           rekognitionClient.createUser(request);
       }
   
   }
   ```

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

   이 AWS CLI 명령은 `create-user` CLI 작업을 사용하여 사용자를 생성합니다.

   ```
   aws rekognition create-user --user-id user-id --collection-id collection-name --region region-name
   --client-request-token request-token
   ```

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

   이 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.)
   
   import boto3
   from botocore.exceptions import ClientError
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def create_user(collection_id, user_id):
       """
       Creates a new User within a collection specified by CollectionId. 
       Takes UserId as a parameter, which is a user provided ID which 
       should be unique within the collection.
   
       :param collection_id: The ID of the collection where the indexed faces will be stored at.
       :param user_id: ID for the UserID to be created. This ID needs to be unique within the collection.
       
       :return: The indexFaces response
       """
       try:
           logger.info(f'Creating user: {collection_id}, {user_id}')
           client.create_user(
               CollectionId=collection_id,
               UserId=user_id
           )
       except ClientError:
           logger.exception(f'Failed to create user with given user id: {user_id}')
           raise
   
   def main():
       collection_id = "collection-id"
       user_id = "user-id"
       create_user(collection_id, user_id)
   
   if __name__ == "__main__":
       main()
   ```

------
#### [ Go ]

   이 Go 코드 예제에서는 AWS Go SDK V2를 사용하고 사용자를 생성합니다.

   ```
   package main
   
   import (
   	"context"
   	"fmt"
   	"log"
   
   	"github.com/aws/aws-sdk-go-v2/aws"
   	"github.com/aws/aws-sdk-go-v2/config"
   	"github.com/aws/aws-sdk-go-v2/service/rekognition"
   )
   
   func main() {
   	// Load the AWS SDK configuration
   	cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-west-2"))
   	if err != nil {
   		log.Fatalf("Failed to load configuration: %v", err)
   	}
   
   	// Create a Rekognition client
   	client := rekognition.NewFromConfig(cfg)
   
   	// Set up the input parameters
   	input := &rekognition.CreateUserInput{
   		CollectionId: aws.String("my-new-collection"), // Replace with your collection ID
   		UserId:       aws.String("user12345678910"),   // Replace with desired user ID
   	}
   
   	// Call the CreateUser operation
   	result, err := client.CreateUser(context.TODO(), input)
   	if err != nil {
   		log.Fatalf("Failed to create user: %v", err)
   	}
   
   	// Print out the results
   	fmt.Printf("User created successfully:\n")
   
   }
   ```

------

# 사용자 삭제
<a name="delete-user"></a>

[DeleteUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteUser.html) 작업을 사용하여 제공된 UserID를 기반으로 컬렉션에서 사용자를 삭제할 수 있습니다. UserID와 연결된 모든 얼굴은 해당 UserID가 삭제되기 전에 UserID와의 연결이 해제된다는 점에 유의하십시오.

**사용자를 삭제하려면(SDK)**

1. 아직 설정하지 않았다면 다음과 같이 하세요.

   1. `AmazonRekognitionFullAccess` 권한이 있는 IAM 사용자 계정을 생성하거나 업데이트합니다. 자세한 내용은 [1단계: AWS 계정 설정 및 사용자 생성](setting-up.md#setting-up-iam) 단원을 참조하십시오.

   1.  AWS CLI 및 AWS SDKs를 설치하고 구성합니다. 자세한 내용은 [2단계: AWS CLI 및 AWS SDKs 설정](setup-awscli-sdk.md) 단원을 참조하십시오.

1. 다음 예제를 사용하여 `DeleteUser` 작업을 호출합니다.

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

   이 Java 코드 예제는 사용자를 삭제합니다.

   ```
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.DeleteUserRequest;
   import com.amazonaws.services.rekognition.model.DeleteUserResult;
   
   
   public class DeleteUser {
   
       public static void main(String[] args) throws Exception {
   
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           //Replace collectionId and userId with the name of the user that you want to delete from that target collection.
   
           String collectionId = "MyCollection";
           String userId = "demoUser";
           System.out.println("Deleting existing user: " +
                   userId);
   
           DeleteUserRequest request = new DeleteUserRequest()
                   .withCollectionId(collectionId)
                   .withUserId(userId);
   
           rekognitionClient.deleteUser(request);
       }
   
   }
   ```

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

   이 AWS CLI 명령은 `create-user` CLI 작업을 사용하여 사용자를 삭제합니다.

   ```
   aws rekognition delete-user --collection-id MyCollection 
   --user-id user-id --collection-id collection-name --region region-name
   ```

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

   이 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.)
   
   import boto3
   from botocore.exceptions import ClientError
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def delete_user(collection_id, user_id):
           """
           Delete the user from the given collection
   
           :param collection_id: The ID of the collection where user is stored.
           :param user_id: The ID of the user in the collection to delete.
           """
           logger.info(f'Deleting user: {collection_id}, {user_id}')
           try:
               client.delete_user(
                   CollectionId=collection_id,
                   UserId=user_id
               )
           except ClientError:
               logger.exception(f'Failed to delete user with given user id: {user_id}')
               raise
   
   def main():
       collection_id = "collection-id"
       user_id = "user-id"
       delete_user(collection_id, user_id)
   
   if __name__ == "__main__":
       main()
   ```

------

# 얼굴을 사용자에 연결
<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"
        }
    ]
}
```

# 사용자에게서 얼굴 연결 해제
<a name="disassociate-faces"></a>

[DisassociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DisassociateFaces.html) 작업을 사용하여 사용자 ID와 얼굴 ID 간의 연결을 제거할 수 있습니다.

**얼굴을 연결 해제하려면(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. 다음 예제를 사용하여 `DisassociateFaces` 작업을 호출합니다.

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

   이 Java 예제는 `DisassociateFaces` 작업을 사용해 FaceID와 UserID 간의 연결을 제거합니다.

   ```
   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.DisassociateFacesRequest;
   import com.amazonaws.services.rekognition.model.DisassociateFacesResult;
   
   
   public class DisassociateFaces {
   
       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 disassociated from
              @faceIds: The list of face IDs that will get disassociated from the given user
            */
   
           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);
   
           System.out.println("Disassociating faces from existing user: " +
                   userId);
   
           DisassociateFacesRequest request = new DisassociateFacesRequest()
                   .withCollectionId(collectionId)
                   .withUserId(userId)
                   .withFaceIds(faceIds)
   
           DisassociateFacesResult result = rekognitionClient.disassociateFaces(request);
   
           System.out.println("Successful face disassociations: " + result.getDisassociatedFaces().size());
           System.out.println("Unsuccessful face disassociations: " + result.getUnsuccessfulFaceDisassociations().size());
       }
   
   }
   ```

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

   이 AWS CLI 명령은 FaceID와 UserID 간의 연결을 `DisassociateFaces` 작업과 함께 제거합니다.

   ```
   aws rekognition disassociate-faces --face-ids list-of-face-ids
   --user-id user-id --collection-id collection-name --region region-name
   ```

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

   다음 예제는 `DisassociateFaces` 작업을 사용해 FaceID와 UserID 간의 연결을 제거합니다.

   ```
   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 disassociate_faces(collection_id, user_id, face_ids):
       """
       Disassociate 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 disassociate faces from
       :param face_ids: The list of face IDs to be disassociated from the given user
   
       :return: response of AssociateFaces API
       """
       logger.info(f'Disssociating faces from user: {user_id}, {face_ids}')
       try:
           response = client.disassociate_faces(
               CollectionId=collection_id,
               UserId=user_id,
               FaceIds=face_ids
           )
           print(f'- disassociated {len(response["DisassociatedFaces"])} faces')
       except ClientError:
           logger.exception("Failed to disassociate faces from the given user")
           raise
       else:
           print(response)
           return response
   
   def main():
       face_ids = ["faceId1", "faceId2"]
       collection_id = "collection-id"
       user_id = "user-id"
       disassociate_faces(collection_id, user_id, face_ids)
   
   if __name__ == "__main__":
       main()
   ```

------

## DisassociateFaces 작업 응답
<a name="disassociate-faces-response"></a>

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

```
{
    "UserStatus": "UPDATING", 
    "DisassociatedFaces": [
        {
            "FaceId": "c92265d4-5f9c-43af-a58e-12be0ce02bc3"
        }
    ], 
    "UnsuccessfulFaceDisassociations": [
        {
            "Reasons": [
                "ASSOCIATED_TO_A_DIFFERENT_IDENTITY"
            ], 
            "FaceId": "f5817d37-94f6-4335-bfee-6cf79a3d806e", 
            "UserId": "demoUser1"
        }
    ]
}
```

# 컬렉션에서 사용자 나열
<a name="list-users"></a>

[ListUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListUsers.html) 작업을 사용하여 UserIds 및 UserStatus를 나열할 수 있습니다. UserID와 연결된 FaceID를 보려면 [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.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. 다음 예제를 사용하여 `ListUsers` 작업을 호출합니다.

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

   이 Java 예제는 `ListUsers` 작업을 사용해 컬렉션에 있는 사용자를 나열합니다.

   ```
   import java.util.List;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.ListUsersRequest;
   import com.amazonaws.services.rekognition.model.ListUsersResult;
   import com.amazonaws.services.rekognition.model.User;
   
   public class ListUsers {
   
       public static void main(String[] args) throws Exception {
   
   
           AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();
   
   
           System.out.println("Listing users");
           int limit = 10;
           ListUsersResult listUsersResult = null;
           String paginationToken = null;
           do {
               if (listUsersResult != null) {
                   paginationToken = listUsersResult.getNextToken();
               }
               ListUsersRequest request = new ListUsersRequest()
                       .withCollectionId(collectionId)
                       .withMaxResults(limit)
                       .withNextToken(paginationToken);
               listUsersResult = amazonRekognition.listUsers(request);
   
               List<User> users = listUsersResult.getUsers();
               for (User currentUser: users) {
                   System.out.println(currentUser.getUserId() + " : " + currentUser.getUserStatus());
               }
           } while (listUsersResult.getNextToken() != null);
       }
   }
   ```

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

   이 AWS CLI 명령은 `ListUsers` 작업이 있는 컬렉션의 사용자를 나열합니다.

   ```
   aws rekognition list-users --collection-id collection-id --max-results number-of-max-results
   ```

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

   다음 예제에서는 `ListUsers` 작업으로 컬렉션에 있는 사용자를 나열합니다.

   ```
   # 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
   from botocore.exceptions import ClientError
   import logging
   from pprint import pprint
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   
   def list_users(collection_id):
       """
       List all users from the given collection
   
       :param collection_id: The ID of the collection where user is stored.
   
       :return: response that contains list of Users found within given collection
       """
       logger.info(f'Listing the users in collection: {collection_id}')
       try:
           response = client.list_users(
               CollectionId=collection_id
           )
           pprint(response["Users"])
       except ClientError:
           logger.exception(f'Failed to list all user from given collection: {collection_id}')
           raise
       else:
           return response
   
   def main():
       collection_id = "collection-id"
       list_users(collection_id)
   
   if __name__ == "__main__":
       main()
   ```

------

## ListUsers 작업 응답
<a name="list-users-response"></a>

ListUsers에 보낸 요청에 대한 응답에는 컬렉션의 `Users` 목록과 User의 `UsedId` 및 `UserStatus`가 포함됩니다.

```
{
    "NextToken": "B1asJT3bAb/ttuGgPFV8BZoBZyGQzlUHXbuTNLh48a6enU7kXKw43hpOwizW7LOk/Gk7Em09lznoq6+FcDCcSq2olrn7A98BLkt5keu+ZRVRUTyrXtT6J7Hmp+ieQ2an6Zu0qzPfcdPeaJ9eAxG2d0WNrzJgi5hvmjoiSTTfKX3MQz1sduWQkvAAs4hZfhZoKFahFlqWofshCXa/FHAAY3PL1PjxXbkNeSSMq8V7i1MlKCdrPVykCv9MokpPt7jtNvKPEZGUhxgBTFMxNWLEcFnzAiCWDg91dFy/LalshPjXA9UVc5Gx9vIJNQ/eO3cQRghAkCT3FOAiXsLAnA015ODTomZpWWVpqB21wKpI3LYmfAVFrDPGzpbTVlRmLsJm41bkmnBBBw9+DHz1Jn7zW+qc5Fs3yaHu0f51Xg==", 
    "Users": [
        {
            "UserId": "demoUser4", 
            "UserStatus": "CREATED"
        }, 
        {
            "UserId": "demoUser2", 
            "UserStatus": "CREATED"
        }
    ]
}
```

# 얼굴 ID로 얼굴 검색
<a name="search-face-with-id-procedure"></a>

[SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) 작업을 사용하여 제공된 이미지에서 가장 큰 얼굴과 일치하는 컬렉션에서 사용자를 검색할 수 있습니다.

얼굴이 감지되고 컬렉션에 추가되면 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 작업 응답에서 얼굴 ID가 반환됩니다. 자세한 내용은 [컬렉션에서 얼굴 관리](managing-face-collections.md#collections-index-faces) 단원을 참조하십시오.



**얼굴 ID(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. 다음 예제를 사용하여 `SearchFaces` 작업을 호출합니다.

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

   이 예제는 ID로 식별한 얼굴과 일치하는 얼굴에 대한 정보를 표시합니다.

   `collectionID`의 값을, 원하는 얼굴이 있는 모음으로 변경합니다. `faceId`의 값을, 찾으려는 얼굴의 식별자로 변경합니다.

   ```
   //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.fasterxml.jackson.databind.ObjectMapper;
   import com.amazonaws.services.rekognition.model.FaceMatch;
   import com.amazonaws.services.rekognition.model.SearchFacesRequest;
   import com.amazonaws.services.rekognition.model.SearchFacesResult;
   import java.util.List;
   
   
     public class SearchFaceMatchingIdCollection {
         public static final String collectionId = "MyCollection";
         public static final String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
         
       public static void main(String[] args) throws Exception {
           
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
         
           ObjectMapper objectMapper = new ObjectMapper();
         // Search collection for faces matching the face id.
         
         SearchFacesRequest searchFacesRequest = new SearchFacesRequest()
                 .withCollectionId(collectionId)
                 .withFaceId(faceId)
                 .withFaceMatchThreshold(70F)
                 .withMaxFaces(2);
              
          SearchFacesResult searchFacesByIdResult = 
                  rekognitionClient.searchFaces(searchFacesRequest);
   
          System.out.println("Face matching faceId " + faceId);
         List < FaceMatch > faceImageMatches = searchFacesByIdResult.getFaceMatches();
         for (FaceMatch face: faceImageMatches) {
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(face));
            
            System.out.println();
         }
       }
   
   }
   ```

   예제 코드를 실행합니다. 일치하는 얼굴에 대한 정보가 표시됩니다.

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java)에서 확인하세요.

   ```
   // snippet-start:[rekognition.java2.match_faces_collection.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.SearchFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceMatch;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   // snippet-end:[rekognition.java2.match_faces_collection.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 SearchFaceMatchingIdCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <sourceImage>\n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection.  \n" +
               "   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String faceId = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Searching for a face in a collections");
           searchFacebyId(rekClient, collectionId, faceId ) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.match_faces_collection.main]
       public static void searchFacebyId(RekognitionClient rekClient,String collectionId, String faceId) {
   
           try {
               SearchFacesRequest searchFacesRequest = SearchFacesRequest.builder()
                   .collectionId(collectionId)
                   .faceId(faceId)
                   .faceMatchThreshold(70F)
                   .maxFaces(2)
                   .build();
   
               SearchFacesResponse imageResponse = rekClient.searchFaces(searchFacesRequest) ;
               System.out.println("Faces matching in the collection");
               List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
               for (FaceMatch face: faceImageMatches) {
                   System.out.println("The similarity level is  "+face.similarity());
                   System.out.println();
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.match_faces_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `search-faces` CLI 작업에 대한 JSON 출력을 표시합니다. 검색하려는 얼굴 식별자로 `face-id` 값을 바꾸고, 검색하려는 모음으로 `collection-id`를 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition search-faces --face-id face-id --collection-id "collection-id" --profile profile-name
   ```

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

   이 예제는 ID로 식별한 얼굴과 일치하는 얼굴에 대한 정보를 표시합니다.

   `collectionID`의 값을, 원하는 얼굴이 있는 모음으로 변경합니다. `faceId`의 값을, 찾으려는 얼굴의 식별자로 변경합니다. 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 search_face_in_collection(face_id, collection_id):
       threshold = 90
       max_faces = 2
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.search_faces(CollectionId=collection_id,
                                      FaceId=face_id,
                                      FaceMatchThreshold=threshold,
                                      MaxFaces=max_faces)
   
       face_matches = response['FaceMatches']
       print('Matching faces')
       for match in face_matches:
           print('FaceId:' + match['Face']['FaceId'])
           print('Similarity: ' + "{:.2f}".format(match['Similarity']) + "%")
   
       return len(face_matches)
   
   def main():
       face_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
       collection_id = 'collection-id'
   
       faces = []
       faces.append(face_id)
   
       faces_count = search_face_in_collection(face_id, collection_id)
       print("faces found: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   이 예제는 ID로 식별한 얼굴과 일치하는 얼굴에 대한 정보를 표시합니다.

   `collectionID`의 값을, 원하는 얼굴이 있는 모음으로 변경합니다. `faceId`의 값을, 찾으려는 얼굴의 식별자로 변경합니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class SearchFacesMatchingId
   {
       public static void Example()
       {
           String collectionId = "MyCollection";
           String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           // Search collection for faces matching the face id.
   
           SearchFacesRequest searchFacesRequest = new SearchFacesRequest()
           {
               CollectionId = collectionId,
               FaceId = faceId,
               FaceMatchThreshold = 70F,
               MaxFaces = 2
           };
   
           SearchFacesResponse searchFacesResponse = rekognitionClient.SearchFaces(searchFacesRequest);
   
           Console.WriteLine("Face matching faceId " + faceId);
   
           Console.WriteLine("Matche(s): ");
           foreach (FaceMatch face in searchFacesResponse.FaceMatches)
               Console.WriteLine("FaceId: " + face.Face.FaceId + ", Similarity: " + face.Similarity);
       }
   }
   ```

   예제 코드를 실행합니다. 일치하는 얼굴에 대한 정보가 표시됩니다.

------

## SearchFaces 작업 요청
<a name="searchfaces-operation-request"></a>

얼굴 ID(얼굴 모음에 저장되는 각 얼굴은 얼굴 ID를 가짐)를 지정할 경우, `SearchFaces`는 지정된 얼굴 모음에서 유사한 얼굴을 검색합니다. 응답에 검색하는 얼굴이 포함되지 않았습니다. 유사한 얼굴만이 포함됩니다. `SearchFaces`는 기본적으로 알고리즘이 80% 이상의 유사성을 감지하는 얼굴을 반환합니다. 유사성은 얼굴이 입력 얼굴과 얼마나 일치하는지를 나타냅니다. 필요하다면 `FaceMatchThreshold`를 사용하여 다른 값을 지정할 수 있습니다.

```
{
    "CollectionId": "MyCollection",
    "FaceId": "0b683aed-a0f1-48b2-9b5e-139e9cc2a757",
    "MaxFaces": 2,
    "FaceMatchThreshold": 99
}
```

## SearchFaces 작업 응답
<a name="searchfaces-operation-response"></a>

작업은 발견된 얼굴 일치의 배열과 입력으로 제공한 얼굴 ID를 반환합니다.

```
{
    "SearchedFaceId": "7ecf8c19-5274-5917-9c91-1db9ae0449e2",
    "FaceMatches": [ list of face matches found ]
}
```

발견된 얼굴 일치마다 응답에는 유사성과 얼굴 메타데이터가 포함됩니다. 다음 예제 응답을 참조하십시오.

```
{
   ...
    "FaceMatches": [
        {
            "Similarity": 100.0,
            "Face": {
                "BoundingBox": {
                    "Width": 0.6154,
                    "Top": 0.2442,
                    "Left": 0.1765,
                    "Height": 0.4692
                },
                "FaceId": "84de1c86-5059-53f2-a432-34ebb704615d",
                "Confidence": 99.9997,
                "ImageId": "d38ebf91-1a11-58fc-ba42-f978b3f32f60"
            }
        },
        {
            "Similarity": 84.6859,
            "Face": {
                "BoundingBox": {
                    "Width": 0.2044,
                    "Top": 0.2254,
                    "Left": 0.4622,
                    "Height": 0.3119
                },
                "FaceId": "6fc892c7-5739-50da-a0d7-80cc92c0ba54",
                "Confidence": 99.9981,
                "ImageId": "5d913eaf-cf7f-5e09-8c8f-cb1bdea8e6aa"
            }
        }
    ]
}
```

# 이미지를 사용하여 얼굴 검색
<a name="search-face-with-image-procedure"></a>

[SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) 작업을 사용하여 제공된 이미지에서 가장 큰 얼굴과 일치하는 컬렉션에서 얼굴을 검색할 수 있습니다.

자세한 내용은 [컬렉션 내의 얼굴 및 사용자 검색](collections-search-faces.md) 단원을 참조하십시오.



**이미지를 사용하여 모음에서 얼굴을 검색하려면(SDK)**

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. 다음 예제를 사용하여 `SearchFacesByImage` 작업을 호출합니다.

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

   이 예제는 이미지에서 가장 큰 얼굴에 대한 정보를 표시합니다. 이 코드 예제는 `FaceMatchThreshold` 및 `MaxFaces` 파라미터를 지정하여 응답에서 반환되는 결과를 제한합니다.

   다음 예제에서, `collectionId` 값을, 검색하려는 모음으로 바꾸고, `bucket` 값을 입력 이미지를 포함하는 버킷으로 바꾸고, `photo` 값을 입력 이미지로 바꿉니다.

   ```
   //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.FaceMatch;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.SearchFacesByImageRequest;
   import com.amazonaws.services.rekognition.model.SearchFacesByImageResult;
   import java.util.List;
   import com.fasterxml.jackson.databind.ObjectMapper;
   
   
   public class SearchFaceMatchingImageCollection {
       public static final String collectionId = "MyCollection";
       public static final String bucket = "bucket";
       public static final String photo = "input.jpg";
         
       public static void main(String[] args) throws Exception {
   
          AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
           
         ObjectMapper objectMapper = new ObjectMapper();
         
          // Get an image object from S3 bucket.
         Image image=new Image()
                 .withS3Object(new S3Object()
                         .withBucket(bucket)
                         .withName(photo));
         
         // Search collection for faces similar to the largest face in the image.
         SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest()
                 .withCollectionId(collectionId)
                 .withImage(image)
                 .withFaceMatchThreshold(70F)
                 .withMaxFaces(2);
              
          SearchFacesByImageResult searchFacesByImageResult = 
                  rekognitionClient.searchFacesByImage(searchFacesByImageRequest);
   
          System.out.println("Faces matching largest face in image from" + photo);
         List < FaceMatch > faceImageMatches = searchFacesByImageResult.getFaceMatches();
         for (FaceMatch face: faceImageMatches) {
             System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                     .writeValueAsString(face));
            System.out.println();
         }
      }
   }
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java)에서 확인하세요.

   ```
   // snippet-start:[rekognition.java2.search_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   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.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageRequest;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceMatch;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   // snippet-end:[rekognition.java2.search_faces_collection.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 SearchFaceMatchingImageCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <sourceImage>\n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection.  \n" +
               "   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String sourceImage = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Searching for a face in a collections");
           searchFaceInCollection(rekClient, collectionId, sourceImage ) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.search_faces_collection.main]
       public static void searchFaceInCollection(RekognitionClient rekClient,String collectionId, String sourceImage) {
   
           try {
               InputStream sourceStream = new FileInputStream(new File(sourceImage));
               SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
               Image souImage = Image.builder()
                   .bytes(sourceBytes)
                   .build();
   
               SearchFacesByImageRequest facesByImageRequest = SearchFacesByImageRequest.builder()
                   .image(souImage)
                   .maxFaces(10)
                   .faceMatchThreshold(70F)
                   .collectionId(collectionId)
                   .build();
   
               SearchFacesByImageResponse imageResponse = rekClient.searchFacesByImage(facesByImageRequest) ;
               System.out.println("Faces matching in the collection");
               List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
               for (FaceMatch face: faceImageMatches) {
                   System.out.println("The similarity level is  "+face.similarity());
                   System.out.println();
               }
   
           } catch (RekognitionException | FileNotFoundException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.search_faces_collection.main]
   }
   ```

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

   이 AWS CLI 명령은 `search-faces-by-image` CLI 작업에 대한 JSON 출력을 표시합니다. `Bucket` 값을 2단계에서 사용한 S3 버킷으로 바꿉니다. `Name` 값을 2단계에서 이미지 파일 이름으로 바꿉니다. `collection-id` 값을 검색할 모음으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   aws rekognition search-faces-by-image --image '{"S3Object":{"Bucket":"bucket-name","Name":"image-name"}}' \
   --collection-id "collection-id" --profile profile-name
   ```

    Windows 디바이스에서 CLI에 액세스하는 경우 작은따옴표 대신 큰따옴표를 사용하고 내부 큰따옴표는 백슬래시(즉 \$1)로 이스케이프 처리하여 발생할 수 있는 구문 분석 오류를 해결합니다. 예를 들어 다음을 참조하세요.

   ```
   aws rekognition search-faces-by-image --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"image-name\"}}" \
   --collection-id "collection-id" --profile profile-name
   ```

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

   이 예제는 이미지에서 가장 큰 얼굴에 대한 정보를 표시합니다. 이 코드 예제는 `FaceMatchThreshold` 및 `MaxFaces` 파라미터를 지정하여 응답에서 반환되는 결과를 제한합니다.

   다음 예제에서, `collectionId` 값을 검색하려는 컬렉션으로 바꾸고, `bucket` 값과 `photo` 값을 2단계에서 사용한 Amazon S3 버킷 및 이미지 이름으로 바꿉니다. Rekognition 세션을 생성하는 라인에서 `profile_name`의 값을 개발자 프로필의 이름으로 대체합니다.

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   if __name__ == "__main__":
   
       bucket='amzn-s3-demo-bucket'
       collectionId='MyCollection'
       fileName='input.jpg'
       threshold = 70
       maxFaces=2
   
       client=boto3.client('rekognition')
   
     
       response=client.search_faces_by_image(CollectionId=collectionId,
                                   Image={'S3Object':{'Bucket':bucket,'Name':fileName}},
                                   FaceMatchThreshold=threshold,
                                   MaxFaces=maxFaces)
   
                                   
       faceMatches=response['FaceMatches']
       print ('Matching faces')
       for match in faceMatches:
               print ('FaceId:' + match['Face']['FaceId'])
               print ('Similarity: ' + "{:.2f}".format(match['Similarity']) + "%")
               print
   ```

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

   이 예제는 이미지에서 가장 큰 얼굴에 대한 정보를 표시합니다. 이 코드 예제는 `FaceMatchThreshold` 및 `MaxFaces` 파라미터를 지정하여 응답에서 반환되는 결과를 제한합니다.

   다음 예제에서, `collectionId` 값을 검색하려는 컬렉션으로 바꾸고, `bucket` 값과 `photo` 값을 2단계에서 사용한 Amazon S3 버킷 및 이미지 이름으로 바꿉니다.

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   using System;
   using Amazon.Rekognition;
   using Amazon.Rekognition.Model;
   
   public class SearchFacesMatchingImage
   {
       public static void Example()
       {
           String collectionId = "MyCollection";
           String bucket = "amzn-s3-demo-bucket";
           String photo = "input.jpg";
   
           AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient();
   
           // Get an image object from S3 bucket.
           Image image = new Image()
           {
               S3Object = new S3Object()
               {
                   Bucket = bucket,
                   Name = photo
               }
           };
   
           SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest()
           {
               CollectionId = collectionId,
               Image = image,
               FaceMatchThreshold = 70F,
               MaxFaces = 2
           };
   
           SearchFacesByImageResponse searchFacesByImageResponse = rekognitionClient.SearchFacesByImage(searchFacesByImageRequest);
   
           Console.WriteLine("Faces matching largest face in image from " + photo);
           foreach (FaceMatch face in searchFacesByImageResponse.FaceMatches)
               Console.WriteLine("FaceId: " + face.Face.FaceId + ", Similarity: " + face.Similarity);
       }
   }
   ```

------

## SearchFacesByImage 작업 요청
<a name="searchfacesbyimage-operation-request"></a>

`SearchFacesImageByImage`에 대한 입력 파라미터는 검색할 모음과 소스 이미지 위치입니다. 이 예제에서 소스 이미지는 Amazon S3 버킷(`S3Object`)에 저장되어 있습니다. 또한 반환할 최대 얼굴 수(`Maxfaces`)와, 반환할 얼굴에 대해 일치해야 할 최소 신뢰도(`FaceMatchThreshold`)를 지정합니다.

```
{
    "CollectionId": "MyCollection",
    "Image": {
        "S3Object": {
            "Bucket": "bucket",
            "Name": "input.jpg"
        }
    },
    "MaxFaces": 2,
    "FaceMatchThreshold": 99
}
```

## SearchFacesByImage 작업 응답
<a name="searchfacesbyimage-operation-response"></a>

입력 이미지(.jpeg 또는 .png)가 주어진 경우, 작업은 먼저 입력 이미지에서 얼굴을 감지한 다음 지정된 얼굴 모음에서 유사한 얼굴을 감지합니다.

**참고**  
입력 이미지에서 여러 얼굴이 감지되는 경우, 서비스는 감지된 가장 큰 얼굴을 얼굴 모음 감지에 사용합니다.

이 작업은 찾아낸 일치 얼굴의 배열과, 입력 얼굴에 대한 정보를 반환합니다. 경계 상자 등과 같은 정보와 신뢰도 값을 포함합니다. 신뢰도는 경계 상자의 얼굴 포함 기준이 되는 신뢰도 수준입니다.

`SearchFacesByImage`는 기본적으로 알고리즘이 80% 이상의 유사성을 감지하는 얼굴을 반환합니다. 유사성은 얼굴이 입력 얼굴과 얼마나 일치하는지를 나타냅니다. 필요하다면 `FaceMatchThreshold`를 사용하여 다른 값을 지정할 수 있습니다. 발견된 얼굴 일치마다 응답에는 유사성과 얼굴 메타데이터가 포함됩니다. 다음 예제 응답을 참조하십시오.

```
{
    "FaceMatches": [
        {
            "Face": {
                "BoundingBox": {
                    "Height": 0.06333330273628235,
                    "Left": 0.1718519926071167,
                    "Top": 0.7366669774055481,
                    "Width": 0.11061699688434601
                },
                "Confidence": 100,
                "ExternalImageId": "input.jpg",
                "FaceId": "578e2e1b-d0b0-493c-aa39-ba476a421a34",
                "ImageId": "9ba38e68-35b6-5509-9d2e-fcffa75d1653"
            },
            "Similarity": 99.9764175415039
        }
    ],
    "FaceModelVersion": "3.0",
    "SearchedFaceBoundingBox": {
        "Height": 0.06333333253860474,
        "Left": 0.17185185849666595,
        "Top": 0.7366666793823242,
        "Width": 0.11061728745698929
    },
    "SearchedFaceConfidence": 99.99999237060547
}
```

# 사용자 검색(얼굴 ID 또는 사용자 ID)
<a name="search-users"></a>

[SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html) 작업을 사용하여 제공된 얼굴 ID 혹은 사용자 ID와 일치하는 컬렉션을 지정하여 사용자를 검색할 수 있습니다. 이 작업은 반환된 `UserIds` 결과를 요청한 UserMatchThreshold보다 높은 유사성 점수 순대로 나열합니다. 사용자 ID는 CreateUsers 작업에서 생성됩니다. 자세한 내용은 [컬렉션의 사용자 관리](managing-face-collections.md#collections-manage-users) 단원을 참조하십시오.

**사용자 검색(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. 다음 예제를 사용하여 `SearchUsers` 작업을 호출합니다.

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

   이 Java 예제는 `SearchUsers` 작업을 사용하여 컬렉션에서 사용자를 검색합니다.

   ```
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.UserMatch;
   import com.amazonaws.services.rekognition.model.SearchUsersRequest;
   import com.amazonaws.services.rekognition.model.SearchUsersResult;
   import com.amazonaws.services.rekognition.model.UserMatch;
   
   public class SearchUsers {
       //Replace collectionId and faceId with the values you want to use.
   
       public static final String collectionId = "MyCollection";
       public static final String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
   
       public static final String userd = 'demo-user';
   
       public static void main(String[] args) throws Exception {
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
           // Search collection for faces matching the user id.
           SearchUsersRequest request = new SearchUsersRequest()
                   .withCollectionId(collectionId)
                   .withUserId(userId);
   
           SearchUsersResult result =
                   rekognitionClient.searchUsers(request);
   
           System.out.println("Printing first search result with matched user and similarity score");
           for (UserMatch match: result.getUserMatches()) {
               System.out.println(match.getUser().getUserId() + " with similarity score " + match.getSimilarity());
           }
   
           // Search collection for faces matching the face id.
           SearchUsersRequest request1 = new SearchUsersRequest()
                   .withCollectionId(collectionId)
                   .withFaceId(faceId);
   
           SearchUsersResult result1 =
                   rekognitionClient.searchUsers(request1);
   
           System.out.println("Printing second search result with matched user and similarity score");
           for (UserMatch match: result1.getUserMatches()) {
               System.out.println(match.getUser().getUserId() + " with similarity score " + match.getSimilarity());
           }
       }
   ```

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

   이 AWS CLI 명령은 `SearchUsers` 작업을 사용하여 컬렉션의 사용자를 검색합니다.

   ```
   aws rekognition search-users --face-id face-id --collection-id collection-id --region region-name
   ```

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

   다음 예제에서는 `SearchUsers` 작업으로 컬렉션에 있는 사용자를 검색합니다.

   ```
   # 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
   from botocore.exceptions import ClientError
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def search_users_by_face_id(collection_id, face_id):
       """
       SearchUsers operation with face ID provided as the search source
   
       :param collection_id: The ID of the collection where user and faces are stored.
       :param face_id: The ID of the face in the collection to search for.
   
       :return: response of SearchUsers API
       """
       logger.info(f'Searching for users using a face-id: {face_id}')
       try:
           response = client.search_users(
               CollectionId=collection_id,
               FaceId=face_id
           )
           print(f'- found {len(response["UserMatches"])} matches')
           print([f'- {x["User"]["UserId"]} - {x["Similarity"]}%' for x in response["UserMatches"]])
       except ClientError:
           logger.exception(f'Failed to perform SearchUsers with given face id: {face_id}')
           raise
       else:
           print(response)
           return response
   
   def search_users_by_user_id(collection_id, user_id):
       """
       SearchUsers operation with user ID provided as the search source
   
       :param collection_id: The ID of the collection where user and faces are stored.
       :param user_id: The ID of the user in the collection to search for.
   
       :return: response of SearchUsers API
       """
       logger.info(f'Searching for users using a user-id: {user_id}')
       try:
           response = client.search_users(
               CollectionId=collection_id,
               UserId=user_id
           )
           print(f'- found {len(response["UserMatches"])} matches')
           print([f'- {x["User"]["UserId"]} - {x["Similarity"]}%' for x in response["UserMatches"]])
       except ClientError:
           logger.exception(f'Failed to perform SearchUsers with given face id: {user_id}')
           raise
       else:
           print(response)
           return response
   
   def main():
       collection_id = "collection-id"
       user_id = "user-id"
       face_id = "face_id"
       search_users_by_face_id(collection_id, face_id)
       search_users_by_user_id(collection_id, user_id)
   
   if __name__ == "__main__":
       main()
   ```

------

## SearchUsers 작업 요청
<a name="search-users-request"></a>

FaceID 또는 UserID가 주어지면 SearchUsers는 지정된 CollectionID에서 일치하는 사용자를 검색합니다. 기본적으로 SearchUsers는 유사성 점수가 80%를 초과하는 UserID를 반환합니다. 유사성은 UserID가 제공된 FaceID 또는 UserID와 얼마나 가깝게 일치하는지를 나타냅니다. 여러 UserID가 반환되는 경우 유사성 점수가 높은 것부터 가장 낮은 순으로 나열됩니다. 필요하다면 UserMatchThreshold를 사용하여 다른 값을 지정할 수 있습니다. 자세한 내용은 [컬렉션의 사용자 관리](managing-face-collections.md#collections-manage-users) 단원을 참조하십시오.

다음은 `UserId`를 사용하는 SearchUsers 요청의 예입니다.

```
{
   "CollectionId": "MyCollection",
   "UserId": "demoUser1",
   "MaxUsers": 2,
   "UserMatchThreshold": 99
}
```

다음은 `FaceId`를 사용하는 SearchUsers 요청의 예입니다.

```
{
    "CollectionId": "MyCollection",
    "FaceId": "bff43c40-cfa7-4b94-bed8-8a08b2205107",
    "MaxUsers": 2,
    "UserMatchThreshold": 99
}
```

## SearchUsers 작업 응답
<a name="search-users-response"></a>

`FaceId`로 검색하는 경우 SearchUsers에 대한 응답에는 `SearchedFace`에 대한 `FaceId`와 `UserMatches` 목록 및 각 User의 `UserId`와`UserStatus`가 포함됩니다.

```
{
    "SearchedFace": {
        "FaceId": "bff43c40-cfa7-4b94-bed8-8a08b2205107"
    }, 
    "UserMatches": [
        {
            "User": {
                "UserId": "demoUser1", 
                "UserStatus": "ACTIVE"
            }, 
            "Similarity": 100.0
        }, 
        {
            "User": {
                "UserId": "demoUser2", 
                "UserStatus": "ACTIVE"
            }, 
            "Similarity": 99.97946166992188
        }
    ], 
    "FaceModelVersion": "6"
}
```

`UserId`로 검색하는 경우 SearchUsers에 대한 응답에는 다른 응답 요소와 함께 `SearchedUser`에 대한 `UserId`가 포함됩니다.

```
{
    "SearchedUser": {
        "UserId": "demoUser1"
    }, 
    "UserMatches": [
        {
            "User": {
                "UserId": "demoUser2", 
                "UserStatus": "ACTIVE"
            }, 
            "Similarity": 99.97946166992188
        }
    ], 
    "FaceModelVersion": "6"
}
```

# 사용자 검색(이미지)
<a name="search-users-by-image"></a>

`SearchUsersByImage`는 지정된 CollectionID를 검색하여 제공된 이미지에서 감지된 가장 큰 얼굴과 일치하는 컬렉션의 사용자를 찾습니다. 기본적으로 SearchUsersByImage는 유사성 점수가 80%를 초과하는 UserID를 반환합니다. 유사성은 UserID가 제공된 이미지에서 감지된 가장 큰 얼굴과 얼마나 가깝게 일치하는지를 나타냅니다. 여러 UserID가 반환되는 경우 유사성 점수가 높은 것부터 가장 낮은 순으로 나열됩니다. 필요하다면 UserMatchThreshold를 사용하여 다른 값을 지정할 수 있습니다. 자세한 내용은 [컬렉션의 사용자 관리](managing-face-collections.md#collections-manage-users) 단원을 참조하십시오.



**이미지로 사용자 검색하기(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. 다음 예제를 사용하여 `SearchUsersByImage` 작업을 호출합니다.

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

   이 Java 예제는 `SearchUsersByImage` 작업을 사용하여 입력 이미지를 기반으로 컬렉션에 있는 사용자를 검색합니다.

   ```
   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.S3Object;
   import com.amazonaws.services.rekognition.model.SearchUsersByImageRequest;
   import com.amazonaws.services.rekognition.model.SearchUsersByImageResult;
   import com.amazonaws.services.rekognition.model.UserMatch;
   
   
   public class SearchUsersByImage {
       //Replace bucket, collectionId and photo with your values.
       public static final String collectionId = "MyCollection";
       public static final String s3Bucket = "bucket";
       public static final String s3PhotoFileKey = "input.jpg";
   
       public static void main(String[] args) throws Exception {
   
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
   
           // Get an image object from S3 bucket.
           Image image = new Image()
                   .withS3Object(new S3Object()
                           .withBucket(s3Bucket)
                           .withName(s3PhotoFileKey));
   
           // Search collection for users similar to the largest face in the image.
           SearchUsersByImageRequest request = new SearchUsersByImageRequest()
                   .withCollectionId(collectionId)
                   .withImage(image)
                   .withUserMatchThreshold(70F)
                   .withMaxUsers(2);
   
           SearchUsersByImageResult result =
                   rekognitionClient.searchUsersByImage(request);
   
           System.out.println("Printing search result with matched user and similarity score");
           for (UserMatch match: result.getUserMatches()) {
               System.out.println(match.getUser().getUserId() + " with similarity score " + match.getSimilarity());
           }
       }
   }
   ```

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

   이 AWS CLI 명령은 `SearchUsersByImage` 작업을 사용하여 입력 이미지를 기반으로 컬렉션의 사용자를 검색합니다.

   ```
   aws rekognition search-users-by-image --image '{"S3Object":{"Bucket":"s3BucketName","Name":"file-name"}}' --collection-id MyCollectionId --region region-name
   ```

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

   다음 예제에서는 `SearchUsersByImage` 작업을 사용하여 입력 이미지를 기반으로 컬렉션에 있는 사용자를 검색합니다.

   ```
   # 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
   from botocore.exceptions import ClientError
   import logging
   import os
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def load_image(file_name):
       """
       helper function to load the image for indexFaces call from local disk
   
       :param image_file_name: The image file location that will be used by indexFaces call.
       :return: The Image in bytes
       """
       print(f'- loading image: {file_name}')
       with open(file_name, 'rb') as file:
           return {'Bytes': file.read()}
   
   def search_users_by_image(collection_id, image_file):
       """
       SearchUsersByImage operation with user ID provided as the search source
   
       :param collection_id: The ID of the collection where user and faces are stored.
       :param image_file: The image that contains the reference face to search for.
   
       :return: response of SearchUsersByImage API
       """
       logger.info(f'Searching for users using an image: {image_file}')
       try:
           response = client.search_users_by_image(
               CollectionId=collection_id,
               Image=load_image(image_file)
           )
           print(f'- found {len(response["UserMatches"])} matches')
           print([f'- {x["User"]["UserId"]} - {x["Similarity"]}%' for x in response["UserMatches"]])
       except ClientError:
           logger.exception(f'Failed to perform SearchUsersByImage with given image: {image_file}')
           raise
       else:
           print(response)
           return response
   
   def main():
       collection_id = "collection-id"
       IMAGE_SEARCH_SOURCE = os.getcwd() + '/image_path'
       search_users_by_image(collection_id, IMAGE_SEARCH_SOURCE)
   
   if __name__ == "__main__":
       main()
   ```

------

## SearchUsersByImage 작업 요청
<a name="search-users-by-image-request"></a>

`SearchUsersByImage`에 대한 요청은 검색할 컬렉션과 소스 이미지 위치를 포함합니다. 이 예제에서 소스 이미지는 Amazon S3 버킷(`S3Object`)에 저장되어 있습니다. 또한 반환할 최대 사용자 수(`MaxUsers`)와, 반환할 사용자에 대해 일치해야 하는 최소 신뢰도(`UserMatchThreshold`)를 지정합니다.

```
{
    "CollectionId": "MyCollection",
    "Image": {
        "S3Object": {
            "Bucket": "bucket",
            "Name": "input.jpg"
        }
    },
    "MaxUsers": 2,
    "UserMatchThreshold": 99
}
```

## SearchUsersByImage 작업 응답
<a name="search-users-by-image-response"></a>

`SearchUsersByImage`에 대한 응답에는 `SearchedFace`에 대한 `FaceDetail` 개체와 UserMatches 목록 및 각각의 `UserId`, `Similarity`, 그리고 `UserStatus`가 포함됩니다. 입력 이미지에 얼굴이 두 개 이상 포함된 경우 UnsearchedFaces 목록도 반환됩니다.

```
{
    "SearchedFace": {
        "FaceDetail": {
            "BoundingBox": {
                "Width": 0.23692893981933594, 
                "Top": 0.19235000014305115, 
                "Left": 0.39177176356315613, 
                "Height": 0.5437348484992981
            }
        }
    }, 
    "UserMatches": [
        {
            "User": {
                "UserId": "demoUser1", 
                "UserStatus": "ACTIVE"
            }, 
            "Similarity": 100.0
        }, 
        {
            "User": {
                "UserId": "demoUser2", 
                "UserStatus": "ACTIVE"
            }, 
            "Similarity": 99.97946166992188
        }
    ], 
    "FaceModelVersion": "6", 
    "UnsearchedFaces": [
        {
            "FaceDetails": {
                "BoundingBox": {
                    "Width": 0.031677018851041794, 
                    "Top": 0.5593535900115967, 
                    "Left": 0.6102562546730042, 
                    "Height": 0.0682177022099495
                }
            }, 
            "Reasons": [
                "FACE_NOT_LARGEST"
            ]
        }, 
        {
            "FaceDetails": {
                "BoundingBox": {
                    "Width": 0.03254449740052223, 
                    "Top": 0.6080358028411865, 
                    "Left": 0.516062319278717, 
                    "Height": 0.06347997486591339
                }
            }, 
            "Reasons": [
                "FACE_NOT_LARGEST"
            ]
        }
    ]
}
```

# 저장된 비디오에서 얼굴 검색
<a name="procedure-person-search-videos"></a>

저장된 비디오나 스트리밍 비디오에서 감지한 얼굴과 일치하는 얼굴을 얼굴 모음에서 찾아낼 수 있습니다. 이 단원에서는 저장된 비디오에서 얼굴을 검색하는 과정에 대해 다룹니다. 스트리밍 비디오에서 얼굴을 검색하는 방법에 대한 정보는 [스트리밍 비디오 이벤트 작업](streaming-video.md)를 참조하십시오.

먼저 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html)를 사용하여 검색할 얼굴을 컬렉션으로 인덱싱해야 합니다. 자세한 내용은 [컬렉션에 얼굴 추가](add-faces-to-collection-procedure.md) 단원을 참조하십시오.

Amazon Rekognition Video 얼굴 검색은 Amazon S3 버킷에 저장된 비디오를 분석하는 다른 Amazon Rekognition Video 작업과 동일한 비동기 워크플로를 따릅니다. 저장된 비디오에서 얼굴 검색을 시작하려면 [StartFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceSearch.html)를 직접 호출하고 검색하려는 컬렉션의 ID를 제공하십시오. Amazon Rekognition Video는 동영상 분석 작업의 완료 상태를 Amazon Simple Notification Service(SNS) 주제에 게시합니다. 비디오 분석이 성공적으로 완료되면 [GetFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GeFaceSearch.html)를 직접 호출하여 검색 결과를 가져옵니다. 비디오 분석 시작 및 결과 가져오기에 대한 자세한 내용은 [Amazon Rekognition Video 작업 직접 호출](api-video.md) 단원을 참조하십시오.

다음 절차는 비디오에서 감지된 사람의 얼굴과 일치하는 얼굴 모음을 감지하는 방법을 보여 줍니다. 다음 절차에서는 비디오에서 일치되는 사람의 추적 데이터를 가져오는 방법을 보여 줍니다. 이 절차는 동영상 분석 요청의 완료 상태를 가져오기 위해 Amazon Simple Queue Service(Amazon SQS) 대기열을 사용하는 [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md)의 코드를 확장합니다.

**비디오에서 일치하는 얼굴을 검색하려면(SDK)**

1. [모음을 만듭니다](create-collection-procedure.md).

1. [얼굴을 모음으로 인덱싱합니다](add-faces-to-collection-procedure.md).

1. [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md)을 수행합니다.

1. 3단계에서 만든 클래스 `VideoDetect`에 다음 코드를 추가합니다.

------
#### [ 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.)
   
          //Face collection search in video ==================================================================
          private static void StartFaceSearchCollection(String bucket, String video, String collection) throws Exception{
   
           NotificationChannel channel= new NotificationChannel()
                   .withSNSTopicArn(snsTopicArn)
                   .withRoleArn(roleArn);
   
           StartFaceSearchRequest req = new StartFaceSearchRequest()
                   .withCollectionId(collection)
                   .withVideo(new Video()
                           .withS3Object(new S3Object()
                                   .withBucket(bucket)
                                   .withName(video)))
                   .withNotificationChannel(channel);
   
   
   
           StartFaceSearchResult startPersonCollectionSearchResult = rek.startFaceSearch(req);
           startJobId=startPersonCollectionSearchResult.getJobId();
   
       } 
   
       //Face collection search in video ==================================================================
       private static void GetFaceSearchCollectionResults() throws Exception{
   
          GetFaceSearchResult faceSearchResult=null;
          int maxResults=10;
          String paginationToken=null;
   
          do {
   
              if (faceSearchResult !=null){
                  paginationToken = faceSearchResult.getNextToken();
              }
   
   
              faceSearchResult  = rek.getFaceSearch(
                      new GetFaceSearchRequest()
                      .withJobId(startJobId)
                      .withMaxResults(maxResults)
                      .withNextToken(paginationToken)
                      .withSortBy(FaceSearchSortBy.TIMESTAMP)
                      );
   
   
              VideoMetadata videoMetaData=faceSearchResult.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());
              System.out.println();      
   
   
              //Show search results
              List<PersonMatch> matches= 
                      faceSearchResult.getPersons();
   
              for (PersonMatch match: matches) { 
                  long milliSeconds=match.getTimestamp();
                  System.out.print("Timestamp: " + Long.toString(milliSeconds));
                  System.out.println(" Person number: " + match.getPerson().getIndex());
                  List <FaceMatch> faceMatches = match.getFaceMatches();
                  if (faceMatches != null) {
                      System.out.println("Matches in collection...");
                      for (FaceMatch faceMatch: faceMatches){
                          Face face=faceMatch.getFace();
                          System.out.println("Face Id: "+ face.getFaceId());
                          System.out.println("Similarity: " + faceMatch.getSimilarity().toString());
                          System.out.println();
                      }
                  }
                  System.out.println();           
              } 
   
              System.out.println(); 
   
          } while (faceSearchResult !=null && faceSearchResult.getNextToken() != null);
   
      }
   ```

   `main` 함수에서 다음 줄을 바꿉니다.

   ```
           StartLabelDetection(bucket, video);
   
           if (GetSQSMessageSuccess()==true)
           	GetLabelDetectionResults();
   ```

   다음으로 바꿉니다.

   ```
           String collection="collection";
           StartFaceSearchCollection(bucket, video, collection);
   
           if (GetSQSMessageSuccess()==true)
           	GetFaceSearchCollectionResults();
   ```

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

   이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoDetectFaces.java)에서 확인하세요.

   ```
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.*;
   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 VideoDetectFaces {
       private static String startJobId = "";
   
       public static void main(String[] args) {
           final String usage = """
   
                   Usage:    <bucket> <video> <topicArn> <roleArn>
   
                   Where:
                      bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                      video - The name of video (for example, people.mp4).\s
                      topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                      roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                   """;
   
           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)
                   .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();
       }
   
       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);
           }
       }
   }
   ```

------
#### [ 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.)
   
       # ============== Face Search ===============
       def StartFaceSearchCollection(self,collection):
           response = self.rek.start_face_search(Video={'S3Object':{'Bucket':self.bucket,'Name':self.video}},
               CollectionId=collection,
               NotificationChannel={'RoleArn':self.roleArn, 'SNSTopicArn':self.snsTopicArn})
           
           self.startJobId=response['JobId']
           
           print('Start Job Id: ' + self.startJobId)
   
   
       def GetFaceSearchCollectionResults(self):
           maxResults = 10
           paginationToken = ''
   
           finished = False
   
           while finished == False:
               response = self.rek.get_face_search(JobId=self.startJobId,
                                           MaxResults=maxResults,
                                           NextToken=paginationToken)
   
               print(response['VideoMetadata']['Codec'])
               print(str(response['VideoMetadata']['DurationMillis']))
               print(response['VideoMetadata']['Format'])
               print(response['VideoMetadata']['FrameRate'])
   
               for personMatch in response['Persons']:
                   print('Person Index: ' + str(personMatch['Person']['Index']))
                   print('Timestamp: ' + str(personMatch['Timestamp']))
   
                   if ('FaceMatches' in personMatch):
                       for faceMatch in personMatch['FaceMatches']:
                           print('Face ID: ' + faceMatch['Face']['FaceId'])
                           print('Similarity: ' + str(faceMatch['Similarity']))
                   print()
               if 'NextToken' in response:
                   paginationToken = response['NextToken']
               else:
                   finished = True
               print()
   ```

   `main` 함수에서 다음 줄을 바꿉니다.

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

   다음으로 바꿉니다.

   ```
       collection='tests'
       analyzer.StartFaceSearchCollection(collection)
       
       if analyzer.GetSQSMessageSuccess()==True:
           analyzer.GetFaceSearchCollectionResults()
   ```

------

   [Java 또는 Python으로 Amazon S3 버킷에 저장된 비디오 분석(SDK)](video-analyzing-with-sqs.md) 이외에 비디오 예제를 이미 실행한 경우, 바꿀 코드가 다를 수 있습니다.

1. `collection`의 값을, 1단계에서 만든 모음의 이름으로 변경합니다.

1. 코드를 실행합니다. 입력 모음의 얼굴과 일치하는 비디오의 사람 목록이 표시됩니다. 일치하는 각 사람의 추적 데이터도 표시됩니다.

## GetFaceSearch 작업 응답
<a name="searchfacesvideo-operation-response"></a>

다음은 `GetFaceSearch`의 JSON 응답 예제입니다.

응답에는 입력 모음의 얼굴과 얼굴이 일치하는 동영상에서 감지된 일련의 사람 `Persons`이 포함됩니다. 배열 요소 [PersonMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonMatch.html)는 비디오에서 사람이 일치할 때마다 존재합니다. 각`PersonMatch`에는 입력 컬렉션에서 가져오는 일련의 얼굴 일치, [FaceMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceMatch.html), 일치하는 사람에 관한 정보, [PersonDetail](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonDetail.html) 및 이 사람이 비디오에서 일치된 시간이 포함되어 있습니다.

```
{
    "JobStatus": "SUCCEEDED",
    "NextToken": "IJdbzkZfvBRqj8GPV82BPiZKkLOGCqDIsNZG/gQsEE5faTVK9JHOz/xxxxxxxxxxxxxxx",
    "Persons": [
        {
            "FaceMatches": [
                {
                    "Face": {
                        "BoundingBox": {
                            "Height": 0.527472972869873,
                            "Left": 0.33530598878860474,
                            "Top": 0.2161169946193695,
                            "Width": 0.35503000020980835
                        },
                        "Confidence": 99.90239715576172,
                        "ExternalImageId": "image.PNG",
                        "FaceId": "a2f2e224-bfaa-456c-b360-7c00241e5e2d",
                        "ImageId": "eb57ed44-8d8d-5ec5-90b8-6d190daff4c3"
                    },
                    "Similarity": 98.40909576416016
                }
            ],
            "Person": {
                "BoundingBox": {
                    "Height": 0.8694444298744202,
                    "Left": 0.2473958283662796,
                    "Top": 0.10092592239379883,
                    "Width": 0.49427083134651184
                },
                "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
                    }
                },
                "Index": 0
            },
            "Timestamp": 0
        },
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.2177777737379074,
                    "Left": 0.7593749761581421,
                    "Top": 0.13333334028720856,
                    "Width": 0.12250000238418579
                },
                "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
                    }
                },
                "Index": 1
            },
            "Timestamp": 0
        },
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.8388888835906982,
                    "Left": 0,
                    "Top": 0.15833333134651184,
                    "Width": 0.2369791716337204
                },
                "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
                    }
                },
                "Index": 2
            },
            "Timestamp": 0
        }......

    ],
    "VideoMetadata": {
        "Codec": "h264",
        "DurationMillis": 67301,
        "Format": "QuickTime / MOV",
        "FrameHeight": 1080,
        "FrameRate": 29.970029830932617,
        "FrameWidth": 1920
    }
}
```

# 스트리밍 비디오에서 컬렉션의 얼굴 검색
<a name="collections-streaming"></a>

Amazon Rekognition Video를 사용하면 스트리밍 비디오의 컬렉션에서 얼굴을 감지하고 인식할 수 있습니다. Amazon Rekognition Video를 사용하면 스트림 프로세서([CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html))를 생성하여 스트리밍 비디오 분석을 시작하고 관리할 수 있습니다.

비디오 스트림에서 알려진 얼굴을 감지(얼굴 검색)하기 위해 Amazon Rekognition Video는 Amazon Kinesis Video Streams를 사용하여 비디오 스트림을 수신하고 처리합니다. 분석 결과는 Amazon Rekognition Video에서 Kinesis 데이터 스트림으로 출력된 후 클라이언트 애플리케이션이 읽게 됩니다.

스트리밍 비디오에 Amazon Rekognition Video를 사용하려면 애플리케이션에 다음을 구현해야 합니다.
+ Amazon Rekognition Video로 스트리밍 비디오를 전송하기 위한 Kinesis 비디오 스트림. 자세한 내용은 [Amazon Kinesis Video Streams 개발자 안내서](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html)를 참조하세요.
+ 스트리밍 비디오 분석을 관리할 Amazon Rekognition Video 스트림 프로세서. 자세한 내용은 [Amazon Rekognition Video 스트림 프로세서 작업 개요](streaming-video.md#using-rekognition-video-stream-processor) 단원을 참조하십시오.
+ Amazon Rekognition Video가 Kinesis 데이터 스트림으로 전송하는 분석 결과를 읽을 Kinesis 데이터 스트림 소비자. 자세한 내용은 [Amazon Kinesis Data Streams 소비자](https://docs.aws.amazon.com/streams/latest/dev/amazon-kinesis-consumers.html)를 참조하세요.

이 섹션에는 Kinesis 비디오 스트림 및 기타 필요한 리소스를 생성하고, Amazon Rekognition Video로 비디오를 스트리밍하고, 분석 결과를 수신하는 애플리케이션을 개발하는 방법에 대한 정보가 포함되어 있습니다.

**Topics**
+ [Amazon Rekognition Video 및 Amazon Kinesis 리소스 설정](setting-up-your-amazon-rekognition-streaming-video-resources.md)
+ [스트리밍 비디오에서 얼굴 검색](rekognition-video-stream-processor-search-faces.md)
+ [GStreamer 플러그인을 사용한 스트리밍](streaming-using-gstreamer-plugin.md)
+ [스트리밍 비디오 문제 해결](streaming-video-troubleshooting.md)

# Amazon Rekognition Video 및 Amazon Kinesis 리소스 설정
<a name="setting-up-your-amazon-rekognition-streaming-video-resources"></a>

 다음 절차는 스트리밍 비디오에서 얼굴을 인식하는 데 사용되는 Kinesis 비디오 스트림 및 기타 리소스를 프로비저닝하기 위해 수행할 단계를 설명합니다.

## 사전 조건
<a name="streaming-video-prerequisites"></a>

이 절차를 실행하려면가 AWS SDK for Java 설치되어 있어야 합니다. 자세한 내용은 [Amazon Rekognition 시작](getting-started.md) 단원을 참조하십시오. AWS 계정 사용하는 에는 Amazon Rekognition API에 대한 액세스 권한이 있어야 합니다. 자세한 내용은 *IAM 사용 설명서*의 [Amazon Rekognition에서 정의한 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions)을 참조하세요.

**비디오 스트림에서 얼굴을 인식하려면(AWS SDK)**

1. IAM 서비스 역할을 아직 생성하지 않은 경우 생성하여 Kinesis 비디오 스트림 및 Kinesis 데이터 스트림에 대한 Amazon Rekognition Video 액세스 권한을 부여하세요. ARN을 기록합니다. 자세한 내용은 [AmazonRekognitionServiceRole을 사용하여 스트림 액세스 권한 부여](api-streaming-video-roles.md#api-streaming-video-roles-all-stream) 단원을 참조하십시오.

1. [모음을 만들고](create-collection-procedure.md), 사용한 모음 식별자를 적어둡니다.

1. 2단계에서 만든 모음에 검색하고자 하는 [얼굴을 인덱싱](add-faces-to-collection-procedure.md)합니다.

1. [Kinesis 비디오 스트림을 만들고](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-createstream.html) 스트림의 Amazon 리소스 이름(ARN)을 적어둡니다.

1. [Kinesis 데이터 스트림을 생성합니다](https://docs.aws.amazon.com/streams/latest/dev/learning-kinesis-module-one-create-stream.html). 스트림 이름 앞에 *AmazonRekognition*을 추가하고 스트림의 ARN을 적어둡니다.

그 후 [얼굴 검색 스트림 프로세서를 생성](rekognition-video-stream-processor-search-faces.md#streaming-video-creating-stream-processor)하고 선택한 스트림 프로세서 이름을 사용하여 [스트림 프로세서를 시작](rekognition-video-stream-processor-search-faces.md#streaming-video-starting-stream-processor)할 수 있습니다.

**참고**  
 미디어를 Kinesis 비디오 스트림으로 수집할 수 있는지 확인한 다음에 스트림 프로세서를 시작해야 합니다.

## Amazon Rekognition Video로 비디오 스트리밍
<a name="video-streaming-kinesisvideostreams-stream"></a>

Amazon Rekognition Video로 비디오를 스트리밍하려면 Amazon Kinesis Video Streams SDK를 사용하여 Kinesis 비디오 스트림을 생성하고 사용합니다. 이 `PutMedia` 작업은 Amazon Rekognition Video가 소비하는 Kinesis 비디오 스트림에 비디오 데이터 *조각*을 기록합니다. 각 비디오 데이터 조각의 길이는 일반적으로 2\$110초이며 독립적인 비디오 프레임 시퀀스를 포함합니다. Amazon Rekognition Video는 H.264로 인코딩된 비디오를 지원하며, 이 비디오에는 세 가지 유형의 프레임(I, B, P)이 있을 수 있습니다. 자세한 내용은 [Inter Frame](https://en.wikipedia.org/wiki/Inter_frame)을 참조하십시오. 조각의 첫 번째 프레임은 I 프레임이어야 합니다. I- 프레임은 다른 프레임과 별도로 디코딩될 수 있습니다.

비디오 데이터가 Kinesis 비디오 스트림에 도착하면 Kinesis Video Streams가 조각에 고유 번호를 할당합니다. 예제를 보려면 [PutMedia API 예제](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-putmedia.html)를 참조하십시오.
+  Matroska(MKV) 로 인코딩된 소스에서 스트리밍하는 경우 [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) 작업을 사용하여 소스 비디오를 생성한 Kinesis 비디오 스트림으로 스트리밍합니다. 자세한 내용은 [PutMedia API 예제](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-putmedia.html)를 참조하십시오.
+  디바이스 카메라에서 스트리밍하는 경우 [GStreamer 플러그인을 사용한 스트리밍](streaming-using-gstreamer-plugin.md) 섹션을 참조하세요.

# Amazon Rekognition Video에 리소스에 대한 액세스 권한 부여
<a name="api-streaming-video-roles"></a>

 AWS Identity and Access Management (IAM) 서비스 역할을 사용하여 Amazon Rekognition Video에 Kinesis 비디오 스트림에 대한 읽기 액세스 권한을 부여합니다. 얼굴 검색 스트림 프로세서를 사용하는 경우 IAM 서비스 역할을 사용하여 Amazon Rekognition Video에 Kinesis 데이터 스트림에 대한 쓰기 액세스 권한을 부여합니다. 보안 모니터링 스트림 프로세서를 사용하는 경우, IAM 역할을 사용하여 Amazon Rekognition Video에 Amazon S3 버킷 및 Amazon SNS 주제에 대한 액세스 권한을 부여합니다.

## 얼굴 검색 스트림 프로세서 액세스 권한 부여
<a name="api-streaming-video-roles-single-stream"></a>

Amazon Rekognition Video에서 개별 Kinesis 비디오 스트림 및 Kinesis 데이터 스트림에 액세스할 수 있도록 허용하는 권한 정책을 생성할 수 있습니다.

**Amazon Rekognition Video에 얼굴 검색 스트림 프로세서를 위한 액세스 권한을 부여하려면**

1. [IAM JSON 정책 편집기로 새 권한 정책을 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)하고 다음 정책을 사용합니다. `video-arn`을 원하는 Kinesis 비디오 스트림의 ARN으로 교체하세요. 얼굴 검색 스트림 프로세서를 사용하는 경우 `data-arn`을 원하는 Kinesis 데이터 스트림의 ARN으로 교체합니다.

1. [IAM 서비스 역할을 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console)하거나 기존 IAM 서비스 역할을 업데이트합니다. 다음 정보를 사용하여 IAM 서비스 역할을 생성하세요.

   1. 서비스 이름으로 **Rekognition**을 선택합니다.

   1. 서비스 역할 사용 사례로 [**Rekognition**]을 선택합니다.

   1. 1단계에 만든 권한 정책을 연결합니다.

1. 서비스 역할의 ARN을 기록합니다. 이것은 비디오 분석 작업을 시작할 때 필요합니다.

## AmazonRekognitionServiceRole을 사용하여 스트림 액세스 권한 부여
<a name="api-streaming-video-roles-all-stream"></a>

 Kinesis 비디오 스트림 및 데이터 스트림에 대한 액세스를 설정하는 대체 옵션으로 `AmazonRekognitionServiceRole` 권한 정책을 사용할 수 있습니다. IAM은 *Rekognition* 서비스 역할 사용 사례를 제공합니다. 이 역할을 `AmazonRekognitionServiceRole` 권한 정책과 함께 사용할 경우 여러 Kinesis 데이터 스트림에 쓰기가 가능하며 모든 Kinesis 비디오 스트림에서 읽기를 할 수 있습니다. Amazon Rekognition Video에 여러 Kinesis 데이터 스트림에 대한 쓰기 권한을 부여하려면 Kinesis 데이터 스트림의 이름 앞에 *AmazonRekognition*을 추가하면 됩니다(예: `AmazonRekognitionMyDataStreamName`).

**Amazon Rekognition Video에 Kinesis 비디오 스트림 및 Kinesis 데이터 스트림에 대한 액세스 권한을 부여하려면**

1. [IAM 서비스 역할을 생성합니다](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console). 다음 정보를 사용하여 IAM 서비스 역할을 생성하세요.

   1. 서비스 이름으로 **Rekognition**을 선택합니다.

   1. 서비스 역할 사용 사례로 [**Rekognition**]을 선택합니다.

   1. **AmazonRekognitionServiceRole** 권한 정책을 선택하세요. 이는 Amazon Rekognition Video에 *AmazonRekognition* 접두사가 붙은 Kinesis 데이터 스트림에 대한 쓰기 액세스 권한 및 모든 Kinesis 비디오 스트림에 대한 읽기 액세스 권한을 부여하게 됩니다.

1.  AWS 계정 의 보안을 보장하려면 Rekognition의 액세스 범위를 사용 중인 리소스로만 제한합니다. 이는 IAM 서비스 역할에 신뢰 정책을 추가하는 것으로 수행할 수 있습니다. 이렇게 하는 방법에 대한 정보는 [교차 서비스 혼동된 대리인 방지](cross-service-confused-deputy-prevention.md) 단원을 참조하십시오.

1. 서비스 역할의 Amazon Resource Name(ARN)을 적어둡니다. 이것은 비디오 분석 작업을 시작할 때 필요합니다.

# 스트리밍 비디오에서 얼굴 검색
<a name="rekognition-video-stream-processor-search-faces"></a>

Amazon Rekognition Video는 스트리밍 비디오에서 감지한 얼굴과 일치하는 얼굴을 컬렉션에서 찾아낼 수 있습니다. 모음에 대한 자세한 내용은 [컬렉션에서 얼굴 검색](collections.md) 단원을 참조하십시오.

**Topics**
+ [Amazon Rekognition Video에 얼굴 검색 스트림 프로세서 생성](#streaming-video-creating-stream-processor)
+ [Amazon Rekognition Video 얼굴 검색 스트림 프로세서 시작](#streaming-video-starting-stream-processor)
+ [얼굴 검색을 위한 스트림 프로세서 사용(Java V2 예제)](#using-stream-processors-v2)
+ [얼굴 검색을 위한 스트림 프로세서 사용(Java V1 예제)](#using-stream-processors)
+ [스트리밍 비디오 분석 결과 읽기](streaming-video-kinesis-output.md)
+ [Kinesis Video Streams를 사용하여 로컬에서 Rekognition 결과 표시](displaying-rekognition-results-locally.md)
+ [Kinesis 얼굴 인식 JSON 프레임 레코드 이해](streaming-video-kinesis-output-reference.md)

다음 다이어그램은 Amazon Rekognition Video가 스트리밍 비디오에서 어떻게 얼굴을 감지하고 인식하는지 보여줍니다.

![\[Amazon Rekognition Video를 사용하여 Amazon Kinesis의 비디오 스트림을 처리하기 위한 워크플로 다이어그램입니다.\]](http://docs.aws.amazon.com/ko_kr/rekognition/latest/dg/images/VideoRekognitionStream.png)


## Amazon Rekognition Video에 얼굴 검색 스트림 프로세서 생성
<a name="streaming-video-creating-stream-processor"></a>

스트리밍 비디오를 분석하기 전에 Amazon Rekognition Video 스트림 프로세서를 만듭니다([CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)). 스트림 프로세서에는 Kinesis 데이터 스트림과 Kinesis 비디오 스트림에 대한 정보가 들어 있습니다. 또한 입력된 스트리밍 비디오에서 인식하고자 하는 얼굴이 포함된 모음의 식별자도 포함되어 있습니다. 스트림 프로세서의 이름도 지정합니다. 다음은 `CreateStreamProcessor` 요청에 대한 JSON 예제입니다.

```
{
       "Name": "streamProcessorForCam",
       "Input": {
              "KinesisVideoStream": {
                     "Arn": "arn:aws:kinesisvideo:us-east-1:nnnnnnnnnnnn:stream/inputVideo"
              }
       },
       "Output": {
              "KinesisDataStream": {
                     "Arn": "arn:aws:kinesis:us-east-1:nnnnnnnnnnnn:stream/outputData"
              }
       },
       "RoleArn": "arn:aws:iam::nnnnnnnnnnn:role/roleWithKinesisPermission",
       "Settings": {
              "FaceSearch": {
                     "CollectionId": "collection-with-100-faces",
                     "FaceMatchThreshold": 85.5
              }
       }
}
```

다음은 `CreateStreamProcessor`의 응답 예제입니다.

```
{
       “StreamProcessorArn”: “arn:aws:rekognition:us-east-1:nnnnnnnnnnnn:streamprocessor/streamProcessorForCam”
}
```

## Amazon Rekognition Video 얼굴 검색 스트림 프로세서 시작
<a name="streaming-video-starting-stream-processor"></a>

`CreateStreamProcessor`에서 지정한 스트림 프로세서 이름으로 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)를 직접 호출하여 스트리밍 비디오 분석을 시작합니다. 다음은 `StartStreamProcessor` 요청에 대한 JSON 예제입니다.

```
{
       "Name": "streamProcessorForCam"
}
```

스트림 프로세서가 성공적으로 시작되면 JSON 본문이 비어 있는 상태로 HTTP 200 응답이 반환됩니다.

## 얼굴 검색을 위한 스트림 프로세서 사용(Java V2 예제)
<a name="using-stream-processors-v2"></a>

다음 예제 코드는 Java용 AWS SDK 버전 2를 사용하여 [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) 및 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)와 같은 다양한 스트림 프로세서 작업을 호출하는 방법을 보여줍니다.

이 코드는 AWS 설명서 SDK 예제 GitHub 리포지토리에서 가져온 것입니다. 전체 예제는 [여기](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java)에서 확인하세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.CreateStreamProcessorRequest;
import software.amazon.awssdk.services.rekognition.model.CreateStreamProcessorResponse;
import software.amazon.awssdk.services.rekognition.model.FaceSearchSettings;
import software.amazon.awssdk.services.rekognition.model.KinesisDataStream;
import software.amazon.awssdk.services.rekognition.model.KinesisVideoStream;
import software.amazon.awssdk.services.rekognition.model.ListStreamProcessorsRequest;
import software.amazon.awssdk.services.rekognition.model.ListStreamProcessorsResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.StreamProcessor;
import software.amazon.awssdk.services.rekognition.model.StreamProcessorInput;
import software.amazon.awssdk.services.rekognition.model.StreamProcessorSettings;
import software.amazon.awssdk.services.rekognition.model.StreamProcessorOutput;
import software.amazon.awssdk.services.rekognition.model.StartStreamProcessorRequest;
import software.amazon.awssdk.services.rekognition.model.DescribeStreamProcessorRequest;
import software.amazon.awssdk.services.rekognition.model.DescribeStreamProcessorResponse;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateStreamProcessor {
    public static void main(String[] args) {
        final String usage = """
                
                Usage:    <role> <kinInputStream> <kinOutputStream> <collectionName> <StreamProcessorName>
                
                Where:
                   role - The ARN of the AWS Identity and Access Management (IAM) role to use. \s
                   kinInputStream - The ARN of the Kinesis video stream.\s
                   kinOutputStream - The ARN of the Kinesis data stream.\s
                   collectionName - The name of the collection to use that contains content. \s
                   StreamProcessorName - The name of the Stream Processor. \s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String role = args[0];
        String kinInputStream = args[1];
        String kinOutputStream = args[2];
        String collectionName = args[3];
        String streamProcessorName = args[4];

        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        processCollection(rekClient, streamProcessorName, kinInputStream, kinOutputStream, collectionName,
                role);
        startSpecificStreamProcessor(rekClient, streamProcessorName);
        listStreamProcessors(rekClient);
        describeStreamProcessor(rekClient, streamProcessorName);
        deleteSpecificStreamProcessor(rekClient, streamProcessorName);
    }

    public static void listStreamProcessors(RekognitionClient rekClient) {
        ListStreamProcessorsRequest request = ListStreamProcessorsRequest.builder()
                .maxResults(15)
                .build();

        ListStreamProcessorsResponse listStreamProcessorsResult = rekClient.listStreamProcessors(request);
        for (StreamProcessor streamProcessor : listStreamProcessorsResult.streamProcessors()) {
            System.out.println("StreamProcessor name - " + streamProcessor.name());
            System.out.println("Status - " + streamProcessor.status());
        }
    }

    private static void describeStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) {
        DescribeStreamProcessorRequest streamProcessorRequest = DescribeStreamProcessorRequest.builder()
                .name(StreamProcessorName)
                .build();

        DescribeStreamProcessorResponse describeStreamProcessorResult = rekClient
                .describeStreamProcessor(streamProcessorRequest);
        System.out.println("Arn - " + describeStreamProcessorResult.streamProcessorArn());
        System.out.println("Input kinesisVideo stream - "
                + describeStreamProcessorResult.input().kinesisVideoStream().arn());
        System.out.println("Output kinesisData stream - "
                + describeStreamProcessorResult.output().kinesisDataStream().arn());
        System.out.println("RoleArn - " + describeStreamProcessorResult.roleArn());
        System.out.println(
                "CollectionId - "
                        + describeStreamProcessorResult.settings().faceSearch().collectionId());
        System.out.println("Status - " + describeStreamProcessorResult.status());
        System.out.println("Status message - " + describeStreamProcessorResult.statusMessage());
        System.out.println("Creation timestamp - " + describeStreamProcessorResult.creationTimestamp());
        System.out.println("Last update timestamp - " + describeStreamProcessorResult.lastUpdateTimestamp());
    }

    private static void startSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) {
        try {
            StartStreamProcessorRequest streamProcessorRequest = StartStreamProcessorRequest.builder()
                    .name(StreamProcessorName)
                    .build();

            rekClient.startStreamProcessor(streamProcessorRequest);
            System.out.println("Stream Processor " + StreamProcessorName + " started.");

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    private static void processCollection(RekognitionClient rekClient, String StreamProcessorName,
                                          String kinInputStream, String kinOutputStream, String collectionName, String role) {
        try {
            KinesisVideoStream videoStream = KinesisVideoStream.builder()
                    .arn(kinInputStream)
                    .build();

            KinesisDataStream dataStream = KinesisDataStream.builder()
                    .arn(kinOutputStream)
                    .build();

            StreamProcessorOutput processorOutput = StreamProcessorOutput.builder()
                    .kinesisDataStream(dataStream)
                    .build();

            StreamProcessorInput processorInput = StreamProcessorInput.builder()
                    .kinesisVideoStream(videoStream)
                    .build();

            FaceSearchSettings searchSettings = FaceSearchSettings.builder()
                    .faceMatchThreshold(75f)
                    .collectionId(collectionName)
                    .build();

            StreamProcessorSettings processorSettings = StreamProcessorSettings.builder()
                    .faceSearch(searchSettings)
                    .build();

            CreateStreamProcessorRequest processorRequest = CreateStreamProcessorRequest.builder()
                    .name(StreamProcessorName)
                    .input(processorInput)
                    .output(processorOutput)
                    .roleArn(role)
                    .settings(processorSettings)
                    .build();

            CreateStreamProcessorResponse response = rekClient.createStreamProcessor(processorRequest);
            System.out.println("The ARN for the newly create stream processor is "
                    + response.streamProcessorArn());

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    private static void deleteSpecificStreamProcessor(RekognitionClient rekClient, String StreamProcessorName) {
        rekClient.stopStreamProcessor(a -> a.name(StreamProcessorName));
        rekClient.deleteStreamProcessor(a -> a.name(StreamProcessorName));
        System.out.println("Stream Processor " + StreamProcessorName + " deleted.");
    }
}
```

## 얼굴 검색을 위한 스트림 프로세서 사용(Java V1 예제)
<a name="using-stream-processors"></a>

다음 예제 코드는 Java V1을 사용하여 [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) 및[StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)와 같은 다양한 스트림 프로세서 작업을 직접 호출하는 방법을 보여줍니다. 이 예제에는 스트림 프로세서 작업을 직접 호출하는 메서드를 제공하는 스트림 프로세서 관리자 클래스(StreamManager)가 포함됩니다. 스타터 클래스(Starter)는 StreamManager 객체를 생성하고 다양한 작업을 호출합니다.

**예제를 구성하려면:**

1. Starter 클래스 멤버 필드의 값을 원하는 값으로 설정합니다.

1. Starter 클래스 함수 `main`에서 원하는 함수 호출을 주석 처리합니다.

### Starter 클래스
<a name="streaming-started"></a>

```
//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.)

// Starter class. Use to create a StreamManager class
// and call stream processor operations.
package com.amazonaws.samples;
import com.amazonaws.samples.*;

public class Starter {

	public static void main(String[] args) {
		
		
    	String streamProcessorName="Stream Processor Name";
    	String kinesisVideoStreamArn="Kinesis Video Stream Arn";
    	String kinesisDataStreamArn="Kinesis Data Stream Arn";
    	String roleArn="Role Arn";
    	String collectionId="Collection ID";
    	Float matchThreshold=50F;

		try {
			StreamManager sm= new StreamManager(streamProcessorName,
					kinesisVideoStreamArn,
					kinesisDataStreamArn,
					roleArn,
					collectionId,
					matchThreshold);
			//sm.createStreamProcessor();
			//sm.startStreamProcessor();
			//sm.deleteStreamProcessor();
			//sm.deleteStreamProcessor();
			//sm.stopStreamProcessor();
			//sm.listStreamProcessors();
			//sm.describeStreamProcessor();
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}
```

### StreamManager 클래스
<a name="streaming-manager"></a>

```
//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.)

// Stream manager class. Provides methods for calling
// Stream Processor operations.
package com.amazonaws.samples;

import com.amazonaws.services.rekognition.AmazonRekognition;
import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
import com.amazonaws.services.rekognition.model.CreateStreamProcessorRequest;
import com.amazonaws.services.rekognition.model.CreateStreamProcessorResult;
import com.amazonaws.services.rekognition.model.DeleteStreamProcessorRequest;
import com.amazonaws.services.rekognition.model.DeleteStreamProcessorResult;
import com.amazonaws.services.rekognition.model.DescribeStreamProcessorRequest;
import com.amazonaws.services.rekognition.model.DescribeStreamProcessorResult;
import com.amazonaws.services.rekognition.model.FaceSearchSettings;
import com.amazonaws.services.rekognition.model.KinesisDataStream;
import com.amazonaws.services.rekognition.model.KinesisVideoStream;
import com.amazonaws.services.rekognition.model.ListStreamProcessorsRequest;
import com.amazonaws.services.rekognition.model.ListStreamProcessorsResult;
import com.amazonaws.services.rekognition.model.StartStreamProcessorRequest;
import com.amazonaws.services.rekognition.model.StartStreamProcessorResult;
import com.amazonaws.services.rekognition.model.StopStreamProcessorRequest;
import com.amazonaws.services.rekognition.model.StopStreamProcessorResult;
import com.amazonaws.services.rekognition.model.StreamProcessor;
import com.amazonaws.services.rekognition.model.StreamProcessorInput;
import com.amazonaws.services.rekognition.model.StreamProcessorOutput;
import com.amazonaws.services.rekognition.model.StreamProcessorSettings;

public class StreamManager {

    private String streamProcessorName;
    private String kinesisVideoStreamArn;
    private String kinesisDataStreamArn;
    private String roleArn;
    private String collectionId;
    private float matchThreshold;

    private AmazonRekognition rekognitionClient;
    

    public StreamManager(String spName,
    		String kvStreamArn,
    		String kdStreamArn,
    		String iamRoleArn,
    		String collId,
    		Float threshold){
    	streamProcessorName=spName;
    	kinesisVideoStreamArn=kvStreamArn;
    	kinesisDataStreamArn=kdStreamArn;
    	roleArn=iamRoleArn;
    	collectionId=collId;
    	matchThreshold=threshold;
    	rekognitionClient=AmazonRekognitionClientBuilder.defaultClient();
    	
    }
    
    public void createStreamProcessor() {
    	//Setup input parameters
        KinesisVideoStream kinesisVideoStream = new KinesisVideoStream().withArn(kinesisVideoStreamArn);
        StreamProcessorInput streamProcessorInput =
                new StreamProcessorInput().withKinesisVideoStream(kinesisVideoStream);
        KinesisDataStream kinesisDataStream = new KinesisDataStream().withArn(kinesisDataStreamArn);
        StreamProcessorOutput streamProcessorOutput =
                new StreamProcessorOutput().withKinesisDataStream(kinesisDataStream);
        FaceSearchSettings faceSearchSettings =
                new FaceSearchSettings().withCollectionId(collectionId).withFaceMatchThreshold(matchThreshold);
        StreamProcessorSettings streamProcessorSettings =
                new StreamProcessorSettings().withFaceSearch(faceSearchSettings);

        //Create the stream processor
        CreateStreamProcessorResult createStreamProcessorResult = rekognitionClient.createStreamProcessor(
                new CreateStreamProcessorRequest().withInput(streamProcessorInput).withOutput(streamProcessorOutput)
                        .withSettings(streamProcessorSettings).withRoleArn(roleArn).withName(streamProcessorName));

        //Display result
        System.out.println("Stream Processor " + streamProcessorName + " created.");
        System.out.println("StreamProcessorArn - " + createStreamProcessorResult.getStreamProcessorArn());
    }

    public void startStreamProcessor() {
        StartStreamProcessorResult startStreamProcessorResult =
                rekognitionClient.startStreamProcessor(new StartStreamProcessorRequest().withName(streamProcessorName));
        System.out.println("Stream Processor " + streamProcessorName + " started.");
    }

    public void stopStreamProcessor() {
        StopStreamProcessorResult stopStreamProcessorResult =
                rekognitionClient.stopStreamProcessor(new StopStreamProcessorRequest().withName(streamProcessorName));
        System.out.println("Stream Processor " + streamProcessorName + " stopped.");
    }

    public void deleteStreamProcessor() {
        DeleteStreamProcessorResult deleteStreamProcessorResult = rekognitionClient
                .deleteStreamProcessor(new DeleteStreamProcessorRequest().withName(streamProcessorName));
        System.out.println("Stream Processor " + streamProcessorName + " deleted.");
    }

    public void describeStreamProcessor() {
        DescribeStreamProcessorResult describeStreamProcessorResult = rekognitionClient
                .describeStreamProcessor(new DescribeStreamProcessorRequest().withName(streamProcessorName));

        //Display various stream processor attributes.
        System.out.println("Arn - " + describeStreamProcessorResult.getStreamProcessorArn());
        System.out.println("Input kinesisVideo stream - "
                + describeStreamProcessorResult.getInput().getKinesisVideoStream().getArn());
        System.out.println("Output kinesisData stream - "
                + describeStreamProcessorResult.getOutput().getKinesisDataStream().getArn());
        System.out.println("RoleArn - " + describeStreamProcessorResult.getRoleArn());
        System.out.println(
                "CollectionId - " + describeStreamProcessorResult.getSettings().getFaceSearch().getCollectionId());
        System.out.println("Status - " + describeStreamProcessorResult.getStatus());
        System.out.println("Status message - " + describeStreamProcessorResult.getStatusMessage());
        System.out.println("Creation timestamp - " + describeStreamProcessorResult.getCreationTimestamp());
        System.out.println("Last update timestamp - " + describeStreamProcessorResult.getLastUpdateTimestamp());
    }

    public void listStreamProcessors() {
        ListStreamProcessorsResult listStreamProcessorsResult =
                rekognitionClient.listStreamProcessors(new ListStreamProcessorsRequest().withMaxResults(100));

        //List all stream processors (and state) returned from Rekognition
        for (StreamProcessor streamProcessor : listStreamProcessorsResult.getStreamProcessors()) {
            System.out.println("StreamProcessor name - " + streamProcessor.getName());
            System.out.println("Status - " + streamProcessor.getStatus());
        }
    }
}
```

# 스트리밍 비디오 분석 결과 읽기
<a name="streaming-video-kinesis-output"></a>

Amazon Kinesis Data Streams 클라이언트 라이브러리를 사용하여 Amazon Kinesis Data Streams 출력 스트림으로 전송되는 분석 결과를 사용할 수 있습니다. 자세한 내용은 [Kinesis 데이터 스트림에서 데이터 읽기](https://docs.aws.amazon.com/streams/latest/dev/building-consumers.html)를 참조하세요. Amazon Rekognition Video는 분석된 각 프레임에 대한 JSON 프레임 레코드를 Kinesis 출력 스트림에 저장합니다. Amazon Rekognition Video는 Kinesis 비디오 스트림을 통해 전달되는 모든 프레임을 분석하지는 않습니다.

Kinesis 데이터 스트림으로 전송되는 프레임 레코드에는 프레임이 있는 Kinesis 비디오 스트림 조각, 조각 내에서 프레임의 위치, 프레임에서 인식되는 얼굴에 대한 정보가 포함되어 있습니다. 또한 스트림 프로세서의 상태 정보도 포함됩니다. 자세한 내용은 [Kinesis 얼굴 인식 JSON 프레임 레코드 이해](streaming-video-kinesis-output-reference.md) 단원을 참조하십시오.

Amazon Kinesis Video Streams 구문 분석 라이브러리에는 Amazon Rekognition Video 결과를 사용하고 이를 원본 Kinesis 비디오 스트림과 통합하는 예제 테스트가 포함되어 있습니다. 자세한 내용은 [Kinesis Video Streams를 사용하여 로컬에서 Rekognition 결과 표시](displaying-rekognition-results-locally.md) 단원을 참조하십시오.

Amazon Rekognition Video는 Amazon Rekognition Video 분석 정보를 Kinesis 데이터 스트림으로 스트리밍합니다. 다음은 단일 레코드에 대한 JSON 예제입니다.

```
{
  "InputInformation": {
    "KinesisVideo": {
      "StreamArn": "arn:aws:kinesisvideo:us-west-2:nnnnnnnnnnnn:stream/stream-name",
      "FragmentNumber": "91343852333289682796718532614445757584843717598",
      "ServerTimestamp": 1510552593.455,
      "ProducerTimestamp": 1510552593.193,
      "FrameOffsetInSeconds": 2
    }
  },
  "StreamProcessorInformation": {
    "Status": "RUNNING"
  },
  "FaceSearchResponse": [
    {
      "DetectedFace": {
        "BoundingBox": {
          "Height": 0.075,
          "Width": 0.05625,
          "Left": 0.428125,
          "Top": 0.40833333
        },
        "Confidence": 99.975174,
        "Landmarks": [
          {
            "X": 0.4452057,
            "Y": 0.4395594,
            "Type": "eyeLeft"
          },
          {
            "X": 0.46340984,
            "Y": 0.43744427,
            "Type": "eyeRight"
          },
          {
            "X": 0.45960626,
            "Y": 0.4526856,
            "Type": "nose"
          },
          {
            "X": 0.44958648,
            "Y": 0.4696949,
            "Type": "mouthLeft"
          },
          {
            "X": 0.46409217,
            "Y": 0.46704912,
            "Type": "mouthRight"
          }
        ],
        "Pose": {
          "Pitch": 2.9691637,
          "Roll": -6.8904796,
          "Yaw": 23.84388
        },
        "Quality": {
          "Brightness": 40.592964,
          "Sharpness": 96.09616
        }
      },
      "MatchedFaces": [
        {
          "Similarity": 88.863960,
          "Face": {
            "BoundingBox": {
              "Height": 0.557692,
              "Width": 0.749838,
              "Left": 0.103426,
              "Top": 0.206731
            },
            "FaceId": "ed1b560f-d6af-5158-989a-ff586c931545",
            "Confidence": 99.999201,
            "ImageId": "70e09693-2114-57e1-807c-50b6d61fa4dc",
            "ExternalImageId": "matchedImage.jpeg"
          }
        }
      ]
    }
  ]
}
```

JSON 예제에서 다음 사항에 유의하십시오.
+ **InputInformation** - Amazon Rekognition Video로 비디오를 스트리밍하는 데 사용되는 Kinesis 비디오 스트림에 관한 정보입니다. 자세한 내용은 [InputInformation](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-inputinformation) 단원을 참조하십시오.
+ **StreamProcessorInformation** - Amazon Rekognition Video 스트림 프로세서의 상태 정보입니다. `Status` 필드에 입력할 수 있는 값은 RUNNING뿐입니다. 자세한 내용은 [StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md) 단원을 참조하십시오.
+ **FaceSearchResponse** - 입력 컬렉션의 얼굴과 일치하는 스트리밍 비디오 속의 얼굴에 대한 정보가 들어 있습니다. [FaceSearchResponse](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facesearchresponse)에는 분석한 비디오 프레임에서 감지된 얼굴, 즉 [DetectedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-detectedface) 객체가 포함되어 있습니다. `MatchedFaces` 배열에는 감지된 얼굴별로 입력 모음에서 발견된 일치하는 얼굴 객체([MatchedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facematch))와 유사성 점수가 나와 있습니다.

## Kinesis 비디오 스트림을 Kinesis 데이터 스트림으로 매핑
<a name="mapping-streams"></a>

Kinesis 비디오 스트림 프레임을 Kinesis 데이터 스트림으로 전송되는 분석 프레임으로 매핑하고자 하는 경우가 있을 수 있습니다. 예를 들어 스트리밍 동영상이 표시되는 도중에도 인식된 사람들의 얼굴 주위로 상자를 표시하는 것이 가능합니다. 경계 상자 좌표는 Kinesis 얼굴 인식 레코드에 포함되어 Kinesis 데이터 스트림으로 전송됩니다. 경계 상자를 정확하게 표시하려면 Kinesis 얼굴 인식 레코드와 함께 전송된 시간 정보를 원본 Kinesis 비디오 스트림의 해당 프레임과 매핑시켜야 합니다.

Kinesis 비디오 스트림을 Kinesis 데이터 스트림에 매핑할 때 사용하는 기법은 라이브 미디어(라이브 스트리밍 비디오 등)를 스트리밍하는지 또는 아카이브 미디어(저장된 비디오 등)를 스트리밍하는지에 따라 달라집니다.

### 라이브 미디어를 스트리밍하는 경우의 매핑
<a name="mapping-streaming-video"></a>

**Kinesis 비디오 스트림 프레임을 Kinesis 데이터 스트림 프레임에 매핑하려면**

1. [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) 작업의 입력 파라미터 `FragmentTimeCodeType`을 `RELATIVE`로 설정합니다.

1. `PutMedia`를 직접 호출하여 라이브 미디어를 Kinesis 비디오 스트림에 전송하세요.

1. Kinesis 데이터 스트림에서 Kinesis 얼굴 인식 레코드를 수신하면 [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) 필드의 `ProducerTimestamp` 값과 `FrameOffsetInSeconds` 값을 저장합니다.

1. `ProducerTimestamp` 필드 값과 `FrameOffsetInSeconds` 필드 값을 합산하여 Kinesis 비디오 스트림 프레임에 대응하는 타임스탬프를 계산합니다.

### 아카이브 미디어를 스트리밍하는 경우의 매핑
<a name="map-stored-video"></a>

**Kinesis 비디오 스트림 프레임을 Kinesis 데이터 스트림 프레임에 매핑하려면**

1. [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html)를 직접 호출하여 아카이브 미디어를 Kinesis 비디오 스트림으로 전달합니다.

1. `PutMedia` 작업 응답에서 `Acknowledgement` 객체를 수신하면 [Payload](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html#API_dataplane_PutMedia_ResponseSyntax) 필드의 `FragmentNumber` 필드 값을 저장합니다. `FragmentNumber`는 MKV 클러스터의 조각 번호입니다.

1. Kinesis 데이터 스트림에서 Kinesis 얼굴 인식 레코드를 수신하면 [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) 필드의 `FrameOffsetInSeconds` 값을 저장합니다.

1. 2단계와 3단계에서 저장한 `FrameOffsetInSeconds` 및 `FragmentNumber` 값을 사용하여 매핑을 계산합니다. 여기에서 `FrameOffsetInSeconds`는 Amazon Kinesis 데이터 스트림으로 전송되는 특정 `FragmentNumber`에 대한 오프셋입니다. 임의의 조각 번호에 대한 비디오 프레임을 가져오는 방법에 대한 자세한 내용은 [Amazon Kinesis Video Streams 아카이브 미디어](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_Operations_Amazon_Kinesis_Video_Streams_Archived_Media.html)를 참조하세요.

# Kinesis Video Streams를 사용하여 로컬에서 Rekognition 결과 표시
<a name="displaying-rekognition-results-locally"></a>

 [KinesisVideo - Rekognition 예제](https://github.com/aws/amazon-kinesis-video-streams-parser-library#kinesisvideo---rekognition-examples)에서 제공하는 Amazon Kinesis Video Streams 구문 분석 라이브러리의 예제 테스트를 사용하여 Amazon Kinesis Video Streams의 피드에 표시된 Amazon Rekognition Video의 결과를 확인할 수 있습니다. `KinesisVideoRekognitionIntegrationExample`는 감지된 얼굴 위에 경계 상자를 표시하고 JFrame을 통해 로컬에서 비디오를 렌더링합니다. 이 프로세스는 디바이스 카메라의 미디어 입력을 Kinesis 비디오 스트림에 성공적으로 연결하고 Amazon Rekognition 스트림 프로세서를 시작했다는 것을 가정한 것입니다. 자세한 내용은 [GStreamer 플러그인을 사용한 스트리밍](streaming-using-gstreamer-plugin.md) 단원을 참조하십시오.

## 1단계: Kinesis Video Streams 구문 분석 라이브러리 설치
<a name="step-1-install-parser-library"></a>

 디렉터리를 생성하고 GitHub 리포지토리를 다운로드하려면 다음 명령을 실행하세요.

```
$ git clone https://github.com/aws/amazon-kinesis-video-streams-parser-library.git
```

 라이브러리 디렉터리로 이동한 후 다음 Maven 명령을 실행하여 클린 설치를 수행합니다.

```
$ mvn clean install
```

## 2단계: Kinesis Video Streams 및 Rekognition 통합 예제 테스트 구성
<a name="step-2-configure-kinesis-video-rekognition-example-test"></a>

 `KinesisVideoRekognitionIntegrationExampleTest.java` 파일을 엽니다. 클래스 헤더 바로 뒤에 있는 `@Ignore`를 제거합니다. Amazon Kinesis 및 Amazon Rekognition 리소스의 정보로 데이터 필드를 채웁니다. 자세한 내용은 [Amazon Rekognition Video 및 Amazon Kinesis 리소스 설정](setting-up-your-amazon-rekognition-streaming-video-resources.md) 단원을 참조하십시오. Kinesis 비디오 스트림으로 비디오를 스트리밍하는 경우 `inputStream` 파라미터를 제거하세요.

 다음 코드 예제를 참조하세요.

```
RekognitionInput rekognitionInput = RekognitionInput.builder()
  .kinesisVideoStreamArn("arn:aws:kinesisvideo:us-east-1:123456789012:stream/rekognition-test-video-stream")
  .kinesisDataStreamArn("arn:aws:kinesis:us-east-1:123456789012:stream/AmazonRekognition-rekognition-test-data-stream")
  .streamingProcessorName("rekognition-test-stream-processor")
  // Refer how to add face collection :
  // https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html
  .faceCollectionId("rekognition-test-face-collection")
  .iamRoleArn("rekognition-test-IAM-role")
  .matchThreshold(0.95f)
  .build();                
            
KinesisVideoRekognitionIntegrationExample example = KinesisVideoRekognitionIntegrationExample.builder()
  .region(Regions.US_EAST_1)
  .kvsStreamName("rekognition-test-video-stream")
  .kdsStreamName("AmazonRekognition-rekognition-test-data-stream")
  .rekognitionInput(rekognitionInput)
  .credentialsProvider(new ProfileCredentialsProvider())
  // NOTE: Comment out or delete the inputStream parameter if you are streaming video, otherwise
  // the test will use a sample video. 
  //.inputStream(TestResourceUtil.getTestInputStream("bezos_vogels.mkv"))
  .build();
```

## 3단계: Kinesis Video Streams 및 Rekognition 통합 예제 테스트 실행
<a name="step-3-run-kinesis-video-rekognition-example-test"></a>

 Kinesis 비디오 스트림으로 스트리밍하는 경우 Kinesis 비디오 스트림이 미디어 입력을 받고 있는지 확인하고 Amazon Rekognition Video 스트림 프로세서가 실행 중인 상태에서 스트림 분석을 시작하세요. 자세한 내용은 [Amazon Rekognition Video 스트림 프로세서 작업 개요](streaming-video.md#using-rekognition-video-stream-processor) 단원을 참조하십시오. `KinesisVideoRekognitionIntegrationExampleTest` 클래스를 JUnit 테스트로 실행하세요. 잠시 후 Kinesis 비디오 스트림의 비디오 피드가 포함된 새 창이 열리고 감지된 얼굴 위에 경계 상자가 그려집니다.

**참고**  
 이 예제에 사용된 컬렉션의 얼굴에 경계 상자 레이블이 유의미한 텍스트를 표시하기 위해서는 외부 이미지 ID(파일 이름)가 다음 형식으로 지정되어 있어야 합니다. PersonName1-Trusted, PersonName2-Intruder, PersonName3-Neutral 등. 레이블은 색상으로 구분할 수도 있으며 FaceType.java 파일에서 사용자 지정할 수도 있습니다.

# Kinesis 얼굴 인식 JSON 프레임 레코드 이해
<a name="streaming-video-kinesis-output-reference"></a>

Amazon Rekognition Video를 사용하면 스트리밍 비디오에서 얼굴을 인식할 수 있습니다. Amazon Rekognition Video는 분석된 각 프레임마다 JSON 프레임 레코드를 Kinesis 데이터 스트림으로 출력합니다. Amazon Rekognition Video는 Kinesis 비디오 스트림을 통해 전달되는 모든 프레임을 분석하지는 않습니다.

JSON 프레임 레코드에는 입력 및 출력 스트림, 스트림 프로세서의 상태, 분석된 프레임에서 인식되는 얼굴에 대한 정보가 들어 있습니다. 이 단원에서는 JSON 프레임 레코드에 대한 참조 정보를 제시합니다.

다음은 Kinesis 데이터 스트림 레코드에 대한 JSON 구문입니다. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

**참고**  
Amazon Rekognition Video API는 입력 스트림의 얼굴을 얼굴 컬렉션과 비교하고 검색된 가장 근접한 일치 항목을 유사성 점수와 함께 반환하는 방식으로 작동합니다.

```
{
    "InputInformation": {
        "KinesisVideo": {
            "StreamArn": "string",
            "FragmentNumber": "string",
            "ProducerTimestamp": number,
            "ServerTimestamp": number,
            "FrameOffsetInSeconds": number
        }
    },
    "StreamProcessorInformation": {
        "Status": "RUNNING"
    },
    "FaceSearchResponse": [
        {
            "DetectedFace": {
                "BoundingBox": {
                    "Width": number,
                    "Top": number,
                    "Height": number,
                    "Left": number
                },
                "Confidence": number,
                "Landmarks": [
                    {
                        "Type": "string",
                        "X": number,
                        "Y": number
                    }
                ],
                "Pose": {
                    "Pitch": number,
                    "Roll": number,
                    "Yaw": number
                },
                "Quality": {
                    "Brightness": number,
                    "Sharpness": number
                }
            },
            "MatchedFaces": [
                {
                    "Similarity": number,
                    "Face": {
                        "BoundingBox": {
                            "Width": number,
                            "Top": number,
                            "Height": number,
                            "Left": number
                        },
                        "Confidence": number,
                        "ExternalImageId": "string",
                        "FaceId": "string",
                        "ImageId": "string"
                    }
                }
            ]
        }
    ]
}
```

## JSON 레코드
<a name="streaming-video-kinesis-output-reference-processorresult"></a>

JSON 레코드에는 Amazon Rekognition Video에서 처리하는 프레임에 대한 정보가 포함되어 있습니다. 레코드에는 스트리밍 비디오, 분석된 프레임의 상태, 프레임에서 인식되는 얼굴에 대한 정보가 포함됩니다.

**InputInformation**

Amazon Rekognition Video로 비디오를 스트리밍하는 데 사용되는 Kinesis 비디오 스트림에 대한 정보입니다.

유형: [InputInformation](#streaming-video-kinesis-output-reference-inputinformation)객체

**StreamProcessorInformation**

Amazon Rekognition Video 스트림 프로세서에 대한 정보. 여기에는 스트림 프로세서의 현재 상태에 대한 상태 정보가 포함됩니다.

유형: [StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md)객체 

**FaceSearchResponse**

스트리밍 비디오 프레임에서 감지된 얼굴과 입력 모음에서 발견된 일치하는 얼굴에 대한 정보입니다.

유형: [FaceSearchResponse](#streaming-video-kinesis-output-reference-facesearchresponse) 객체 배열

## InputInformation
<a name="streaming-video-kinesis-output-reference-inputinformation"></a>

Amazon Rekognition Video에서 사용하는 소스 비디오 스트림에 대한 정보입니다. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

**KinesisVideo**

유형: [KinesisVideo](#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo)객체

## KinesisVideo
<a name="streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo"></a>

소스 비디오를 Amazon Rekognition Video로 스트리밍하는 Kinesis 비디오 스트림에 대한 정보입니다. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

**StreamArn**

Kinesis 비디오 스트림의 Amazon 리소스 이름(ARN)입니다.

유형: 문자열 

**FragmentNumber**

이 레코드가 나타내는 프레임이 포함된 스트리밍 비디오 조각입니다.

유형: 문자열

**ProducerTimestamp**

조각의 생산자 측 Unix 타임스탬프입니다. 자세한 내용은 [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) 단원을 참조하십시오.

형식: 숫자

**ServerTimestamp**

조각의 서버 측 Unix 타임스탬프입니다. 자세한 내용은 [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) 단원을 참조하십시오.

형식: 숫자

**FrameOffsetInSeconds**

조각 내의 프레임 오프셋(초 단위)입니다.

형식: 숫자 

# StreamProcessorInformation
<a name="streaming-video-kinesis-output-reference-streamprocessorinformation"></a>

스트림 프로세서에 대한 상태 정보입니다.

**상태**

스트림 프로세서의 현재 상태입니다. 가능한 값은 RUNNING입니다.

유형: 문자열

## FaceSearchResponse
<a name="streaming-video-kinesis-output-reference-facesearchresponse"></a>

스트리밍 비디오 프레임에서 감지된 얼굴과 모음에서 발견된 그것과 일치하는 얼굴에 대한 정보입니다. 컬렉션은 [CreateStreamProcessor를](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) 직접 호출하여 지정합니다. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

**DetectedFace**

분석된 비디오 프레임에서 감지된 얼굴의 세부 정보입니다.

유형: [DetectedFace](#streaming-video-kinesis-output-reference-detectedface)객체

**MatchedFaces**

`DetectedFace`에서 감지된 얼굴과 일치하는 얼굴 모음의 세부 정보 배열입니다.

유형: [MatchedFace](#streaming-video-kinesis-output-reference-facematch) 객체 배열

## DetectedFace
<a name="streaming-video-kinesis-output-reference-detectedface"></a>

스트리밍 비디오 프레임에서 감지된 얼굴에 대한 정보입니다. 입력 모음에 들어 있는 일치하는 얼굴은 [MatchedFace](#streaming-video-kinesis-output-reference-facematch) 객체 필드에서 사용할 수 있습니다.

**BoundingBox**

분석된 비디오 프레임 내에서 감지된 얼굴의 경계 상자 좌표입니다. BoundingBox 객체는 이미지 분석에 사용되는 BoundingBox 객체와 동일한 속성을 가집니다.

유형: [BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html) 객체 

**신뢰도**

Amazon Rekognition Video에서 감지된 얼굴이 실제로 얼굴임을 신뢰할 수 있는 수준(1\$1100)입니다. 1은 가장 낮은 신뢰도, 100은 가장 높은 신뢰도입니다.

형식: 숫자

**표식**

얼굴 표식의 배열입니다.

유형: [Landmark](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Landmark.html) 객체 배열

**포즈**

피치, 롤 및 요로 판단되는 얼굴의 포즈를 나타냅니다.

유형: [Pose](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Pose.html) 객체

**화질**

얼굴 이미지의 밝기와 선명도를 나타냅니다.

유형: [ImageQuality](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ImageQuality.html) 객체

## MatchedFace
<a name="streaming-video-kinesis-output-reference-facematch"></a>

분석된 비디오 프레임에서 감지된 얼굴과 일치하는 얼굴에 대한 정보입니다.

**얼굴**

[DetectedFace](#streaming-video-kinesis-output-reference-detectedface) 객체의 얼굴과 일치하는, 입력 모음의 얼굴에 대한 얼굴 일치 정보입니다.

유형: [Face](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Face.html) 객체 

**유사성**

얼굴 일치의 신뢰 수준(1\$1100)입니다. 1은 가장 낮은 신뢰도, 100은 가장 높은 신뢰도입니다.

형식: 숫자 

# GStreamer 플러그인을 사용한 스트리밍
<a name="streaming-using-gstreamer-plugin"></a>

Amazon Rekognition Video는 디바이스 카메라의 라이브 스트리밍 비디오를 분석할 수 있습니다. 디바이스 소스에서의 미디어 입력에 액세스하려면 GStreamer를 설치해야 합니다. GStreamer는 워크플로 파이프라인에서 미디어 소스와 처리 도구를 함께 연결하는 서드 파티 멀티미디어 프레임워크 소프트웨어입니다. Gstreamer용 [Amazon Kinesis Video Streams Producer 플러그인](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/)도 설치해야 합니다. 이 프로세스에서는 Amazon Rekognition Video 및 Amazon Kinesis 리소스를 성공적으로 설정했다고 가정합니다. 자세한 내용은 [Amazon Rekognition Video 및 Amazon Kinesis 리소스 설정](setting-up-your-amazon-rekognition-streaming-video-resources.md) 단원을 참조하십시오.

## 1단계: Gstreamer 설치
<a name="step-1-install-gstreamer"></a>

 서드 파티 멀티미디어 플랫폼 소프트웨어인 Gstreamer를 다운로드하여 설치합니다. Homebrew([Gstreamer on Homebrew](https://formulae.brew.sh/formula/gstreamer))와 같은 패키지 관리 소프트웨어를 사용하거나 [Freedesktop 웹사이트](https://gstreamer.freedesktop.org/download/)에서 직접 다운로드할 수 있습니다.

 명령줄 터미널의 테스트 소스로 비디오 피드를 실행하여 Gstreamer가 성공적으로 설치되었는지 확인하세요.

```
$ gst-launch-1.0 videotestsrc ! autovideosink
```

## 2단계: Kinesis Video Streams Producer 플러그인 설치
<a name="step-2-install-kinesis-video-plugin"></a>

 이 섹션에서는 [Amazon Kinesis Video Streams Producer 라이브러리](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/)를 다운로드하고 Kinesis Video Streams Gstreamer 플러그인을 설치합니다.

 디렉터리를 생성하고 GitHub 리포지토리에서 소스 코드를 복제합니다. `--recursive` 파라미터가 반드시 포함되어야 합니다.

```
$ git clone --recursive https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp.git
```

[라이브러리에서 제공하는 지침](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/blob/master/README.md)에 따라 프로젝트를 구성하고 빌드하세요. 운영 체제에 맞는 플랫폼별 명령을 사용해야 합니다. Kinesis Video Streams Gstreamer 플러그인 설치를 위해 `cmake`를 실행할 때 `-DBUILD_GSTREAMER_PLUGIN=ON` 파라미터를 사용하세요. 이 프로젝트에는 설치에 포함된 GCC 또는 Clang, Curl, Openssl 및 Log4cplus와 같은 추가 패키지가 필요합니다. 패키지 누락으로 인해 빌드가 실패하는 경우 해당 패키지가 설치되어 있고 PATH에 위치해 있는지 확인하세요. 빌드 중 "can't run C compiled program" 오류가 발생한 경우, 빌드 명령을 다시 실행하세요. 올바른 C 컴파일러를 찾을 수 없는 경우가 있습니다.

 다음 명령을 실행하여 Kinesis Video Streams 플러그인의 설치를 확인하세요.

```
$ gst-inspect-1.0 kvssink
```

 팩토리 및 플러그인 세부 정보와 같은 다음 정보가 표시되어야 합니다.

```
Factory Details:
  Rank                     primary + 10 (266)
  Long-name                KVS Sink
  Klass                    Sink/Video/Network
  Description              GStreamer AWS KVS plugin
  Author                   AWS KVS <kinesis-video-support@amazon.com>
                
Plugin Details:
  Name                     kvssink
  Description              GStreamer AWS KVS plugin
  Filename                 /Users/YOUR_USER/amazon-kinesis-video-streams-producer-sdk-cpp/build/libgstkvssink.so
  Version                  1.0
  License                  Proprietary
  Source module            kvssinkpackage
  Binary package           GStreamer
  Origin URL               http://gstreamer.net/
  
  ...
```

## 3단계: Kinesis Video Streams 플러그인을 사용하여 Gstreamer 실행
<a name="step-3-run-gstreamer-with-kinesis-video-plugin"></a>

 디바이스 카메라에서 Kinesis Video Streams로 스트리밍을 시작하기 전에 미디어 소스를 Kinesis Video Streams에 적합한 코덱으로 변환해야 할 수 있습니다. 현재 컴퓨터에 연결된 디바이스의 사양과 포맷 기능을 확인하려면 다음 명령을 실행하세요.

```
$ gst-device-monitor-1.0
```

 스트리밍을 시작하려면 다음 샘플 명령을 사용하여 Gstreamer를 실행하고 보안 인증 정보 및 Amazon Kinesis Video Streams 정보를 추가합니다. [Amazon Rekognition에 Kinesis 스트림에 대한 액세스 부여](https://docs.aws.amazon.com/rekognition/latest/dg/api-streaming-video-roles.html#api-streaming-video-roles-all-stream) 중에 생성한 IAM 서비스 역할에 맞는 액세스 키와 리전을 사용해야 합니다. 액세스 키에 대한 자세한 내용은 *IAM 사용 설명서*의 [IAM 사용자의 액세스 키 관리](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)를 참조하세요. 또한 비디오 형식 인수 파라미터를 디바이스에서 사용 가능하다면 사용량에 따라 필요한 대로 조정할 수 있습니다.

```
$ gst-launch-1.0 autovideosrc device=/dev/video0 ! videoconvert ! video/x-raw,format=I420,width=640,height=480,framerate=30/1 ! 
                x264enc bframes=0 key-int-max=45 bitrate=500 ! video/x-h264,stream-format=avc,alignment=au,profile=baseline ! 
                kvssink stream-name="YOUR_STREAM_NAME" storage-size=512 access-key="YOUR_ACCESS_KEY" secret-key="YOUR_SECRET_ACCESS_KEY" aws-region="YOUR_AWS_REGION"
```

 시작 명령에 대한 자세한 내용은 [GStreamer 시작 명령 예제](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-gstreamer-plugin.html#examples-gstreamer-plugin-launch)를 참조하세요.

**참고**  
 시작 명령이 비협상 오류로 종료되는 경우 디바이스 모니터의 출력값을 확인하고 `videoconvert` 파라미터 값이 디바이스의 설정에 유효한지 확인하세요.

 몇 초 후에 Kinesis 비디오 스트림에서 디바이스 카메라의 비디오 피드를 볼 수 있습니다. Amazon Rekognition으로 얼굴 감지 및 일치를 시작하려면 Amazon Rekognition Video 스트림 프로세서를 시작하세요. 자세한 내용은 [Amazon Rekognition Video 스트림 프로세서 작업 개요](streaming-video.md#using-rekognition-video-stream-processor) 단원을 참조하십시오.

# 스트리밍 비디오 문제 해결
<a name="streaming-video-troubleshooting"></a>

이 주제에서는 Amazon Rekognition Video를 스트리밍 비디오에 사용할 경우의 문제 해결 정보를 제공합니다.

**Topics**
+ [스트림 프로세서가 성공적으로 생성되었는지 모르겠습니다.](#ts-streaming-video-create-sp)
+ [스트림 프로세서를 올바로 구성했는지 모르겠습니다](#ts-configured-sp)
+ [스트림 프로세서가 결과를 반환하지 않습니다](#ts-streaming-video-no-results-from-sp)
+ [스트림 프로세서의 상태가 FAILED입니다](#ts-failed-state)
+ [스트림 프로세서가 예상 결과를 반환하지 않습니다](#w2aac27c79c27c15)

## 스트림 프로세서가 성공적으로 생성되었는지 모르겠습니다.
<a name="ts-streaming-video-create-sp"></a>

다음 AWS CLI 명령을 사용하여 스트림 프로세서 목록과 현재 상태를 가져옵니다.

```
aws rekognition list-stream-processors
```

다음 AWS CLI 명령을 사용하여 추가 세부 정보를 얻을 수 있습니다. `stream-processor-name`을 요청된 스트림 프로세서 이름으로 바꿉니다.

```
aws rekognition describe-stream-processor --name stream-processor-name
```

## 스트림 프로세서를 올바로 구성했는지 모르겠습니다
<a name="ts-configured-sp"></a>

코드가 Amazon Rekognition Video에서 분석 결과를 출력하고 있지 않다면 스트림 프로세서가 올바로 구성되지 않았을 수 있습니다. 다음을 수행하여 스트림 프로세서가 올바로 구성되었고 결과를 생성할 수 있는지 확인하십시오.

**솔루션이 올바로 구성되었는지 확인하려면**

1. 다음 명령을 실행하여 스트림 프로세서가 실행 중 상태인지 확인합니다. `stream-processor-name`을 해당 스트림 프로세서의 이름으로 변경합니다. `Status` 값이 `RUNNING`이라면 스트림 프로세서가 실행 중인 것입니다. 상태가 `RUNNING`이고 결과를 얻지 못하는 경우, [스트림 프로세서가 결과를 반환하지 않습니다](#ts-streaming-video-no-results-from-sp) 단원을 참조하십시오. 상태가 `FAILED`인 경우, [스트림 프로세서의 상태가 FAILED입니다](#ts-failed-state) 단원을 참조하십시오.

   ```
   aws rekognition describe-stream-processor --name stream-processor-name
   ```

1. 스트림 프로세서가 실행 중이라면 다음 Bash 또는 PowerShell 명령을 실행하여 출력 Kinesis 데이터 스트림에서 데이터를 읽습니다.

   **Bash**

   ```
   SHARD_ITERATOR=$(aws kinesis get-shard-iterator --shard-id shardId-000000000000 --shard-iterator-type TRIM_HORIZON --stream-name kinesis-data-stream-name --query 'ShardIterator')
                           aws kinesis get-records --shard-iterator $SHARD_ITERATOR
   ```

   **PowerShell**

   ```
   aws kinesis get-records --shard-iterator ((aws kinesis get-shard-iterator --shard-id shardId-000000000000 --shard-iterator-type TRIM_HORIZON --stream-name kinesis-data-stream-name).split('"')[4])
   ```

1. Base64 Decode 웹사이트에서 [Decode 도구](https://www.base64decode.org/)를 사용하여 출력을 사람이 읽을 수 있는 문자열로 디코딩합니다. 자세한 내용은 [3단계: 레코드 가져오기](https://docs.aws.amazon.com/streams/latest/dev/fundamental-stream.html#get-records)를 참조하십시오.

1. 명령이 작동하고 Kinesis 데이터 스트림에서 얼굴 감지 결과가 표시된다면 솔루션이 올바로 구성된 것입니다. 명령이 실패하면 다른 문제 해결 제안을 확인하고 [Amazon Rekognition Video에 리소스에 대한 액세스 권한 부여](api-streaming-video-roles.md) 단원을 참조하십시오.

또는 "kinesis-process-record" AWS Lambda 블루프린트를 사용하여 Kinesis 데이터 스트림의 메시지를 CloudWatch에 로깅하여 지속적으로 시각화할 수 있습니다. 이로 인해 AWS Lambda 및 CloudWatch에 대한 추가 비용이 발생합니다.

## 스트림 프로세서가 결과를 반환하지 않습니다
<a name="ts-streaming-video-no-results-from-sp"></a>

스트림 프로세서가 결과를 반환하지 않는 이유에는 몇 가지가 있을 수 있습니다.

### 이유 1: 스트림 프로세서가 올바로 구성되지 않은 경우
<a name="w2aac27c79c27c11b5"></a>

스트림 프로세서가 올바로 구성되지 않았을 수 있습니다. 자세한 내용은 [스트림 프로세서를 올바로 구성했는지 모르겠습니다](#ts-configured-sp) 단원을 참조하십시오.

### 이유 2: 스트림 프로세서 상태가 RUNNING이 아닌 경우
<a name="w2aac27c79c27c11b7"></a>

**스트림 프로세서 상태 문제를 해결하려면**

1. 다음 AWS CLI 명령을 사용하여 스트림 프로세서의 상태를 확인합니다.

   ```
   aws rekognition describe-stream-processor --name stream-processor-name
   ```

1. `Status` 값이 `STOPPED`라면 다음 명령을 사용하여 스트림 프로세서를 시작합니다.

   ```
   aws rekognition start-stream-processor --name stream-processor-name
   ```

1. `Status` 값이 `FAILED`라면 [스트림 프로세서의 상태가 FAILED입니다](#ts-failed-state) 단원을 참조하십시오.

1. `Status` 값이 `STARTING`이라면 2분 간 기다린 후 1단계를 반복하여 상태를 확인합니다. 상태 값이 여전히 `STARTING`이라면 다음을 수행합니다.

   1. 다음 명령을 사용하여 스트림 프로세서를 삭제합니다.

      ```
      aws rekognition delete-stream-processor --name stream-processor-name
      ```

   1. 동일한 구성의 새 스트림 프로세서를 생성합니다. 자세한 내용은 [스트리밍 비디오 이벤트 작업](streaming-video.md) 단원을 참조하십시오.

   1. 여전히 문제가 있는 경우 AWS Support에 문의하세요.

1. `Status` 값이 `RUNNING`라면 [원인 3: Kinesis 비디오 스트림에 활성 데이터가 없는 경우](#ts-no-data) 단원을 참조하십시오.

### 원인 3: Kinesis 비디오 스트림에 활성 데이터가 없는 경우
<a name="ts-no-data"></a>

**Kinesis 비디오 스트림에 활성 데이터가 있는지 확인하려면**

1. 에 로그인 AWS Management Console하고 [https://console.aws.amazon.com/kinesisvideo/](https://console.aws.amazon.com/kinesisvideo/) Amazon Kinesis Video Streams 콘솔을 엽니다.

1. Amazon Rekognition 스트림 프로세서에 입력되는 Kinesis 비디오 스트림을 선택합니다.

1. 미리 보기에 **No data on stream**이 표시되는 경우, Amazon Rekognition Video의 입력 스트림에 처리할 데이터가 없는 것입니다.

Kinesis Video Streams를 사용한 비디오 제작에 대한 자세한 내용은 [Kinesis Video Streams Producer 라이브러리](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html)를 참조하세요.

## 스트림 프로세서의 상태가 FAILED입니다
<a name="ts-failed-state"></a>

다음 AWS CLI 명령을 사용하여 스트림 프로세서의 상태를 확인할 수 있습니다.

```
aws rekognition describe-stream-processor --name stream-processor-name
```

상태 값이 FAILED인 경우, 다음 오류 메시지의 문제 해결 정보를 확인하십시오.

### 오류: "Access denied to Role"
<a name="w2aac27c79c27c13b9"></a>

스트림 프로세서가 사용하는 IAM 역할이 존재하지 않거나 Amazon Rekognition Video에 해당 역할을 맡을 권한이 없습니다.

**IAM 역할에 대한 액세스 문제를 해결하려면**

1. 에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) IAM 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **역할**을 선택하고 역할이 존재하는지 확인합니다.

1. 역할이 존재하는 경우, 역할에 *AmazonRekognitionServiceRole* 권한 정책이 있는지 확인합니다.

1. 역할이 존재하지 않거나 적절한 권한을 가지고 있지 않다면 [Amazon Rekognition Video에 리소스에 대한 액세스 권한 부여](api-streaming-video-roles.md) 단원을 참조하십시오.

1. 다음 AWS CLI 명령을 사용하여 스트림 프로세서를 시작합니다.

   ```
   aws rekognition start-stream-processor --name stream-processor-name
   ```

### 오류: "Kinesis Video에 대한 액세스 거부됨 *또는* Kinesis Data에 대한 액세스 거부됨"
<a name="w2aac27c79c27c13c11"></a>

해당 역할에 `GetMedia` 및 `GetDataEndpoint` Kinesis Video Streams API 작업에 대한 액세스 권한이 없습니다. `PutRecord` 및 `PutRecords` Kinesis Data Streams API 작업에 대한 액세스 권한도 없을 수 있습니다.

**API 권한 문제를 해결하려면**

1. 에 로그인 AWS Management Console 하고 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) IAM 콘솔을 엽니다.

1. 역할을 열고 다음 권한 정책이 연결되어 있는지 확인합니다.

1. 권한 중에 없는 것이 있다면 정책을 업데이트합니다. 자세한 내용은 [Amazon Rekognition Video에 리소스에 대한 액세스 권한 부여](api-streaming-video-roles.md) 단원을 참조하십시오.

### 오류: "Stream *input-video-stream-name* doesn't exist"
<a name="w2aac27c79c27c13c13"></a>

스트림 프로세서로 들어가는 Kinesis 비디오 스트림 입력이 존재하지 않거나 올바로 구성되지 않았습니다.

**Kinesis 비디오 스트림 문제를 해결하려면**

1. 다음 명령을 사용하여 스트림이 존재하는지 확인합니다.

   ```
   aws kinesisvideo list-streams
   ```

1. 스트림이 존재하는 경우, 다음을 확인합니다.
   + Amazon 리소스 이름(ARN)이 스트림 프로세서 입력 스트림의 ARN과 동일합니다.
   + Kinesis 비디오 스트림은 스트림 프로세서와 동일한 리전에 있어야 합니다.

   스트림 프로세서가 올바르게 구성되지 않은 경우 다음 AWS CLI 명령을 사용하여 삭제합니다.

   ```
   aws rekognition delete-stream-processor --name stream-processor-name
   ```

1. 의도한 Kinesis 비디오 스트림으로 새 스트림 프로세서를 생성합니다. 자세한 내용은 [Amazon Rekognition Video에 얼굴 검색 스트림 프로세서 생성](rekognition-video-stream-processor-search-faces.md#streaming-video-creating-stream-processor) 단원을 참조하십시오.

### 오류: "Collection not found"
<a name="w2aac27c79c27c13c15"></a>

스트림 프로세서가 얼굴 일치에 사용하는 Amazon Rekognition 컬렉션이 존재하지 않거나 잘못된 컬렉션이 사용되고 있습니다.

**모음을 확인하려면**

1. 다음 AWS CLI 명령을 사용하여 필요한 컬렉션이 존재하는지 확인합니다. 스트림 프로세서를 실행하는 AWS 리전`region`으로 변경합니다.

   ```
   aws rekognition list-collections --region region
   ```

   필요한 모음이 존재하지 않는 경우, 새 모음을 생성하고 얼굴 정보를 추가합니다. 자세한 내용은 [컬렉션에서 얼굴 검색](collections.md) 단원을 참조하십시오.

1. [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) 직접 호출에서 `CollectionId` 입력 파라미터의 값이 올바른지 확인합니다.

1. 다음 AWS CLI 명령을 사용하여 스트림 프로세서를 시작합니다.

   ```
   aws rekognition start-stream-processor --name stream-processor-name
   ```

### 오류: "Stream *output-kinesis-data-stream-name* under account *account-id* not found"
<a name="w2aac27c79c27c13c17"></a>

스트림 프로세서에서 사용하는 출력 Kinesis 데이터 스트림 AWS 계정 이에 없거나 스트림 프로세서와 동일한 AWS 리전에 없습니다.

**Kinesis 데이터 스트림 문제를 해결하려면**

1. 다음 AWS CLI 명령을 사용하여 Kinesis 데이터 스트림이 존재하는지 확인합니다. 스트림 프로세서를 사용하는 AWS 리전`region`으로 변경합니다.

   ```
   aws kinesis list-streams --region region
   ```

1. Kinesis 데이터 스트림이 존재하는 경우, Kinesis 데이터 스트림 이름이 스트림 프로세서가 사용하는 출력 스트림의 이름과 동일한지 확인합니다.

1. Kinesis 데이터 스트림이 없는 경우 다른 AWS 리전에 존재할 수 있습니다. Kinesis 데이터 스트림은 스트림 프로세서와 동일한 리전에 있어야 합니다.

1. 필요하다면 새 Kinesis 데이터 스트림을 만듭니다.

   1. 스트림 프로세서가 사용하는 이름과 동일한 이름으로 Kinesis 데이터 스트림을 생성합니다. 자세한 내용은 [ 1단계: 데이터 스트림 생성](https://docs.aws.amazon.com/streams/latest/dev/learning-kinesis-module-one-create-stream.html)을 참조하십시오.

   1. 다음 AWS CLI 명령을 사용하여 스트림 프로세서를 시작합니다.

      ```
      aws rekognition start-stream-processor --name stream-processor-name
      ```

## 스트림 프로세서가 예상 결과를 반환하지 않습니다
<a name="w2aac27c79c27c15"></a>

스트림 프로세서가 예상 얼굴 일치를 반환하지 않는 경우, 다음 정보를 사용하십시오.
+ [컬렉션에서 얼굴 검색](collections.md)
+ [카메라 설정 권장 사항(스트리밍 비디오)](recommendations-camera-streaming-video.md)