

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

# 在集合中搜尋人臉
<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/zh_tw/rekognition/latest/dg/images/uservectorsCollection.png)


**若要與個別臉部向量進行高準確度比對：**

![\[描述在集合中存放和搜尋臉部的圖表，列出 CreateCollection、IndexFaces、StartFaceSearch、CreateStreamProcessor、SearchFacesByImage 和 SearchFaces 等操作。\]](http://docs.aws.amazon.com/zh_tw/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 Resource Name (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)：將 1 至 100 個唯一人臉 ID 新增至使用者 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-100 之間，預設值為 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` 的相似性閾值輸入屬性，會根據匹配的人臉相似度來控制傳回結果的數量。`UserMatchThreshold` 作為 `SearchUsers` 和 `SearchUsersByImage`​ 的相似性閾值屬性，會根據匹配的使用者向量相似度來控制的傳回結果數量。臨界值屬性適 `SimilarityThreshold` 用於 `CompareFaces`。

含低於臨界值之 `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 持續監控一物件。

在所有情況下，應在具有其他強而有力的證據下檢視臉部比較配對，而不應將其做為採取行動的唯一決定因素。不過，如果將臉部比較用於非執法部門的案例 (例如，解除電話的鎖定或在進入安全、私有辦公室建築物時驗證員工的身分)，這些決策就不需要手動稽核，因為不會影響一個人的公民權利。

如果您打算針對涉及公共安全的使用案例使用臉部偵測或臉部比較系統，則應該採用先前提及的最佳實務。此外，您應該參考已發佈的資源，了解如何使用臉部比較。其中包括司法部司法援助局所提供的 [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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `create-collection` 輸出。

   將 `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 Resource Name (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 Resource Name (ARN) (`ResourceArn`) 和標籤 (`Tags`)。下列範例顯示如何結合標記。

------
#### [ 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 Resource Name，則可以使用該 `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` 操作。指定要移除的模型 (`ResourceArn`) 和標籤鍵 (`Tag-Keys`) 的 ARN。

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

使用您開發人員設定檔的名稱取代 `profile_name` 的值。

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

或者，您可以使用以下格式指定標籤鍵：

```
--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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `list-collections` 輸出。使用您開發人員設定檔的名稱取代 `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 Resource Name (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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `describe-collection` 輸出。將 `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 Resource Name，`CollectionARN`。
+ 集合的建立日期和時間，`CreationTimestamp`。`CreationTimestamp` 的值是 Unix epoch 時間到集合建立時所經的毫秒數。Unix epoch 時間為 1970 年 1 月 1 日周四 00:00:00 國際標準時間 (UTC)。如需詳細資訊，請參閱 [Unix 時間](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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `delete-collection` 輸出。將 `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 保留於人臉集合中的資訊外，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` 陣列包含為何無法為人臉建立索引的原因清單。例如，當值為 `EXCEEDS_MAX_FACES` 時，表示因為已偵測到透過 `MaxFaces` 指定的人臉數目，所以無法為人臉建立索引。

如需詳細資訊，請參閱 [管理集合中的人臉](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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `index-faces` 輸出。

   以您要儲存臉部的集合之名稱取代 `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 個特徵點)
+ 十個面部屬性 (眼鏡、鬍鬚、人臉遮挡、眼睛凝視方向等) 
+ 表情 (請參閱 `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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `list-faces` 輸出。將 `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 Face 也會透過人臉識別碼清單來篩選結果，並提供使用者 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 的資訊。如需詳細資訊，請參閱[人臉](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。如果要刪除多個人臉相符，可新增人臉 ID 至 `faces` 陣列。

   ```
   //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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `delete-faces` 輸出。將 `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。如果要刪除多個人臉相符，可新增人臉 ID 至 `faces` 陣列。將建立 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。如果要刪除多個臉部相符，可新增臉部 ID 至 `faces` 清單。

   ```
   //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 命令會使用 CLI `create-user` 操作建立使用者。

   ```
   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 命令會使用 CLI `create-user` 操作刪除使用者。

   ```
   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 命令會使用 CLI `associate-faces` 操作，將臉部與使用者建立關聯。

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

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

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

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

------

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

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

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

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

# 取消使用者人臉的關聯
<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 範例會移除 FaceID 和 UserID 與 `DisassociateFaces` 操作之間的關聯。

   ```
   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 ]

   下列範例會移除 FaceID 和 UserID 與 `DisassociateFaces` 操作之間的關聯。

   ```
   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 請求後，該操作可能需要一分鐘左右的時間才能完成。基於這個原因，UserStatus 會傳回，取值如下：
+ 已建立：表示「使用者」已成功建立，且目前沒有與其相關聯的任何人臉。在「AssociateFaces」的任何成功呼叫之前，「使用者」將處於此狀態。
+ 更新：表示「使用者」正在更新以反映新關聯/取消關聯的人臉，並在幾秒鐘內變為作用中狀態。此狀態下的搜尋結果可能包含「使用者」，客戶可以選擇從傳回的結果中忽略這些結果。
+ 作用中：表示****「使用者」****已更新，以反映所有關聯/已取消關聯的人臉，且處於可搜尋狀態。

```
{
    "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) 操作來列出 UserId 和 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` 清單，以及使用者的 `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) 操作來搜尋集合中符合指定映像中最大人臉的人臉。

當偵測到人臉並加入至集合時，人臉 ID 將隨 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 操作的回應一同回傳。如需詳細資訊，請參閱 [管理集合中的人臉](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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `search-faces` 輸出。以您想要搜尋的臉部識別碼來取代`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>

`SearchFaces` 將根據人臉 ID (每個儲存在人臉集合中的人臉都有人臉 ID) 在指定的人臉集合中搜尋相似的人臉。回應不包含您要搜尋的臉部。它只包含類似的臉部。在預設情況下，`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 文件開發套件範例 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 命令會顯示 CLI 操作的 JSON `search-faces-by-image` 輸出。以您在步驟 2 中所使用的 S3 儲存貯體來取代 `Bucket` 的值。以您在步驟 2 中所使用的映像檔案名稱來取代 `Name` 的值。以您要搜尋的集合名稱取代 `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)
<a name="search-users"></a>

您可以使用 [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html) 操作來搜尋集合中符合指定人臉 ID 的人臉。本操作會依據請求的 UserMatchThreshold 以上的最高相似性分數列出傳回的 `UserIds` 排名。使用者 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，則會依相似度分數最高到最低的順序列出這些 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` 進行搜尋，SearchUser 的回應包括適用於 `SearchedFace` 的 `FaceId`，以及每個使用者的 `UserMatches`、`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`，SearchUser 的回應除了其他回應單元之外，還包括適用於 `UserId` 的 `SearchedUser`。

```
{
    "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，則會依相似度分數最高到最低的順序列出這些 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`，以及適用於每個物件的 `UserId`、`Similarity` 和 `UserStatus` 的 UserMatches 清單。如果輸入映像包含多個人臉，則還將傳回 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 (Amazon SNS) 主题。如果影片分析成功，請呼叫 [GetFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GeFaceSearch.html) 以取得搜尋結果。如需開始影片分析並取得結果的詳細資訊，請參閱 [呼叫 Amazon Rekognition Video 操作](api-video.md)。

下列程序說明如何在集合中搜尋與影片中偵測到的人物相符之人臉。程序也將說明如何取得影片中相符人物的追蹤資料。此程序會展開 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](video-analyzing-with-sqs.md) 中的程式碼，該操作使用 Amazon Simple Queue Service (Amazon SQS) 佇列來取得影片分析要求的完成狀態。

**搜尋與臉部相符的影片 (開發套件)**

1. [建立集合](create-collection-procedure.md)。

1. [將臉部編入集合索引](add-faces-to-collection-procedure.md)。

1. 執行 [使用 Java 或 Python (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](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 文件開發套件範例 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 (SDK) 分析儲存於 Amazon S3 儲存貯體中的影片](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，您的應用程式需要實作下列專案：
+ Kinesis video stream，用於將串流影片傳送至 Amazon Rekognition Video。如需詳細資訊，請參閱 [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)。
+ Kinesis 資料串流消費者可讀取 Amazon Rekognition Video 傳送至 Kinesis 資料串流的分析結果。如需詳細資訊，請參閱 [Kinesis 資料串流消费者](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>

若要執行此程序，您需要 適用於 Java 的 AWS SDK 安裝 。如需詳細資訊，請參閱[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 開發套件)**

1. 如果您尚未建立 IAM 服務角色，請建立 IAM 服務角色，讓 Amazon Rekognition Video 有權存取您的 Kinesis 影片串流和 Kinesis 資料串流。請記下 ARN。如需詳細資訊，請參閱 [使用 AmazonRekognitionServiceRole 提供對串流的存取權](api-streaming-video-roles.md#api-streaming-video-roles-all-stream)。

1. [建立集合](create-collection-procedure.md)並記下您所使用的集合識別符。

1. [將您要搜尋之臉部的索引建立](add-faces-to-collection-procedure.md)至您於步驟 2 中建立的集合。

1. [建立 Kinesis 資料串流](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-createstream.html)，並記下串流的 Amazon Resource Name (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 至 10 秒，並包含一連串獨立的影片影格。Amazon Rekognition Video 支援 H.264 編碼影片，包含三種影格類型 (I、B 與 P)。如需詳細資訊，請參閱 [I 影格](https://en.wikipedia.org/wiki/Inter_frame)。片段中的第一個影格必須是 I 影格。I 影格可以與任何其他影格分開解碼。

當影片資料進入 Kinesis 影片串流時，會指派唯一號碼給片段。如需範例，請參閱 [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)，並使用下列政策。以所需的 Kinesis 影片串流 ARN 取代 `video-arn`。如果您使用的是人臉搜尋串流處理器，請以所需的 Kinesis 資料串流 ARN 取代 `data-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/zh_tw/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>

您可以透過呼叫 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html) 並提供您在 `CreateStreamProcessor` 中指定的串流處理器名稱，來開始分析串流影片。以下是 `StartStreamProcessor` 要求的 JSON 範例。

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

如果串流處理器成功啟動，就會傳回 HTTP 200 回應，以及空的 JSON 內文。

## 使用串流處理器進行人臉搜尋 (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 文件開發套件範例 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 Client Library 取用傳送至 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. 將 `FragmentTimeCodeType`PutMedia[ 操作的輸入參數 ](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) 設定為 `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` 物件時，請储存[承載](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` 是具有特定 `FragmentNumber` 之片段的位移，其會傳送至 Amazon Kinesis Data Streams。如需取得指定片段號碼之影片影格的詳細資訊，請參閱 [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 影片串流剖析程式庫
<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 影片串流和 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 (受信任)、PersonName2 (入侵)、PersonName3 (中立)等。這些標籤也可以進行顏色編碼，並且可以在 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 Resource Name (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-100) 。1 是最低的可信度，100 是最高的可信度。

類型：數字

**特徵點**

臉部特徵點的陣列。

類型：[特徵點](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Landmark.html)物件陣列

**姿態**

表示由俯仰、側傾與偏轉所決定的臉部姿態。

類型：[姿態](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) 物件中臉部相符之臉部的臉部配對資訊。

類型：[人臉](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Face.html)物件 

**相似度**

人臉相符的可信度 (1-100)。1 是最低的可信度，100 是最高的可信度。

類型：數字 

# 使用 GStreamer 外掛程式進行串流
<a name="streaming-using-gstreamer-plugin"></a>

Amazon Rekognition Video 可以分析來自裝置攝影機的即時串流影片。如要從裝置來源存取媒體輸入，您需要安裝 GStreamer。GStreamer 是第三方多媒體框架軟件，將媒體源和處理工具在工作流程管道中連接在一起。您還需要為 Gstreamer 安裝 [Amazon Kinesis Video Streams 生成器外掛程式](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。您可以使用軟件包管理軟件，例如自製軟件 ([自製軟件上的 Gstreamer](https://formulae.brew.sh/formula/gstreamer))，也可以直接從[免費桌面網站](https://gstreamer.freedesktop.org/download/)獲取。

 通過從命令行終端啟動帶有測試源的影片源來驗證 Gstreamer 是否成功安裝。

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

## 步驟 2：安裝 Kinesis Video Streams 製作外掛程式
<a name="step-2-install-kinesis-video-plugin"></a>

 在本節中，您將下載 [Amazon Kinesis Video Streams 生成器程式庫](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)來規劃和建置專案。請務必針對您的作業系統使用平台的特定指令。當您執行 `cmake` 以安裝 Kinesis Video Streams Gstreamer 外掛程式時，請使用此 `-DBUILD_GSTREAMER_PLUGIN=ON` 參數。此專案需要安裝中包含的下列額外套件：GCC 或 Clang、Curl、Openssl 和 Log4cplus。如果您的組建因為遺失套件而失敗，請確認套件已安裝且已安裝在 PATH 中。如果在構建時遇到「無法執行 C 編譯程序」錯誤，請再次執行構建命令。有時，找不到正確的 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：使用室壁執行影片流插件
<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 資訊。應該針對您建立的 IAM 服務角色使用存取金鑰和區域，同時[授予 Amazon Rekognition 存取 Kinesis 串流的權限](https://docs.aws.amazon.com/rekognition/latest/dg/api-streaming-video-roles.html#api-streaming-video-roles-all-stream)。如需有關存取金鑰的詳細資訊，請參閱《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)
+ [我的串流處理器狀態是失敗](#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`，請參閱[我的串流處理器狀態是失敗](#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 網站上的[解碼工具](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`，請參閱 [我的串流處理器狀態是失敗](#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 管理主控台，然後開啟位於 https：//[https://console.aws.amazon.com/kinesisvideo/](https://console.aws.amazon.com/kinesisvideo/) 的 Amazon Kinesis Video Streams 主控台。

1. 選取作為 Amazon Rekognition 串流處理器輸入的 Kinesis 影片串流。

1. 如果預覽顯示為**無串流資料**，則在輸入串流中沒有可供 Amazon Rekognition Video 處理的資料。

如需使用 Kinesis Video Streams 產生影片的資訊，請參閱 [Kinesis 影片串流生成器程式庫](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html)。

## 我的串流處理器狀態是失敗
<a name="ts-failed-state"></a>

您可以使用下列 AWS CLI 命令來檢查串流處理器的狀態。

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

如果狀態的值為失敗，請查看以下錯誤訊息的故障診斷資訊。

### 錯誤：「 角色存取遭拒」
<a name="w2aac27c79c27c13b9"></a>

由串流處理器使用的 IAM 角色不存在或 Amazon Rekognition Video 未具有擔任角色的許可。

**故障診斷 IAM 角色的存取**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在左側導覽窗格中，請選擇 **Roles (角色)** 並確認角色存在。

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>

該角色無法存取 API 操作 `GetMedia` 和 `GetDataEndpoint`。該角色可能也無法存取 Kinesis Data Streams API 操作 `PutRecord` 和 `PutRecords`。

**故障診斷 API 許可**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 開啟角色並確認角色已連接以下許可政策。

1. 如果遺失任何許可，請更新政策。如需詳細資訊，請參閱 [讓 Amazon Rekognition Video 有權存取您的資源](api-streaming-video-roles.md)。

### 錯誤：「串流 *input-video-stream-name* 不存在」
<a name="w2aac27c79c27c13c13"></a>

Kinesis 對串流處理器的影片串流輸入不存在或設定不正確。

**故障診斷 Kinesis 資料串流**

1. 使用以下命令確認串流存在。

   ```
   aws kinesisvideo list-streams
   ```

1. 如果串流存在，請檢查下列各項。
   + Amazon Resource Name (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)。

### 錯誤：「找不到集合」
<a name="w2aac27c79c27c13c15"></a>

串流處理器用於比對人臉的 Amazon Rekognition 集合不存在或使用了錯誤的集合。

**確認集合**

1. 使用下列 AWS CLI 命令來判斷所需的集合是否存在。`region` 變更為您正在執行串流處理器 AWS 的區域。

   ```
   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
   ```

### 錯誤：「找不到*帳戶 ID* 的串流 *output-kinesis-data-stream-name*」
<a name="w2aac27c79c27c13c17"></a>

串流處理器使用的輸出 Kinesis 資料串流不存在於 中， AWS 帳戶 或與您的串流處理器不在相同的 AWS 區域中。

**Kinesis 資料串流的故障診斷**

1. 使用下列 AWS CLI 命令來判斷 Kinesis 資料串流是否存在。`region` 變更為您使用串流處理器 AWS 的區域。

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