

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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


**为了与单个人脸向量进行高精度匹配：**

![\[该图描绘了在集合中存储和搜索人脸，列出了诸如 CreateCollection、、、 IndexFaces StartFaceSearch CreateStreamProcessor SearchFacesByImage、和 SearchFaces之类的操作。\]](http://docs.aws.amazon.com/zh_cn/rekognition/latest/dg/images/facevectorsCollection.png)


在许多情况下都可以使用集合。例如，您可以使用和`AssociateFaces`操作创建一个人脸集合，用于存储从扫描的员工徽章图像中检测到的人脸和 IDs 政府签发的人脸。`IndexFaces`当员工进入大楼时，将捕获员工的人脸图像，并将此图像发送到 `SearchUsersByImage` 操作。如果人脸匹配得到了足够高的相似度得分（例如 99%），则可对员工进行身份验证。

# 管理人脸集合、人脸和用户
<a name="managing-face-collections"></a>

 人脸集合是 Amazon Rekognition 用来包含与人脸和用户相关信息的资源。您可以使用各种 Rekognition API 操作来管理集合本身，以及存储在集合中的任何人脸或人脸向量。

## 管理集合
<a name="managing-collections"></a>

人脸集合是主要 Amazon Rekognition 资源，而您创建的每个人脸集合均具有一个唯一的 Amazon 资源名称 (ARN)。你可以在账户的特定 AWS 区域创建每个面孔集合。创建集合时，它会与人脸检测模型的最新版本关联。有关更多信息，请参阅 [了解模型版本控制](face-detection-model.md)。

您可以对集合执行以下管理操作：
+ 使用 [CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html) 创建集合。有关更多信息，请参阅 [创建集合](create-collection-procedure.md)。
+ 使用 [ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html) 列出可用的集合。有关更多信息，请参阅 [列出集合](list-collection-procedure.md)。
+ 使用 [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html) 描述集合。有关更多信息，请参阅 [描述集合](describe-collection-procedure.md)。
+ 使用 [DeleteCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteCollection.html) 删除集合。有关更多信息，请参阅 [删除集合](delete-collection-procedure.md)。

## 管理集合中的人脸
<a name="collections-index-faces"></a>

在创建人脸集合后，您可以将人脸存储到该集合中。Amazon Rekognition 提供以下操作来管理集合中的人脸：
+  [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 操作可检测输入图像 (JPEG 或 PNG) 中的人脸，并将这些人脸添加到指定的人脸集合。将为在图像中检测到的每个人脸返回一个唯一的人脸 ID。在保留人脸后，您可以在人脸集合中搜索匹配的人脸。有关更多信息，请参阅 [将人脸添加到集合](add-faces-to-collection-procedure.md)。
+ [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) 操作列出集合中的人脸。有关更多信息，请参阅 [将人脸添加到集合](add-faces-to-collection-procedure.md)。
+ [DeleteFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteFaces.html) 操作删除集合中的人脸。有关更多信息，请参阅 [从集合中删除人脸](delete-faces-procedure.md)。

## 在集合中管理用户
<a name="collections-manage-users"></a>

存储来自同一个人的多个人脸向量后，您可以通过将所有这些人脸向量关联到一个用户向量中来提高准确性。您可以使用以下操作来管理用户：
+ [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html)-Operation 使用提供的唯一用户 ID 在集合中创建新用户。
+ [AssociateUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateUsers.html)-在用户 ID 中添加 1-100 张唯一面孔 IDs 。将至少一个人脸 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)-移除用户的一张或 IDs 多张面孔。

# 使用相似度阈值关联和匹配人脸
<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[SearchFaces[SearchFacesByImage[SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html)](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html)](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html)](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CompareFaces.html)、、、、[SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html)）。

`FaceMatchThreshold` 是 `SearchFaces` 和 `SearchFacesByImage` 的相似性阈值输入属性，它根据与被匹配人脸的相似性来控制返回的结果数。`SearchUsers` 和 `SearchUsersByImage` 的相似性阈值属性是 `UserMatchThreshold`，它根据与被匹配用户向量的相似性来控制返回的结果数。阈值属性为 `CompareFaces` 的 `SimilarityThreshold`。

对于响应，如果其 `Similarity` 响应属性值低于阈值，则不返回。此阈值对于校准使用案例非常重要，因为它可以确定匹配结果中包含的误报数。此阈值控制搜索结果的查全率；该阈值越低，查全率越高。

所有机器学习系统是概率性的。您应根据自己的使用案例，判断如何设置合适的相似性阈值。例如，如果您打算生成一个照片应用来标识长相相似的家庭成员，则可选择较低的阈值（例如，80%）。另一方面，对于许多执法使用案例，我们建议您使用 99% 或更高的阈值来减少意外错误。

除了 `FaceMatchThreshold` 和 `UserMatchThreshold`，还可以使用 `Similarity` 响应属性来减少意外错误。例如，您可以选择使用较低的阈值（如 80%）以返回更多结果。然后，您可以使用响应属性相似性（相似性的百分比）来缩小选择范围以及在应用程序中筛选合适的响应。再次强调，使用越高的相似性（例如 99% 及以上）越能降低识别出错的风险。

# 常见场景中的人脸索引指南
<a name="guidance-index-faces"></a>

下面是在常见情景中使用 `IndexFaces` 的指南。

## 关键或公共安全应用
<a name="guidance-index-faces-critical"></a>
+ 使用仅包含每个图像中的一个人脸且将返回的人脸 ID 与图像主体的标识符关联的图像调用 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html)。
+ 您可以在索引之前使用 [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>

创建人脸集合并存储人脸矢量 and/or 用户向量后，可以在人脸集合中搜索面部匹配项。使用 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 持续监视人员。

在所有情况下，人脸比较匹配均应在其他有力证据的背景下考虑，而不应该用作采取行动的唯一决定因素。但是，如果在 non-law-enforcement场景中使用面部比较（例如，解锁手机或验证员工的身份以进入安全的私人办公楼），则这些决定不需要人工审计，因为它们不会影响个人的公民自由或同等人权。

如果您计划在涉及公共安全的使用案例中使用人脸检测或人脸比较系统，则应采用前面所述的最佳实践。此外，您还应参考已发布的关于人脸比较使用的资源。这包括司法部的司法援助局提供的[在刑事情报和调查活动中使用的人脸识别政策制定模板](https://www.bja.gov/Publications/Face-Recognition-Policy-Development-Template-508-compliant.pdf)。该模板提供了一些人脸比较和生物比较相关资源，旨在为执法和公共安全机构提供一个框架，用于制定符合适用法律的人脸比较政策、降低隐私风险和建立实体责任制和监督制。其他资源包括美国国家电信与信息管理局提供的[人脸识别商用最佳隐私实践](https://www.ntia.doc.gov/files/ntia/publications/privacy_best_practices_recommendations_for_commercial_use_of_facial_recogntion.pdf)和美国联邦贸易委员会工作人员提供的[人脸识别一般用途最佳实践](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)。

**创建集合 (开发工具包)**

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 资源名称 (ARN)。

   将 `collectionId` 的值更改为您要创建的集合的名称。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.CreateCollectionRequest;
   import com.amazonaws.services.rekognition.model.CreateCollectionResult;
   
   
   public class CreateCollection {
   
      public static void main(String[] args) throws Exception {
   
   
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         
         String collectionId = "MyCollection";
               System.out.println("Creating collection: " +
            collectionId );
               
           CreateCollectionRequest request = new CreateCollectionRequest()
                       .withCollectionId(collectionId);
              
         CreateCollectionResult createCollectionResult = rekognitionClient.createCollection(request); 
         System.out.println("CollectionArn : " +
            createCollectionResult.getCollectionArn());
         System.out.println("Status code : " +
            createCollectionResult.getStatusCode().toString());
   
      } 
   
   }
   ```

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java)查看完整示例。

    将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   //snippet-start:[rekognition.java2.create_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.CreateCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.CreateCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   //snippet-end:[rekognition.java2.create_collection.import]
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class CreateCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <collectionName> \n\n" +
            "Where:\n" +
            "   collectionName - The name of the collection. \n\n";
   
        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionId = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        System.out.println("Creating collection: " +collectionId);
        createMyCollection(rekClient, collectionId );
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.create_collection.main]
    public static void createMyCollection(RekognitionClient rekClient,String collectionId ) {
   
        try {
            CreateCollectionRequest collectionRequest = CreateCollectionRequest.builder()
                .collectionId(collectionId)
                .build();
   
            CreateCollectionResponse collectionResponse = rekClient.createCollection(collectionRequest);
            System.out.println("CollectionArn: " + collectionResponse.collectionArn());
            System.out.println("Status code: " + collectionResponse.statusCode().toString());
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.create_collection.main]
   ```

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

   此 AWS CLI 命令显示 `create-collection` CLI 操作的 JSON 输出。

   将 `collection-id` 的值替换为您要创建的集合的名称。

    将`profile_name`的值替换为您的开发人员资料的名称。

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

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

   以下示例创建一个集合，并显示其 Amazon 资源名称 (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 资源名称 (ARN)。

   将 `collectionId` 的值更改为您要创建的集合的名称。

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

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

   在以下示例中，将`region`的值替换为与您的账户关联的区域名称，并将 `collectionName` 的值替换为所需的集合名称。

    将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import { CreateCollectionCommand} from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const collectionName = "collection-name"
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   const createCollection = async (collectionName) => {
       try {
          console.log(`Creating collection: ${collectionName}`)
          const data = await rekogClient.send(new CreateCollectionCommand({CollectionId: collectionName}));
          console.log("Collection ARN:")
          console.log(data.CollectionARN)
          console.log("Status Code:")
          console.log(String(data.StatusCode))
          console.log("Success.",  data);
          return data;
       } catch (err) {
         console.log("Error", err.stack);
       }
     };
   
    createCollection(collectionName)
   ```

------

## CreateCollection 操作请求
<a name="createcollection-request"></a>

`CreationCollection` 的输入是您要创建的集合的名称。

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

## CreateCollection 操作响应
<a name="createcollection-operation-response"></a>

Amazon Rekognition 将创建集合，并返回最新创建的集合的 Amazon 资源名称 (ARN)。

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

# 标记集合
<a name="tag-collections"></a>

您可以使用标签识别、整理、搜索和筛选 Amazon Rekognition 集合。每个标签都是由用户定义的键和值组成的标签。

您还可以使用 Identity and Access Management (IAM) 使用标签控制集合的访问权限。有关更多信息，请参阅[使用 AWS 资源标签控制对资源的访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html)。

**Topics**
+ [向新集合添加标签](#add-tag-new-collection)
+ [向现有集合添加标签](#add-tag-existing-collection)
+ [列出集合中的标签](#list-tags-collection)
+ [从集合中删除标签](#delete-tag-collection)

## 向新集合添加标签
<a name="add-tag-new-collection"></a>

您可以使用 `CreateCollection` 操作在创建集合时向其添加标签。请在 `Tags` 数组输入参数中指定一个或多个标签。

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

 将`profile_name`的值替换为您的开发人员资料的名称。

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

对于 Windows 设备：

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

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

 将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

------

## 向现有集合添加标签
<a name="add-tag-existing-collection"></a>

要将一个或多个标签添加到现有集合，请使用 `TagResource` 操作。指定集合的 Amazon 资源名称（ARN）（`ResourceArn`）和要添加的标签（`Tags`）。以下示例说明了如何添加两个标签。

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

 将`profile_name`的值替换为您的开发人员资料的名称。

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

 对于 Windows 设备：

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

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

 将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

```
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

import boto3

def create_tag(collection_id):
    session = boto3.Session(profile_name='default')
    client = session.client('rekognition')
    response = client.tag_resource(ResourceArn=collection_id,
                                   Tags={
                                       "KeyName": "ValueName"
                                   })
    print(response)
    if "'HTTPStatusCode': 200" in str(response):
        print("Success!!")

def main():
    collection_arn = "collection-arn"
    create_tag(collection_arn)

if __name__ == "__main__":
    main()
```

------

**注意**  
如果您不知道该集合的 Amazon 资源名称，则可以使用 `DescribeCollection` 操作。

## 列出集合中的标签
<a name="list-tags-collection"></a>

要列出附加到集合的标签，请使用 `ListTagsForResource` 操作并指定该集合的 ARN（`ResourceArn`）。该操作的响应是附加到指定集合的标签键和值的映射图。

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

 将`profile_name`的值替换为您的开发人员资料的名称。

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

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

 将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

------

输出将显示附加到集合的标签列表：

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

## 从集合中删除标签
<a name="delete-tag-collection"></a>

要从集合中删除一个或多个标签，请使用 `UntagResource` 操作。指定模型的 ARN（`ResourceArn`）和要移除的标签键（`Tag-Keys`）。

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

将`profile_name`的值替换为您的开发人员资料的名称。

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

或者，您可以按以下格式指定标签键：

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

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

 将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

------

# 列出集合
<a name="list-collection-procedure"></a>

您可以使用 [ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html) 操作列出您正在使用的区域中的集合。

有关更多信息，请参阅 [管理集合](managing-face-collections.md#managing-collections)。



**列出集合 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `ListCollections` 操作。

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

   以下示例列出当前区域中的集合。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   
   import java.util.List;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.ListCollectionsRequest;
   import com.amazonaws.services.rekognition.model.ListCollectionsResult;
   
   public class ListCollections {
   
      public static void main(String[] args) throws Exception {
   
   
         AmazonRekognition amazonRekognition = AmazonRekognitionClientBuilder.defaultClient();
    
   
         System.out.println("Listing collections");
         int limit = 10;
         ListCollectionsResult listCollectionsResult = null;
         String paginationToken = null;
         do {
            if (listCollectionsResult != null) {
               paginationToken = listCollectionsResult.getNextToken();
            }
            ListCollectionsRequest listCollectionsRequest = new ListCollectionsRequest()
                    .withMaxResults(limit)
                    .withNextToken(paginationToken);
            listCollectionsResult=amazonRekognition.listCollections(listCollectionsRequest);
            
            List < String > collectionIds = listCollectionsResult.getCollectionIds();
            for (String resultId: collectionIds) {
               System.out.println(resultId);
            }
         } while (listCollectionsResult != null && listCollectionsResult.getNextToken() !=
            null);
        
      } 
   }
   ```

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/ListCollections.java)查看完整示例。

   ```
   //snippet-start:[rekognition.java2.list_collections.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.ListCollectionsRequest;
   import software.amazon.awssdk.services.rekognition.model.ListCollectionsResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   //snippet-end:[rekognition.java2.list_collections.import]
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class ListCollections {
   
    public static void main(String[] args) {
   
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        System.out.println("Listing collections");
        listAllCollections(rekClient);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.list_collections.main]
    public static void listAllCollections(RekognitionClient rekClient) {
        try {
            ListCollectionsRequest listCollectionsRequest = ListCollectionsRequest.builder()
                .maxResults(10)
                .build();
   
            ListCollectionsResponse response = rekClient.listCollections(listCollectionsRequest);
            List<String> collectionIds = response.collectionIds();
            for (String resultId : collectionIds) {
                System.out.println(resultId);
            }
   
        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.list_collections.main]
   }
   ```

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

   此 AWS CLI 命令显示 `list-collections` CLI 操作的 JSON 输出。将`profile_name`的值替换为您的开发人员资料的名称。

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

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

   以下示例列出当前区域中的集合。

    将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def list_collections():
   
       max_results=2
       
       client=boto3.client('rekognition')
   
       #Display all the collections
       print('Displaying collections...')
       response=client.list_collections(MaxResults=max_results)
       collection_count=0
       done=False
       
       while done==False:
           collections=response['CollectionIds']
   
           for collection in collections:
               print (collection)
               collection_count+=1
           if 'NextToken' in response:
               nextToken=response['NextToken']
               response=client.list_collections(NextToken=nextToken,MaxResults=max_results)
               
           else:
               done=True
   
       return collection_count   
   
   def main():
   
       collection_count=list_collections()
       print("collections: " + str(collection_count))
   if __name__ == "__main__":
       main()
   ```

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

   以下示例列出当前区域中的集合。

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

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

    将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import { ListCollectionsCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   const listCollection = async () => {
     var max_results = 10
     console.log("Displaying collections:")
     var response = await rekogClient.send(new ListCollectionsCommand({MaxResults: max_results}))
     var collection_count = 0
     var done = false
     while (done == false){
         var collections = response.CollectionIds
         collections.forEach(collection => {
             console.log(collection)
             collection_count += 1
         });
         return collection_count
     }
   }
   
   var collect_list = await listCollection()
   console.log(collect_list)
   ```

------

## ListCollections 操作请求
<a name="listcollections-request"></a>

`ListCollections` 的输入是要返回的集合的最大数量。

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

如果响应中包含的集合比 `MaxResults` 请求的人脸多，则会返回一个令牌，您可以使用此令牌在后续调用 `ListCollections` 时获得下一组结果。例如：

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

## ListCollections 操作响应
<a name="listcollections-operation-response"></a>

Amazon Rekognition 返回一系列集合（`CollectionIds`）。一个单独的数组 (`FaceModelVersions`) 提供用于分析每个集合中的人脸的人脸模型版本。例如，在下面的 JSON 响应中，集合 `MyCollection` 通过使用 2.0 版本的人脸模型来分析人脸。集合 `AnotherCollection` 使用 3.0 版本的人脸模型。有关更多信息，请参阅 [了解模型版本控制](face-detection-model.md)。

`NextToken` 是用于在后续调用 `ListCollections` 时获取下一组结果的令牌。

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

# 描述集合
<a name="describe-collection-procedure"></a>

您可以使用 [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html) 操作获取有关集合的下列信息：
+ 在集合中索引的人脸数量。
+ 与集合一起使用的模型版本。有关更多信息，请参阅 [了解模型版本控制](face-detection-model.md)。
+ 集合的 Amazon 资源名称 (ARN)。
+ 集合的创建日期和时间。

**描述集合 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `DescribeCollection` 操作。

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

   此示例描述集合。

   将值 `collectionId` 更改为所需集合的 ID。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package com.amazonaws.samples;
   
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.DescribeCollectionRequest;
   import com.amazonaws.services.rekognition.model.DescribeCollectionResult;
   
   
   public class DescribeCollection {
   
      public static void main(String[] args) throws Exception {
   
         String collectionId = "CollectionID";
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
               
         System.out.println("Describing collection: " +
            collectionId );
            
               
           DescribeCollectionRequest request = new DescribeCollectionRequest()
                       .withCollectionId(collectionId);
              
         DescribeCollectionResult describeCollectionResult = rekognitionClient.describeCollection(request); 
         System.out.println("Collection Arn : " +
            describeCollectionResult.getCollectionARN());
         System.out.println("Face count : " +
            describeCollectionResult.getFaceCount().toString());
         System.out.println("Face model version : " +
            describeCollectionResult.getFaceModelVersion());
         System.out.println("Created : " +
            describeCollectionResult.getCreationTimestamp().toString());
   
      } 
   
   }
   ```

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DescribeCollection.java)查看完整示例。

   ```
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DescribeCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.DescribeCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   //snippet-end:[rekognition.java2.describe_collection.import]
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class DescribeCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "   <collectionName>\n\n" +
            "Where:\n" +
            "   collectionName - The name of the Amazon Rekognition collection. \n\n";
   
        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionName = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        describeColl(rekClient, collectionName);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.describe_collection.main]
    public static void describeColl(RekognitionClient rekClient, String collectionName) {
   
        try {
            DescribeCollectionRequest describeCollectionRequest = DescribeCollectionRequest.builder()
                .collectionId(collectionName)
                .build();
   
            DescribeCollectionResponse describeCollectionResponse = rekClient.describeCollection(describeCollectionRequest);
            System.out.println("Collection Arn : " + describeCollectionResponse.collectionARN());
            System.out.println("Created : " + describeCollectionResponse.creationTimestamp().toString());
   
        } catch(RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.describe_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `describe-collection` CLI 操作的 JSON 输出。将 `collection-id` 的值更改为所需集合的 ID。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例描述集合。

   将值 `collection_id` 更改为所需集合的 ID。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   from botocore.exceptions import ClientError
   
   def describe_collection(collection_id):
   
       print('Attempting to describe collection ' + collection_id)
       
       session = boto3.Session(profile_name='default')
       client = session.client('rekognition')
       
       try:
       response = client.describe_collection(CollectionId=collection_id)
       print("Collection Arn: " + response['CollectionARN'])
       print("Face Count: " + str(response['FaceCount']))
       print("Face Model Version: " + response['FaceModelVersion'])
       print("Timestamp: " + str(response['CreationTimestamp']))
       
       except ClientError as e:
       if e.response['Error']['Code'] == 'ResourceNotFoundException':
       print('The collection ' + collection_id + ' was not found ')
       else:
       print('Error other than Not Found occurred: ' + e.response['Error']['Message'])
       print('Done...')
   
   def main():
       collection_id = 'collection-name'
       describe_collection(collection_id)
   
   if __name__ == "__main__":
       main()
   ```

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

   此示例描述集合。

   将值 `collectionId` 更改为所需集合的 ID。

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

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

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import { DescribeCollectionCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   // Name the collection
   const collection_name = "collection-name"
   
   const describeCollection = async (collectionName) => {
     try {
        console.log(`Attempting to describe collection named - ${collectionName}`)
        var response = await rekogClient.send(new DescribeCollectionCommand({CollectionId: collectionName}))
        console.log('Collection Arn:')
        console.log(response.CollectionARN)
        console.log('Face Count:')
        console.log(response.FaceCount)
        console.log('Face Model Version:')
        console.log(response.FaceModelVersion)
        console.log('Timestamp:')
        console.log(response.CreationTimestamp)
        return response; // For unit tests.
     } catch (err) {
       console.log("Error", err.stack);
     }
   };
   
   describeCollection(collection_name)
   ```

------

## DescribeCollection 操作请求
<a name="describe-collection-request"></a>

`DescribeCollection` 的输入是所需集合的 ID，如下面的 JSON 示例所示。

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

## DescribeCollection 操作响应
<a name="describe-collection-operation-response"></a>

响应包括以下内容：
+ 在集合中索引的人脸数量 `FaceCount`。
+ 与集合一起使用的人脸模型版本，`FaceModelVersion`。有关更多信息，请参阅 [了解模型版本控制](face-detection-model.md)。
+ 集合的 Amazon 资源名称 `CollectionARN`。
+ 集合的创建时间和日期 `CreationTimestamp`。`CreationTimestamp` 的值是自 Unix 纪元时间到集合创建时间的毫秒数。Unix 纪元时间是 1970 年 1 月 1 日星期四，协调世界时 (UTC) 00:00:00。有关更多信息，请参阅 [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 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteCollection.java)查看完整示例。

   ```
   // snippet-start:[rekognition.java2.delete_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DeleteCollectionRequest;
   import software.amazon.awssdk.services.rekognition.model.DeleteCollectionResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   // snippet-end:[rekognition.java2.delete_collection.import]
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class DeleteCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> \n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection to delete. \n\n";
   
           if (args.length != 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Deleting collection: " + collectionId);
           deleteMyCollection(rekClient, collectionId);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.delete_collection.main]
       public static void deleteMyCollection(RekognitionClient rekClient,String collectionId ) {
   
           try {
               DeleteCollectionRequest deleteCollectionRequest = DeleteCollectionRequest.builder()
                   .collectionId(collectionId)
                   .build();
   
               DeleteCollectionResponse deleteCollectionResponse = rekClient.deleteCollection(deleteCollectionRequest);
               System.out.println(collectionId + ": " + deleteCollectionResponse.statusCode().toString());
   
           } catch(RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.delete_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `delete-collection` CLI 操作的 JSON 输出。将 `collection-id` 的值替换为您要删除的集合的名称。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例删除集合。

   将 `collection_id` 的值更改为您要删除的集合。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   from botocore.exceptions import ClientError
   
   def delete_collection(collection_id):
   
       print('Attempting to delete collection ' + collection_id)
       session = boto3.Session(profile_name='default')
       client = session.client('rekognition')
   
       status_code = 0
   
       try:
           response = client.delete_collection(CollectionId=collection_id)
           status_code = response['StatusCode']
   
       except ClientError as e:
           if e.response['Error']['Code'] == 'ResourceNotFoundException':
               print('The collection ' + collection_id + ' was not found ')
           else:
               print('Error other than Not Found occurred: ' + e.response['Error']['Message'])
           status_code = e.response['ResponseMetadata']['HTTPStatusCode']
       return (status_code)
   
   def main():
   
       collection_id = 'collection-name'
       status_code = delete_collection(collection_id)
       print('Status code: ' + str(status_code))
   
   if __name__ == "__main__":
       main()
   ```

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

   此示例删除集合。

   将 `collectionId` 的值更改为您要删除的集合。

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

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

    将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import { DeleteCollectionCommand } from  "@aws-sdk/client-rekognition";
   import  { RekognitionClient } from "@aws-sdk/client-rekognition";
   import {fromIni} from '@aws-sdk/credential-providers';
   
   // Set the AWS Region.
   const REGION = "region-name"; //e.g. "us-east-1"
   // Set the profile name
   const profileName = "profile-name"
   // Name the collection
   const rekogClient = new RekognitionClient({region: REGION, 
     credentials: fromIni({profile: profileName,}), 
   });
   
   // Name the collection
   const collection_name = "collection-name"
   
   const deleteCollection = async (collectionName) => {
       try {
          console.log(`Attempting to delete collection named - ${collectionName}`)
          var response = await rekogClient.send(new DeleteCollectionCommand({CollectionId: collectionName}))
          var status_code = response.StatusCode
          if (status_code = 200){
              console.log("Collection successfully deleted.")
          }
          return response; // For unit tests.
       } catch (err) {
         console.log("Error", err.stack);
       }
     };
   
   deleteCollection(collection_name)
   ```

------

## DeleteCollection 操作请求
<a name="deletecollection-request"></a>

`DeleteCollection` 的输入是要删除的集合的 ID，如下面的 JSON 示例所示。

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

## DeleteCollection 操作响应
<a name="deletecollection-operation-response"></a>

`DeleteCollection` 响应包含 HTTP 状态代码，指示操作成功还是失败。如果成功删除了集合，则返回 `200`。

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

# 将人脸添加到集合
<a name="add-faces-to-collection-procedure"></a>

您可以使用 [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 操作检测图像中的人脸并将人脸添加到集合中。对于检测到的每张人脸，Amazon Rekognition 将提取人脸特征并将特征信息存储到数据库中。此外，该命令将检测到的每个人脸的元数据存储在指定的人脸集合中。Amazon Rekognition 不存储实际的图像字节。

有关提供合适的人脸用于编制索引的信息，请参阅[有关面部比较输入图像的建议](recommendations-facial-input-images.md)。

对于每个人脸，`IndexFaces` 操作保留以下信息：
+ **多维人脸特征** – `IndexFaces` 使用人脸分析来提取有关人脸特征的多维信息，并将该信息存储在人脸集合中。您无法直接访问此信息。不过，Amazon Rekognition 在人脸集合中搜索匹配的人脸时将使用此信息。

   
+ **元数据**-每张人脸的元数据包括边界框、由 Amazon Rekognition IDs 分配的置信度（边界框包含人脸）（人脸 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 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/AddFacesToCollection.java)查看完整示例。

   ```
   //snippet-start:[rekognition.java2.add_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.IndexFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.IndexFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.QualityFilter;
   import software.amazon.awssdk.services.rekognition.model.Attribute;
   import software.amazon.awssdk.services.rekognition.model.FaceRecord;
   import software.amazon.awssdk.services.rekognition.model.UnindexedFace;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.Reason;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   //snippet-end:[rekognition.java2.add_faces_collection.import]
   
   /**
   * Before running this Java V2 code example, set up your development environment, including your credentials.
   *
   * For more information, see the following documentation topic:
   *
   * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
   */
   public class AddFacesToCollection {
   
    public static void main(String[] args) {
   
        final String usage = "\n" +
            "Usage: " +
            "    <collectionId> <sourceImage>\n\n" +
            "Where:\n" +
            "    collectionName - The name of the collection.\n" +
            "    sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }
   
        String collectionId = args[0];
        String sourceImage = args[1];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
            .build();
   
        addToCollection(rekClient, collectionId, sourceImage);
        rekClient.close();
    }
   
    // snippet-start:[rekognition.java2.add_faces_collection.main]
    public static void addToCollection(RekognitionClient rekClient, String collectionId, String sourceImage) {
   
        try {
            InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
            Image souImage = Image.builder()
                .bytes(sourceBytes)
                .build();
   
            IndexFacesRequest facesRequest = IndexFacesRequest.builder()
                .collectionId(collectionId)
                .image(souImage)
                .maxFaces(1)
                .qualityFilter(QualityFilter.AUTO)
                .detectionAttributes(Attribute.DEFAULT)
                .build();
   
            IndexFacesResponse facesResponse = rekClient.indexFaces(facesRequest);
            System.out.println("Results for the image");
            System.out.println("\n Faces indexed:");
            List<FaceRecord> faceRecords = facesResponse.faceRecords();
            for (FaceRecord faceRecord : faceRecords) {
                System.out.println("  Face ID: " + faceRecord.face().faceId());
                System.out.println("  Location:" + faceRecord.faceDetail().boundingBox().toString());
            }
   
            List<UnindexedFace> unindexedFaces = facesResponse.unindexedFaces();
            System.out.println("Faces not indexed:");
            for (UnindexedFace unindexedFace : unindexedFaces) {
                System.out.println("  Location:" + unindexedFace.faceDetail().boundingBox().toString());
                System.out.println("  Reasons:");
                for (Reason reason : unindexedFace.reasons()) {
                    System.out.println("Reason:  " + reason);
                }
            }
   
        } catch (RekognitionException | FileNotFoundException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
    // snippet-end:[rekognition.java2.add_faces_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `index-faces` CLI 操作的 JSON 输出。

   将 `collection-id` 的值替换为您希望在其中存储人脸的集合的名称。将`Bucket`和`Name`的值替换为您在步骤 2 中使用的 Amazon S3 存储桶和图像文件。`max-faces` 参数将索引的人脸数限制为 1。删除或更改其值以满足您的需求。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

    如果您在 Windows 设备上访问 CLI，请使用双引号代替单引号，并用反斜杠（即 \$1）对内部双引号进行转义，以解决可能遇到的任何解析器错误。例如，请参阅以下内容：

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

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

   此示例显示添加到集合的人脸的人脸标识符。

   将 `collectionId` 的值更改为您要向其中添加人脸的集合的名称。将`bucket`和`photo`的值替换为您在步骤 2 中使用的 Amazon S3 存储桶和图像的名称。`MaxFaces` 输入参数将索引的人脸数限制为 1。删除或更改其值以满足您的需求。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def add_faces_to_collection(bucket, photo, collection_id):
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.index_faces(CollectionId=collection_id,
                                     Image={'S3Object': {'Bucket': bucket, 'Name': photo}},
                                     ExternalImageId=photo,
                                     MaxFaces=1,
                                     QualityFilter="AUTO",
                                     DetectionAttributes=['ALL'])
   
       print('Results for ' + photo)
       print('Faces indexed:')
       for faceRecord in response['FaceRecords']:
           print('  Face ID: ' + faceRecord['Face']['FaceId'])
           print('  Location: {}'.format(faceRecord['Face']['BoundingBox']))
   
       print('Faces not indexed:')
       for unindexedFace in response['UnindexedFaces']:
           print(' Location: {}'.format(unindexedFace['FaceDetail']['BoundingBox']))
           print(' Reasons:')
           for reason in unindexedFace['Reasons']:
               print('   ' + reason)
       return len(response['FaceRecords'])
   
   def main():
       bucket = 'amzn-s3-demo-bucket'
       collection_id = 'collection-id'
       photo = 'photo-name'
   
       indexed_faces_count = add_faces_to_collection(bucket, photo, collection_id)
       print("Faces indexed count: " + str(indexed_faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   此示例显示添加到集合的人脸的人脸标识符。

   将 `collectionId` 的值更改为您要向其中添加人脸的集合的名称。将`bucket`和`photo`的值替换为您在步骤 2 中使用的 Amazon S3 存储桶和图像的名称。

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

------

## IndexFaces 操作请求
<a name="indexfaces-request"></a>

`IndexFaces` 的输入是要编入索引的图像和要向其中添加人脸的集合。

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

## IndexFaces 操作响应
<a name="indexfaces-operation-response"></a>

`IndexFaces` 返回有关在图像中检测到的人脸的信息。例如，以下 JSON 响应包含在输入图像中检测到的人脸的默认检测属性。此示例还显示未为人脸编制索引，因为已超出 `MaxFaces` 输入参数的值，`Reasons` 数组包含 *EXCEEDS\$1MAX\$1FACES*。如果因质量原因而未为人脸编制索引，`Reasons` 将包含 *LOW\$1SHARPNESS* 或 *LOW\$1BRIGHTNESS* 等值。有关更多信息，请参阅 [UnindexedFace](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UnindexedFace.html)。

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

要获取所有面部信息，对于 `DetectionAttributes` 请求参数，请指定“ALL”。例如，在以下示例响应中，记住 `faceDetail` 元素中的其他信息，这些信息不会保留在服务器上：
+ 25 个人脸标记（相较于上一个示例中的仅 5 个人脸标记）
+ 十个人脸属性（眼镜、胡须、遮挡、视线方向等） 
+ 情绪（请参阅 `emotion` 元素）

`face` 元素提供了服务器上保留的元数据。

 `FaceModelVersion` 是与集合关联的人脸模型的版本。有关更多信息，请参阅 [了解模型版本控制](face-detection-model.md)。

`OrientationCorrection` 是估计的图像方向。如果您使用的是高于版本 3 的人脸检测模型版本，则不会返回方向校正信息。有关更多信息，请参阅 [获取图像方向和边界框坐标](images-orientation.md)。

以下示例响应显示了指定 ["ALL"] 时返回的 JSON：

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

# 列出集合中的人脸和相关用户
<a name="list-faces-in-collection-procedure"></a>

您可以使用该[ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html)操作在集合中列出面孔及其关联用户。

有关更多信息，请参阅 [管理集合中的人脸](managing-face-collections.md#collections-index-faces)。



**列出集合中的人脸 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `ListFaces` 操作。

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

   此示例显示了集合中的人脸列表。

   将 `collectionId` 的值更改为所需的集合。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.Face;
   import com.amazonaws.services.rekognition.model.ListFacesRequest;
   import com.amazonaws.services.rekognition.model.ListFacesResult;
   import java.util.List;
   import com.fasterxml.jackson.databind.ObjectMapper;
   
   
   
   public class ListFacesInCollection {
       public static final String collectionId = "MyCollection";
   
      public static void main(String[] args) throws Exception {
         
         AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
   
         ObjectMapper objectMapper = new ObjectMapper();
   
         ListFacesResult listFacesResult = null;
         System.out.println("Faces in collection " + collectionId);
   
         String paginationToken = null;
         do {
            if (listFacesResult != null) {
               paginationToken = listFacesResult.getNextToken();
            }
            
            ListFacesRequest listFacesRequest = new ListFacesRequest()
                    .withCollectionId(collectionId)
                    .withMaxResults(1)
                    .withNextToken(paginationToken);
           
            listFacesResult =  rekognitionClient.listFaces(listFacesRequest);
            List < Face > faces = listFacesResult.getFaces();
            for (Face face: faces) {
               System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                  .writeValueAsString(face));
            }
         } while (listFacesResult != null && listFacesResult.getNextToken() !=
            null);
      }
   
   }
   ```

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/ListFacesInCollection.java)查看完整示例。

   ```
   // snippet-start:[rekognition.java2.list_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.Face;
   import software.amazon.awssdk.services.rekognition.model.ListFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.ListFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   // snippet-end:[rekognition.java2.list_faces_collection.import]
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class ListFacesInCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId>\n\n" +
               "Where:\n" +
               "   collectionId - The name of the collection. \n\n";
   
           if (args.length < 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Faces in collection " + collectionId);
           listFacesCollection(rekClient, collectionId) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.list_faces_collection.main]
       public static void listFacesCollection(RekognitionClient rekClient, String collectionId ) {
           try {
               ListFacesRequest facesRequest = ListFacesRequest.builder()
                   .collectionId(collectionId)
                   .maxResults(10)
                   .build();
   
               ListFacesResponse facesResponse = rekClient.listFaces(facesRequest);
               List<Face> faces = facesResponse.faces();
               for (Face face: faces) {
                   System.out.println("Confidence level there is a face: "+face.confidence());
                   System.out.println("The face Id value is "+face.faceId());
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
            }
         }
       // snippet-end:[rekognition.java2.list_faces_collection.main]
     }
   ```

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

   此 AWS CLI 命令显示 `list-faces` CLI 操作的 JSON 输出。将 `collection-id` 的值替换为您要列出的集合的名称。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例显示了集合中的人脸列表。

   将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def list_faces_in_collection(collection_id):
       maxResults = 2
       faces_count = 0
       tokens = True
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
       response = client.list_faces(CollectionId=collection_id,
                                    MaxResults=maxResults)
   
       print('Faces in collection ' + collection_id)
   
       while tokens:
   
           faces = response['Faces']
   
           for face in faces:
               print(face)
               faces_count += 1
           if 'NextToken' in response:
               nextToken = response['NextToken']
               response = client.list_faces(CollectionId=collection_id,
                                            NextToken=nextToken, MaxResults=maxResults)
           else:
               tokens = False
       return faces_count
   
   def main():
       collection_id = 'collection-id'
       faces_count = list_faces_in_collection(collection_id)
       print("faces count: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   此示例显示了集合中的人脸列表。

   将 `collectionId` 的值更改为所需的集合。

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

------

## ListFaces 操作请求
<a name="listfaces-request"></a>

的输入`ListFaces`是您要为其列出面孔的集合的 ID。 `MaxResults`是要返回的最大面孔数。 ListFaces 还会接收 IDs 用于筛选结果的人脸列表，以及用于仅列出与给定用户关联的面孔的用户 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。要删除多张脸，请将该人脸 IDs 添加到`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 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/DeleteFacesFromCollection.java)查看完整示例。

   ```
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.DeleteFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   // snippet-end:[rekognition.java2.delete_faces_collection.import]
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class DeleteFacesFromCollection {
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <faceId> \n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection from which faces are deleted. \n\n" +
               "   faceId - The id of the face to delete. \n\n";
   
           if (args.length != 1) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String faceId = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Deleting collection: " + collectionId);
           deleteFacesCollection(rekClient, collectionId, faceId);
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.delete_faces_collection.main]
       public static void deleteFacesCollection(RekognitionClient rekClient,
                                                String collectionId,
                                                String faceId) {
   
           try {
               DeleteFacesRequest deleteFacesRequest = DeleteFacesRequest.builder()
                   .collectionId(collectionId)
                   .faceIds(faceId)
                   .build();
   
               rekClient.deleteFaces(deleteFacesRequest);
               System.out.println("The face was deleted from the collection.");
   
           } catch(RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.delete_faces_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `delete-faces` CLI 操作的 JSON 输出。将 `collection-id` 的值替换为您要删除的人脸所在集合的名称。将的`face-ids`值替换为要删除 IDs 的人脸数组。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例从集合中删除单个人脸。

   将 `collectionId` 的值更改为包含您要删除的人脸的集合。将 `faces` 的值更改为您要删除的人脸的 ID。要删除多张脸，请将该人脸 IDs 添加到`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。要删除多张面孔，请将该人脸 IDs 添加到`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，以及要删除的人脸 IDs 的数组。

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

## DeleteFaces 操作响应
<a name="deletefaces-operation-response"></a>

`DeleteFaces`响应包含已删除人脸 IDs 的面孔数组。

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

 如果输入中 IDs 提供的面孔当前与用户关联，则将以正当理由将其作为其中的 UnsuccessfulFaceDeletions 一部分返回。

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

# 创建用户
<a name="create-user"></a>

您可以使用该[CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html)操作使用您提供的唯一用户 ID 在集合中创建新用户。然后，您可以将多张人脸与新创建的用户相关联。

**创建用户 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新 IAM 用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `CreateUser` 操作。

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

   此 Java 代码示例创建了一名用户。

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

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

   此 AWS CLI 命令使用 `create-user` CLI 操作创建用户。

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

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

   此 Python 代码示例创建了一名用户。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   from botocore.exceptions import ClientError
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def create_user(collection_id, user_id):
       """
       Creates a new User within a collection specified by CollectionId. 
       Takes UserId as a parameter, which is a user provided ID which 
       should be unique within the collection.
   
       :param collection_id: The ID of the collection where the indexed faces will be stored at.
       :param user_id: ID for the UserID to be created. This ID needs to be unique within the collection.
       
       :return: The indexFaces response
       """
       try:
           logger.info(f'Creating user: {collection_id}, {user_id}')
           client.create_user(
               CollectionId=collection_id,
               UserId=user_id
           )
       except ClientError:
           logger.exception(f'Failed to create user with given user id: {user_id}')
           raise
   
   def main():
       collection_id = "collection-id"
       user_id = "user-id"
       create_user(collection_id, user_id)
   
   if __name__ == "__main__":
       main()
   ```

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

   此 Go 代码示例使用 AWS Go SDK V2 并创建了一个用户。

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

------

# 删除用户
<a name="delete-user"></a>

您可以使用该[DeleteUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteUser.html)操作根据提供的用户 ID 从集合中删除用户。请注意，在删除指定的用户 ID 之前，与该用户 ID 关联的所有人脸都将与用户 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. 使用以下示例调用 `DeleteUser` 操作。

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

   此 Java 代码示例删除了一名用户。

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

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

   此 AWS CLI 命令使用 `create-user` CLI 操作删除用户。

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

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

   此 Python 代码示例删除了一名用户。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   from botocore.exceptions import ClientError
   import logging
   
   logger = logging.getLogger(__name__)
   session = boto3.Session(profile_name='profile-name')
   client = session.client('rekognition')
   
   def delete_user(collection_id, user_id):
           """
           Delete the user from the given collection
   
           :param collection_id: The ID of the collection where user is stored.
           :param user_id: The ID of the user in the collection to delete.
           """
           logger.info(f'Deleting user: {collection_id}, {user_id}')
           try:
               client.delete_user(
                   CollectionId=collection_id,
                   UserId=user_id
               )
           except ClientError:
               logger.exception(f'Failed to delete user with given user id: {user_id}')
               raise
   
   def main():
       collection_id = "collection-id"
       user_id = "user-id"
       delete_user(collection_id, user_id)
   
   if __name__ == "__main__":
       main()
   ```

------

# 将人脸与用户关联
<a name="associate-faces"></a>

您可以使用该[AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociatingFaces.html)操作将多个单独的面孔与单个用户相关联。要将人脸与用户关联，必须先创建一个集合和一名用户。请注意，人脸向量必须位于用户向量所在的同一个集合中。

**关联人脸 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `AssociateFaces` 操作。

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

   此 Java 代码示例将人脸与用户关联起来。

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

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

   此 AWS CLI 命令使用 `associate-faces` CLI 操作将人脸与用户关联起来。

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

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

   此 Python 代码示例将人脸与用户关联起来。

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

------

## AssociateFaces 操作响应
<a name="associatefaces-operation-response"></a>

`AssociateFaces` 的响应包括 `UserStatus`（即解除关联请求的状态）以及要关联的 `FaceIds` 的列表。还会返回一个 `UnsuccessfulFaceAssociations` 列表。向 `AssociateFaces` 提交请求后，操作可能需要一分钟左右的时间才能完成。

因此，将返回 UserStatus ，其值可能如下所示：
+ CREATED - 表示“用户”已成功创建，并且当前没有人脸与之关联。在进行任何成功的 “” 呼叫之前，“用户AssociateFaces” 将处于此状态。
+ 更新-表示 “用户” 正在更新以反映新 associated/disassociated 面孔，并将在几秒钟后变为活动状态。搜索结果可能包含处于这种状态的“用户”，客户可以选择在返回的结果中忽略他们。
+ ACTIVE-表示 **“**用户**”** 已更新以反映所有 associated/disassociated 面孔并且处于可搜索状态。

```
{
    "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 和用户 ID 与 `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 和用户 ID 与`DisassociateFaces`操作之间的关联。

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

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

   以下示例删除了 FaceID 和用户 ID 与 `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 ，其值可能如下所示：
+ CREATED - 表示“用户”已成功创建，并且当前没有人脸与之关联。在进行任何成功的 “” 呼叫之前，“用户AssociateFaces” 将处于此状态。
+ 更新-表示 “用户” 正在更新以反映新 associated/disassociated 面孔，并将在几秒钟后变为活动状态。搜索结果可能包含处于这种状态的“用户”，客户可以选择在返回的结果中忽略他们。
+ ACTIVE-表示 **“**用户**”** 已更新以反映所有 associated/disassociated 面孔并且处于可搜索状态。

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

# 列出集合中的用户
<a name="list-users"></a>

您可以使用[ListUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListUsers.html)操作来列出 UserIds 和 UserStatus. 要查看与用户 ID 关联IDs 的面孔，请使用操作。[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)操作在集合中搜索与所提供图像中最大人脸相匹配的用户。

当检测到人脸并将人脸添加到集合时，[IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) 操作响应中将返回人脸 ID。有关更多信息，请参阅 [管理集合中的人脸](managing-face-collections.md#collections-index-faces)。



**使用人脸 ID 搜索集合中的相应人脸 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 使用以下示例调用 `SearchFaces` 操作。

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

   此示例显示与通过 ID 标识的人脸匹配的人脸的相关信息。

   将 `collectionID` 的值更改为包含所需人脸的集合。将 `faceId` 的值更改为您要查找的人脸的标识符。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.fasterxml.jackson.databind.ObjectMapper;
   import com.amazonaws.services.rekognition.model.FaceMatch;
   import com.amazonaws.services.rekognition.model.SearchFacesRequest;
   import com.amazonaws.services.rekognition.model.SearchFacesResult;
   import java.util.List;
   
   
     public class SearchFaceMatchingIdCollection {
         public static final String collectionId = "MyCollection";
         public static final String faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
         
       public static void main(String[] args) throws Exception {
           
           AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
         
           ObjectMapper objectMapper = new ObjectMapper();
         // Search collection for faces matching the face id.
         
         SearchFacesRequest searchFacesRequest = new SearchFacesRequest()
                 .withCollectionId(collectionId)
                 .withFaceId(faceId)
                 .withFaceMatchThreshold(70F)
                 .withMaxFaces(2);
              
          SearchFacesResult searchFacesByIdResult = 
                  rekognitionClient.searchFaces(searchFacesRequest);
   
          System.out.println("Face matching faceId " + faceId);
         List < FaceMatch > faceImageMatches = searchFacesByIdResult.getFaceMatches();
         for (FaceMatch face: faceImageMatches) {
            System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                    .writeValueAsString(face));
            
            System.out.println();
         }
       }
   
   }
   ```

   运行示例代码。将显示有关匹配的人脸的信息。

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingIdCollection.java)查看完整示例。

   ```
   // snippet-start:[rekognition.java2.match_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesRequest;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceMatch;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import java.util.List;
   // snippet-end:[rekognition.java2.match_faces_collection.import]
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class SearchFaceMatchingIdCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <sourceImage>\n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection.  \n" +
               "   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String faceId = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Searching for a face in a collections");
           searchFacebyId(rekClient, collectionId, faceId ) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.match_faces_collection.main]
       public static void searchFacebyId(RekognitionClient rekClient,String collectionId, String faceId) {
   
           try {
               SearchFacesRequest searchFacesRequest = SearchFacesRequest.builder()
                   .collectionId(collectionId)
                   .faceId(faceId)
                   .faceMatchThreshold(70F)
                   .maxFaces(2)
                   .build();
   
               SearchFacesResponse imageResponse = rekClient.searchFaces(searchFacesRequest) ;
               System.out.println("Faces matching in the collection");
               List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
               for (FaceMatch face: faceImageMatches) {
                   System.out.println("The similarity level is  "+face.similarity());
                   System.out.println();
               }
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.match_faces_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `search-faces` CLI 操作的 JSON 输出。将 `face-id` 的值替换为您要搜索的人脸标识符，并将 `collection-id` 的值替换为您要在其中执行搜索的集合。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例显示与通过 ID 标识的人脸匹配的人脸的相关信息。

   将 `collectionID` 的值更改为包含所需人脸的集合。将 `faceId` 的值更改为您要查找的人脸的标识符。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

   ```
   # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   import boto3
   
   def search_face_in_collection(face_id, collection_id):
       threshold = 90
       max_faces = 2
   
       session = boto3.Session(profile_name='profile-name')
       client = session.client('rekognition')
   
       response = client.search_faces(CollectionId=collection_id,
                                      FaceId=face_id,
                                      FaceMatchThreshold=threshold,
                                      MaxFaces=max_faces)
   
       face_matches = response['FaceMatches']
       print('Matching faces')
       for match in face_matches:
           print('FaceId:' + match['Face']['FaceId'])
           print('Similarity: ' + "{:.2f}".format(match['Similarity']) + "%")
   
       return len(face_matches)
   
   def main():
       face_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
       collection_id = 'collection-id'
   
       faces = []
       faces.append(face_id)
   
       faces_count = search_face_in_collection(face_id, collection_id)
       print("faces found: " + str(faces_count))
   
   if __name__ == "__main__":
       main()
   ```

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

   此示例显示与通过 ID 标识的人脸匹配的人脸的相关信息。

   将 `collectionID` 的值更改为包含所需人脸的集合。将 `faceId` 的值更改为您要查找的人脸的标识符。

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

   运行示例代码。将显示有关匹配的人脸的信息。

------

## SearchFaces 操作请求
<a name="searchfaces-operation-request"></a>

在给定人脸 ID（人脸集合中存储的每张人脸均有一个人脸 ID）的情况下，`SearchFaces` 将在指定人脸集合中搜索相似的人脸。该响应不包含您搜索的人脸。它仅包括相似的人脸。默认情况下，对于 `SearchFaces` 返回的人脸，算法检测到相似度得分高于 80%。相似度指示人脸与输入人脸的匹配程度。（可选）您可以使用 `FaceMatchThreshold` 指定不同的值。

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

## SearchFaces 操作响应
<a name="searchfaces-operation-response"></a>

此操作将返回一组找到的匹配人脸以及您作为输入提供的人脸 ID。

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

对于找到的每个匹配的人脸，此响应将包含相似度和人脸元数据，如以下示例响应所示：

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

# 使用图像搜索人脸
<a name="search-face-with-image-procedure"></a>

您可以使用 [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) 操作搜索集合中与所提供图像中最大的人脸匹配的人脸。

有关更多信息，请参阅 [搜索集合内的人脸和用户](collections-search-faces.md)。



**使用图像搜索集合中的人脸 (SDK)**

1. 如果您尚未执行以下操作，请：

   1. 使用 `AmazonRekognitionFullAccess` 和 `AmazonS3ReadOnlyAccess` 权限创建或更新用户。有关更多信息，请参阅 [步骤 1：设置 AWS 账户并创建用户](setting-up.md#setting-up-iam)。

   1. 安装并配置 AWS CLI 和 AWS SDKs。有关更多信息，请参阅 [第 2 步：设置 AWS CLI 和 AWS SDKs](setup-awscli-sdk.md)。

1. 将包含一张或多张人脸的图像上传到您的 S3 存储桶。

   有关说明，请参阅**《Amazon Simple Storage Service 用户指南》中的[将对象上传到 Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html)。

1. 使用以下示例调用 `SearchFacesByImage` 操作。

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

   此示例显示与图像中的最大人脸匹配的人脸的相关信息。此代码示例同时指定 `FaceMatchThreshold` 和 `MaxFaces` 参数以限制响应中返回的结果。

   在以下示例中，更改以下内容：将 `collectionId` 的值更改为您想要搜索的集合，将 `bucket` 的值更改为包含输入图像的存储桶，将 `photo` 的值更改为输入图像。

   ```
   //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
   package aws.example.rekognition.image;
   import com.amazonaws.services.rekognition.AmazonRekognition;
   import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder;
   import com.amazonaws.services.rekognition.model.FaceMatch;
   import com.amazonaws.services.rekognition.model.Image;
   import com.amazonaws.services.rekognition.model.S3Object;
   import com.amazonaws.services.rekognition.model.SearchFacesByImageRequest;
   import com.amazonaws.services.rekognition.model.SearchFacesByImageResult;
   import java.util.List;
   import com.fasterxml.jackson.databind.ObjectMapper;
   
   
   public class SearchFaceMatchingImageCollection {
       public static final String collectionId = "MyCollection";
       public static final String bucket = "bucket";
       public static final String photo = "input.jpg";
         
       public static void main(String[] args) throws Exception {
   
          AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient();
           
         ObjectMapper objectMapper = new ObjectMapper();
         
          // Get an image object from S3 bucket.
         Image image=new Image()
                 .withS3Object(new S3Object()
                         .withBucket(bucket)
                         .withName(photo));
         
         // Search collection for faces similar to the largest face in the image.
         SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest()
                 .withCollectionId(collectionId)
                 .withImage(image)
                 .withFaceMatchThreshold(70F)
                 .withMaxFaces(2);
              
          SearchFacesByImageResult searchFacesByImageResult = 
                  rekognitionClient.searchFacesByImage(searchFacesByImageRequest);
   
          System.out.println("Faces matching largest face in image from" + photo);
         List < FaceMatch > faceImageMatches = searchFacesByImageResult.getFaceMatches();
         for (FaceMatch face: faceImageMatches) {
             System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
                     .writeValueAsString(face));
            System.out.println();
         }
      }
   }
   ```

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/SearchFaceMatchingImageCollection.java)查看完整示例。

   ```
   // snippet-start:[rekognition.java2.search_faces_collection.import]
   import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
   import software.amazon.awssdk.core.SdkBytes;
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.RekognitionException;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageRequest;
   import software.amazon.awssdk.services.rekognition.model.Image;
   import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageResponse;
   import software.amazon.awssdk.services.rekognition.model.FaceMatch;
   import java.io.File;
   import java.io.FileInputStream;
   import java.io.FileNotFoundException;
   import java.io.InputStream;
   import java.util.List;
   // snippet-end:[rekognition.java2.search_faces_collection.import]
   
   /**
    * Before running this Java V2 code example, set up your development environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class SearchFaceMatchingImageCollection {
   
       public static void main(String[] args) {
   
           final String usage = "\n" +
               "Usage: " +
               "   <collectionId> <sourceImage>\n\n" +
               "Where:\n" +
               "   collectionId - The id of the collection.  \n" +
               "   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png). \n\n";
   
           if (args.length != 2) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String collectionId = args[0];
           String sourceImage = args[1];
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
               .region(region)
               .credentialsProvider(ProfileCredentialsProvider.create("profile-name"))
               .build();
   
           System.out.println("Searching for a face in a collections");
           searchFaceInCollection(rekClient, collectionId, sourceImage ) ;
           rekClient.close();
       }
   
       // snippet-start:[rekognition.java2.search_faces_collection.main]
       public static void searchFaceInCollection(RekognitionClient rekClient,String collectionId, String sourceImage) {
   
           try {
               InputStream sourceStream = new FileInputStream(new File(sourceImage));
               SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
               Image souImage = Image.builder()
                   .bytes(sourceBytes)
                   .build();
   
               SearchFacesByImageRequest facesByImageRequest = SearchFacesByImageRequest.builder()
                   .image(souImage)
                   .maxFaces(10)
                   .faceMatchThreshold(70F)
                   .collectionId(collectionId)
                   .build();
   
               SearchFacesByImageResponse imageResponse = rekClient.searchFacesByImage(facesByImageRequest) ;
               System.out.println("Faces matching in the collection");
               List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
               for (FaceMatch face: faceImageMatches) {
                   System.out.println("The similarity level is  "+face.similarity());
                   System.out.println();
               }
   
           } catch (RekognitionException | FileNotFoundException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
       // snippet-end:[rekognition.java2.search_faces_collection.main]
   }
   ```

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

   此 AWS CLI 命令显示 `search-faces-by-image` CLI 操作的 JSON 输出。将 `Bucket` 的值替换为您在步骤 2 中使用的 S3 存储桶。将 `Name` 的值替换为您在步骤 2 中使用的图像文件名。将 `collection-id` 的值替换为您要在其中执行搜索的集合。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

    如果您在 Windows 设备上访问 CLI，请使用双引号代替单引号，并用反斜杠（即 \$1）对内部双引号进行转义，以解决可能遇到的任何解析器错误。例如，请参阅以下内容：

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

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

   此示例显示与图像中的最大人脸匹配的人脸的相关信息。此代码示例同时指定 `FaceMatchThreshold` 和 `MaxFaces` 参数以限制响应中返回的结果。

   在以下示例中，更改以下内容：将 `collectionId` 的值更改为您想要搜索的集合，将`bucket`和`photo`的值分别替换为您在步骤 2 中使用的 Amazon S3 存储桶和图像的名称。将创建 Rekognition 会话的行中的`profile_name`值替换为您的开发人员资料的名称。

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

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

   此示例显示与图像中的最大人脸匹配的人脸的相关信息。此代码示例同时指定 `FaceMatchThreshold` 和 `MaxFaces` 参数以限制响应中返回的结果。

   在以下示例中，更改以下内容：将 `collectionId` 的值更改为您想要搜索的集合，将`bucket`和`photo`的值分别替换为您在步骤 2 中使用的 Amazon S3 存储桶和图像的名称。

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

------

## SearchFacesByImage 操作请求
<a name="searchfacesbyimage-operation-request"></a>

`SearchFacesImageByImage` 的输入参数是要在其中进行搜索的集合和源图像位置。在此示例中，源图像存储在 Amazon S3 存储桶（`S3Object`）中。另外还指定了要返回的人脸最大数量 (`Maxfaces`) 和要与返回的人脸匹配所必须达到的最低置信度 (`FaceMatchThreshold`)。

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

## SearchFacesByImage 操作响应
<a name="searchfacesbyimage-operation-response"></a>

在给定输入图像（.jpeg 或 .png）的情况下，此操作会先检测输入图像中的人脸，然后在指定的人脸集合中搜索相似的人脸。

**注意**  
如果服务在输入图像中检测到多个人脸，它会使用检测到的最大人脸来搜索人脸集合。

此操作将返回一组找到的匹配人脸以及有关输入人脸的信息。这包括如下信息：边界框以及置信度值，后者指示边界框包含人脸的置信度级别。

默认情况下，对于 `SearchFacesByImage` 返回的人脸，算法检测到相似度得分高于 80%。相似度指示人脸与输入人脸的匹配程度。（可选）您可以使用 `FaceMatchThreshold` 指定不同的值。对于找到的每个匹配的人脸，此响应将包含相似度和人脸元数据，如以下示例响应所示：

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

# 搜索用户（人脸 ID /用户 ID）
<a name="search-users"></a>

您可以使用该[SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html)操作在指定集合中搜索与提供的面容 ID 或用户 ID 相匹配的用户。该操作列出了按高于请求 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 或用户 ID SearchUsers ，在指定的 CollectionId 中搜索用户匹配项。默认情况下， SearchUsers 返回相似度分数大于 80% 的用户IDs 。相似度表示用户 ID 与提供的 FaceID 或用户 ID 的匹配程度。如果返回多个用户IDs ，则按相似度分数最高到最低的顺序列出。或者，您可以使用 UserMatchThreshold 来指定不同的值。有关更多信息，请参阅 [在集合中管理用户](managing-face-collections.md#collections-manage-users)。

以下是使用以下 SearchUsers 请求的示例`UserId`：

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

以下是使用以下 SearchUsers 请求的示例`FaceId`：

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

## SearchUsers 操作响应
<a name="search-users-response"></a>

如果使用 a 进行搜索`FaceId`，则对`FaceId`的响应将 SearchUsers `SearchedFace`包括每个用户的列表以及`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"
}
```

如果使用 a 进行搜索`UserId`，则除了其他响应元素外`SearchedUser`，的响应还 SearchUsers 包括对的。`UserId`

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

# 搜索用户（图像）
<a name="search-users-by-image"></a>

`SearchUsersByImage` 在指定集合 ID 中搜索与所提供图像中检测到的最大人脸相匹配的用户。默认情况下， SearchUsersByImage 返回相似度分数大于 80% 的用户IDs 。相似度表示用户 ID 与所提供图像中检测到的最大面孔的匹配程度。如果返回多个用户IDs ，则按相似度分数最高到最低的顺序列出。或者，您可以使用 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`包括一个对应的`FaceDetail`对象`SearchedFace`，以及每个对象 UserMatches 的列表，均`UserStatus`为`UserId``Similarity`、和。如果输入图像包含多张脸，则还 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 分析存储在 Amazon S3 存储桶中的视频 (SDK)](video-analyzing-with-sqs.md)（使用 Amazon Simple Queue Service (Amazon SQS) 队列获取视频分析请求的完成状态）中的代码的基础上进行了扩展。

**在视频中搜索匹配的人脸 (SDK)**

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

1. [将人脸索引到集合中](add-faces-to-collection-procedure.md)。

1. 执行[使用 Java 或 Python 分析存储在 Amazon S3 存储桶中的视频 (SDK)](video-analyzing-with-sqs.md)。

1. 将以下代码添加到您在步骤 3 中创建的类 `VideoDetect`。

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

   ```
      //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
      //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
          //Face collection search in video ==================================================================
          private static void StartFaceSearchCollection(String bucket, String video, String collection) throws Exception{
   
           NotificationChannel channel= new NotificationChannel()
                   .withSNSTopicArn(snsTopicArn)
                   .withRoleArn(roleArn);
   
           StartFaceSearchRequest req = new StartFaceSearchRequest()
                   .withCollectionId(collection)
                   .withVideo(new Video()
                           .withS3Object(new S3Object()
                                   .withBucket(bucket)
                                   .withName(video)))
                   .withNotificationChannel(channel);
   
   
   
           StartFaceSearchResult startPersonCollectionSearchResult = rek.startFaceSearch(req);
           startJobId=startPersonCollectionSearchResult.getJobId();
   
       } 
   
       //Face collection search in video ==================================================================
       private static void GetFaceSearchCollectionResults() throws Exception{
   
          GetFaceSearchResult faceSearchResult=null;
          int maxResults=10;
          String paginationToken=null;
   
          do {
   
              if (faceSearchResult !=null){
                  paginationToken = faceSearchResult.getNextToken();
              }
   
   
              faceSearchResult  = rek.getFaceSearch(
                      new GetFaceSearchRequest()
                      .withJobId(startJobId)
                      .withMaxResults(maxResults)
                      .withNextToken(paginationToken)
                      .withSortBy(FaceSearchSortBy.TIMESTAMP)
                      );
   
   
              VideoMetadata videoMetaData=faceSearchResult.getVideoMetadata();
   
              System.out.println("Format: " + videoMetaData.getFormat());
              System.out.println("Codec: " + videoMetaData.getCodec());
              System.out.println("Duration: " + videoMetaData.getDurationMillis());
              System.out.println("FrameRate: " + videoMetaData.getFrameRate());
              System.out.println();      
   
   
              //Show search results
              List<PersonMatch> matches= 
                      faceSearchResult.getPersons();
   
              for (PersonMatch match: matches) { 
                  long milliSeconds=match.getTimestamp();
                  System.out.print("Timestamp: " + Long.toString(milliSeconds));
                  System.out.println(" Person number: " + match.getPerson().getIndex());
                  List <FaceMatch> faceMatches = match.getFaceMatches();
                  if (faceMatches != null) {
                      System.out.println("Matches in collection...");
                      for (FaceMatch faceMatch: faceMatches){
                          Face face=faceMatch.getFace();
                          System.out.println("Face Id: "+ face.getFaceId());
                          System.out.println("Similarity: " + faceMatch.getSimilarity().toString());
                          System.out.println();
                      }
                  }
                  System.out.println();           
              } 
   
              System.out.println(); 
   
          } while (faceSearchResult !=null && faceSearchResult.getNextToken() != null);
   
      }
   ```

   在函数 `main` 中，将以下行: 

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

   替换为:

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

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

   此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/VideoDetectFaces.java)查看完整示例。

   ```
   import software.amazon.awssdk.regions.Region;
   import software.amazon.awssdk.services.rekognition.RekognitionClient;
   import software.amazon.awssdk.services.rekognition.model.*;
   import java.util.List;
   
   /**
    * Before running this Java V2 code example, set up your development
    * environment, including your credentials.
    *
    * For more information, see the following documentation topic:
    *
    * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
    */
   public class VideoDetectFaces {
       private static String startJobId = "";
   
       public static void main(String[] args) {
           final String usage = """
   
                   Usage:    <bucket> <video> <topicArn> <roleArn>
   
                   Where:
                      bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                      video - The name of video (for example, people.mp4).\s
                      topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                      roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                   """;
   
           if (args.length != 4) {
               System.out.println(usage);
               System.exit(1);
           }
   
           String bucket = args[0];
           String video = args[1];
           String topicArn = args[2];
           String roleArn = args[3];
   
           Region region = Region.US_EAST_1;
           RekognitionClient rekClient = RekognitionClient.builder()
                   .region(region)
                   .build();
   
           NotificationChannel channel = NotificationChannel.builder()
                   .snsTopicArn(topicArn)
                   .roleArn(roleArn)
                   .build();
   
           startFaceDetection(rekClient, channel, bucket, video);
           getFaceResults(rekClient);
           System.out.println("This example is done!");
           rekClient.close();
       }
   
       public static void startFaceDetection(RekognitionClient rekClient,
               NotificationChannel channel,
               String bucket,
               String video) {
           try {
               S3Object s3Obj = S3Object.builder()
                       .bucket(bucket)
                       .name(video)
                       .build();
   
               Video vidOb = Video.builder()
                       .s3Object(s3Obj)
                       .build();
   
               StartFaceDetectionRequest faceDetectionRequest = StartFaceDetectionRequest.builder()
                       .jobTag("Faces")
                       .faceAttributes(FaceAttributes.ALL)
                       .notificationChannel(channel)
                       .video(vidOb)
                       .build();
   
               StartFaceDetectionResponse startLabelDetectionResult = rekClient.startFaceDetection(faceDetectionRequest);
               startJobId = startLabelDetectionResult.jobId();
   
           } catch (RekognitionException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   
       public static void getFaceResults(RekognitionClient rekClient) {
           try {
               String paginationToken = null;
               GetFaceDetectionResponse faceDetectionResponse = null;
               boolean finished = false;
               String status;
               int yy = 0;
   
               do {
                   if (faceDetectionResponse != null)
                       paginationToken = faceDetectionResponse.nextToken();
   
                   GetFaceDetectionRequest recognitionRequest = GetFaceDetectionRequest.builder()
                           .jobId(startJobId)
                           .nextToken(paginationToken)
                           .maxResults(10)
                           .build();
   
                   // Wait until the job succeeds.
                   while (!finished) {
   
                       faceDetectionResponse = rekClient.getFaceDetection(recognitionRequest);
                       status = faceDetectionResponse.jobStatusAsString();
   
                       if (status.compareTo("SUCCEEDED") == 0)
                           finished = true;
                       else {
                           System.out.println(yy + " status is: " + status);
                           Thread.sleep(1000);
                       }
                       yy++;
                   }
   
                   finished = false;
   
                   // Proceed when the job is done - otherwise VideoMetadata is null.
                   VideoMetadata videoMetaData = faceDetectionResponse.videoMetadata();
                   System.out.println("Format: " + videoMetaData.format());
                   System.out.println("Codec: " + videoMetaData.codec());
                   System.out.println("Duration: " + videoMetaData.durationMillis());
                   System.out.println("FrameRate: " + videoMetaData.frameRate());
                   System.out.println("Job");
   
                   // Show face information.
                   List<FaceDetection> faces = faceDetectionResponse.faces();
                   for (FaceDetection face : faces) {
                       String age = face.face().ageRange().toString();
                       String smile = face.face().smile().toString();
                       System.out.println("The detected face is estimated to be"
                               + age + " years old.");
                       System.out.println("There is a smile : " + smile);
                   }
   
               } while (faceDetectionResponse != null && faceDetectionResponse.nextToken() != null);
   
           } catch (RekognitionException | InterruptedException e) {
               System.out.println(e.getMessage());
               System.exit(1);
           }
       }
   }
   ```

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

   ```
   #Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   #PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
   
       # ============== Face Search ===============
       def StartFaceSearchCollection(self,collection):
           response = self.rek.start_face_search(Video={'S3Object':{'Bucket':self.bucket,'Name':self.video}},
               CollectionId=collection,
               NotificationChannel={'RoleArn':self.roleArn, 'SNSTopicArn':self.snsTopicArn})
           
           self.startJobId=response['JobId']
           
           print('Start Job Id: ' + self.startJobId)
   
   
       def GetFaceSearchCollectionResults(self):
           maxResults = 10
           paginationToken = ''
   
           finished = False
   
           while finished == False:
               response = self.rek.get_face_search(JobId=self.startJobId,
                                           MaxResults=maxResults,
                                           NextToken=paginationToken)
   
               print(response['VideoMetadata']['Codec'])
               print(str(response['VideoMetadata']['DurationMillis']))
               print(response['VideoMetadata']['Format'])
               print(response['VideoMetadata']['FrameRate'])
   
               for personMatch in response['Persons']:
                   print('Person Index: ' + str(personMatch['Person']['Index']))
                   print('Timestamp: ' + str(personMatch['Timestamp']))
   
                   if ('FaceMatches' in personMatch):
                       for faceMatch in personMatch['FaceMatches']:
                           print('Face ID: ' + faceMatch['Face']['FaceId'])
                           print('Similarity: ' + str(faceMatch['Similarity']))
                   print()
               if 'NextToken' in response:
                   paginationToken = response['NextToken']
               else:
                   finished = True
               print()
   ```

   在函数 `main` 中，将以下行:

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

   替换为:

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

------

   如果您已经运行了除 [使用 Java 或 Python 分析存储在 Amazon S3 存储桶中的视频 (SDK)](video-analyzing-with-sqs.md) 之外的视频示例，则要替换的代码可能会有所不同。

1. 将 `collection` 的值更改为您在步骤 1 中创建的集合的名称。

1. 运行该代码。将显示视频中人脸与输入集合中的人脸匹配的人员的列表。还将显示每个匹配人员的跟踪数据。

## GetFaceSearch 操作响应
<a name="searchfacesvideo-operation-response"></a>

以下是来自 `GetFaceSearch` 的示例 JSON 响应。

该响应包括在视频中检测到的其人脸与输入集合中的人脸匹配的一组人员 (`Persons`)。每当在视频中匹配到该人员时，都会存在一个 [PersonMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonMatch.html) 对象。每个 `PersonMatch` 都包含输入集合中的人脸匹配的数组 [FaceMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceMatch.html)、有关匹配人员的信息 [PersonDetail](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonDetail.html) 以及在视频中匹配到人员的时间。

```
{
    "JobStatus": "SUCCEEDED",
    "NextToken": "IJdbzkZfvBRqj8GPV82BPiZKkLOGCqDIsNZG/gQsEE5faTVK9JHOz/xxxxxxxxxxxxxxx",
    "Persons": [
        {
            "FaceMatches": [
                {
                    "Face": {
                        "BoundingBox": {
                            "Height": 0.527472972869873,
                            "Left": 0.33530598878860474,
                            "Top": 0.2161169946193695,
                            "Width": 0.35503000020980835
                        },
                        "Confidence": 99.90239715576172,
                        "ExternalImageId": "image.PNG",
                        "FaceId": "a2f2e224-bfaa-456c-b360-7c00241e5e2d",
                        "ImageId": "eb57ed44-8d8d-5ec5-90b8-6d190daff4c3"
                    },
                    "Similarity": 98.40909576416016
                }
            ],
            "Person": {
                "BoundingBox": {
                    "Height": 0.8694444298744202,
                    "Left": 0.2473958283662796,
                    "Top": 0.10092592239379883,
                    "Width": 0.49427083134651184
                },
                "Face": {
                    "BoundingBox": {
                        "Height": 0.23000000417232513,
                        "Left": 0.42500001192092896,
                        "Top": 0.16333332657814026,
                        "Width": 0.12937499582767487
                    },
                    "Confidence": 99.97504425048828,
                    "Landmarks": [
                        {
                            "Type": "eyeLeft",
                            "X": 0.46415066719055176,
                            "Y": 0.2572723925113678
                        },
                        {
                            "Type": "eyeRight",
                            "X": 0.5068183541297913,
                            "Y": 0.23705792427062988
                        },
                        {
                            "Type": "nose",
                            "X": 0.49765899777412415,
                            "Y": 0.28383663296699524
                        },
                        {
                            "Type": "mouthLeft",
                            "X": 0.487221896648407,
                            "Y": 0.3452930748462677
                        },
                        {
                            "Type": "mouthRight",
                            "X": 0.5142884850502014,
                            "Y": 0.33167609572410583
                        }
                    ],
                    "Pose": {
                        "Pitch": 15.966927528381348,
                        "Roll": -15.547388076782227,
                        "Yaw": 11.34195613861084
                    },
                    "Quality": {
                        "Brightness": 44.80223083496094,
                        "Sharpness": 99.95819854736328
                    }
                },
                "Index": 0
            },
            "Timestamp": 0
        },
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.2177777737379074,
                    "Left": 0.7593749761581421,
                    "Top": 0.13333334028720856,
                    "Width": 0.12250000238418579
                },
                "Face": {
                    "BoundingBox": {
                        "Height": 0.2177777737379074,
                        "Left": 0.7593749761581421,
                        "Top": 0.13333334028720856,
                        "Width": 0.12250000238418579
                    },
                    "Confidence": 99.63436889648438,
                    "Landmarks": [
                        {
                            "Type": "eyeLeft",
                            "X": 0.8005779385566711,
                            "Y": 0.20915353298187256
                        },
                        {
                            "Type": "eyeRight",
                            "X": 0.8391435146331787,
                            "Y": 0.21049551665782928
                        },
                        {
                            "Type": "nose",
                            "X": 0.8191410899162292,
                            "Y": 0.2523227035999298
                        },
                        {
                            "Type": "mouthLeft",
                            "X": 0.8093273043632507,
                            "Y": 0.29053622484207153
                        },
                        {
                            "Type": "mouthRight",
                            "X": 0.8366993069648743,
                            "Y": 0.29101791977882385
                        }
                    ],
                    "Pose": {
                        "Pitch": 3.165884017944336,
                        "Roll": 1.4182015657424927,
                        "Yaw": -11.151537895202637
                    },
                    "Quality": {
                        "Brightness": 28.910892486572266,
                        "Sharpness": 97.61507415771484
                    }
                },
                "Index": 1
            },
            "Timestamp": 0
        },
        {
            "Person": {
                "BoundingBox": {
                    "Height": 0.8388888835906982,
                    "Left": 0,
                    "Top": 0.15833333134651184,
                    "Width": 0.2369791716337204
                },
                "Face": {
                    "BoundingBox": {
                        "Height": 0.20000000298023224,
                        "Left": 0.029999999329447746,
                        "Top": 0.2199999988079071,
                        "Width": 0.11249999701976776
                    },
                    "Confidence": 99.85971069335938,
                    "Landmarks": [
                        {
                            "Type": "eyeLeft",
                            "X": 0.06842322647571564,
                            "Y": 0.3010137975215912
                        },
                        {
                            "Type": "eyeRight",
                            "X": 0.10543643683195114,
                            "Y": 0.29697132110595703
                        },
                        {
                            "Type": "nose",
                            "X": 0.09569807350635529,
                            "Y": 0.33701086044311523
                        },
                        {
                            "Type": "mouthLeft",
                            "X": 0.0732642263174057,
                            "Y": 0.3757539987564087
                        },
                        {
                            "Type": "mouthRight",
                            "X": 0.10589495301246643,
                            "Y": 0.3722417950630188
                        }
                    ],
                    "Pose": {
                        "Pitch": -0.5589138865470886,
                        "Roll": -5.1093974113464355,
                        "Yaw": 18.69594955444336
                    },
                    "Quality": {
                        "Brightness": 43.052337646484375,
                        "Sharpness": 99.68138885498047
                    }
                },
                "Index": 2
            },
            "Timestamp": 0
        }......

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

# 在流视频中搜索集合中的人脸
<a name="collections-streaming"></a>

您可以使用 Amazon Rekognition Video 在流视频中检测和识别集合中的人脸。使用 Amazon Rekognition Video，你可以创建一个流处理器 [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)() 来启动和管理流媒体视频的分析。

为检测视频流中的已知人脸（人脸搜索），Amazon Rekognition Video 使用 Amazon Kinesis Video Streams 接收和处理视频流。分析结果将从 Amazon Rekognition Video 输出到 Kinesis 数据流，然后由您的客户端应用程序进行读取。

要将 Amazon Rekognition Video 与流视频结合使用，您的应用程序需要实施以下内容：
+ 用于向 Amazon Rekognition Video 发送流视频的 Kinesis 视频流。有关更多信息，请参阅 [Amazon Kinesis Video Streams 开发人员指南](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html)。
+ 一个 Amazon Rekognition Video 流处理器，用于管理对流视频的分析。有关更多信息，请参阅 [Amazon Rekognition Video 流处理器操作概述](streaming-video.md#using-rekognition-video-stream-processor)。
+ 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 账户 您使用的必须拥有亚马逊 Rekognition API 的访问权限。有关更多信息，请参阅 [IAM 用户指南](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions)中的 *Amazon Rekognition 定义的操作*。

**识别视频流中的人脸 (AWS SDK)**

1. 如果您还没有这样做，请创建一个 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 资源名称 (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）。有关更多信息，请参阅[帧间](https://en.wikipedia.org/wiki/Inter_frame)。版本中的第一个帧必须为 I 帧。I 帧可独立于任何其他帧进行解码。

当视频数据进入 Kinesis 视频流时，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) 服务角色向亚马逊 Rekognition Video 授予 Kinesis 视频流的读取权限。如果您使用的是人脸搜索流处理器，则可以使用 IAM 服务角色向 Amazon Rekognition Video 授予对 Kinesis 数据流的写入权限。如果您使用的是安全监控流处理器，则可以使用 IAM 角色授予 Amazon Rekognition Video 访问您的 Amazon S3 存储桶和 Amazon SNS 主题的权限。

## 为人脸搜索流处理器提供访问权限
<a name="api-streaming-video-roles-single-stream"></a>

您可以创建权限策略，允许 Amazon Rekognition Video 访问单个 Kinesis 视频流和 Kinesis 数据流。

**允许 Amazon Rekognition Video 访问人脸搜索流处理器**

1. [ 使用 IAM JSON 策略编辑器创建新的权限策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)，然后使用以下策略。将 `video-arn` 替换为所需的 Kinesis 视频流的 ARN。如果您使用的是人脸搜索流处理器，请将 `data-arn` 替换为所需的 Kinesis 数据流的 ARN。

1. [创建 IAM 服务角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console)，或者更新现有 IAM 服务角色。使用以下信息创建 IAM 服务角色：

   1. 对于服务名称，选择 **Rekognition**。

   1. 对于服务角色使用案例，选择 **Rekognition**。

   1. 附加您在步骤 1 中创建的权限策略。

1. 记下服务角色的 ARN。您需要它才能开始视频分析操作。

## 使用授予直播访问权限 AmazonRekognitionServiceRole
<a name="api-streaming-video-roles-all-stream"></a>

 作为设置 Kinesis 视频流和数据流访问权限的替代选项，您可以使用 `AmazonRekognitionServiceRole` 权限策略。IAM 提供 *Rekognition* 服务角色使用案例，当与 `AmazonRekognitionServiceRole` 权限策略结合使用时，该案例可以写入多个 Kinesis 数据流并从您的所有 Kinesis 数据流中进行读取。要向 Amazon Rekognition Video 授予对多个 Kinesis 数据流的写入权限，你可以在 Kinesis 数据流的名称前面加上——例如。*AmazonRekognition*`AmazonRekognitionMyDataStreamName`

**允许 Amazon Rekognition Video 访问您的 Kinesis 视频流和 Kinesis 数据流**

1. [创建 IAM 服务角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console)。使用以下信息创建 IAM 服务角色：

   1. 对于服务名称，选择 **Rekognition**。

   1. 对于服务角色使用案例，选择 **Rekognition**。

   1. 选择**AmazonRekognitionServiceRole**权限策略，该策略授予亚马逊 Rekognition Video 对以您的所有 Kinesis 视频流为前缀的 Kinesis 数据流的写入权限，*AmazonRekognition*以及对所有 Kinesis 视频流的读取权限。

1. 为确保您的安全，请将 Rekognition 的访问范围限制为仅限于您 AWS 账户 正在使用的资源。这可以通过将信任策略附加到您的 IAM 服务角色来完成。有关如何执行此操作的信息，请参阅 [防止跨服务混淆代理](cross-service-confused-deputy-prevention.md)。

1. 记下服务角色的 Amazon 资源名称 (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 视频流显示 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_cn/rekognition/latest/dg/images/VideoRekognitionStream.png)


## 创建 Amazon Rekognition Video 人脸搜索流处理器
<a name="streaming-video-creating-stream-processor"></a>

在分析流媒体视频之前，您需要先创建一个 Amazon Rekognition Video 流处理器 ()。[CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)流处理器包含有关 Kinesis 数据流和 Kinesis 视频流的信息。它还包含含有您要在输入流视频中识别的人脸的集合的标识符。您还可为流处理器指定名称。以下是 `CreateStreamProcessor` 请求的 JSON 示例。

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

以下是来自 `CreateStreamProcessor` 的示例响应。

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

## 启动 Amazon Rekognition Video 人脸搜索流处理器
<a name="streaming-video-starting-stream-processor"></a>

您可使用在 `CreateStreamProcessor` 中指定的流处理器名称来调用 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)，由此开始分析流视频。以下是 `StartStreamProcessor` 请求的 JSON 示例。

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

如果流处理器成功启动，则会返回 HTTP 200 响应以及空白的 JSON 正文。

## 使用流处理器搜索人脸（Java V2 示例）
<a name="using-stream-processors-v2"></a>

以下示例代码展示了如何使用适用于 Java 的 AWS SDK 版本 2 调用各种流处理器操作 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)，例如[CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)和。

此代码取自 AWS 文档 SDK 示例 GitHub 存储库。请在[此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateStreamProcessor.java)查看完整示例。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

## 使用流处理器搜索人脸（Java V1 示例）
<a name="using-stream-processors"></a>

以下示例代码显示如何使用 Java V1 调用各种流处理器操作 [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html)，例如[CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)和。该示例包括一个流处理器管理器类 (StreamManager)，该类提供调用流处理器操作的方法。入门类（Starter）创建一个 StreamManager 对象并调用各种操作。

**配置示例:**

1. 将 Starter 类成员字段的值设置为所需值。

1. 在 Starter 类函数 `main` 中，取消注释所需的函数调用。

### Starter 类
<a name="streaming-started"></a>

```
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

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

public class Starter {

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

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

### StreamManager 班级
<a name="streaming-manager"></a>

```
//Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)

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

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

public class StreamManager {

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

    private AmazonRekognition rekognitionClient;
    

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

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

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

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

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

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

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

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

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

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

# 读取流视频分析结果
<a name="streaming-video-kinesis-output"></a>

您可使用 Amazon Kinesis Data Streams 客户端库来使用已发送到 Amazon Kinesis Data Streams 输出流的分析结果。有关更多信息，请参阅[从 Kinesis 数据流读取数据](https://docs.aws.amazon.com/streams/latest/dev/building-consumers.html)。Amazon Rekognition Video 将每个分析过的帧的 JSON 帧记录放入 Kinesis 输出流。Amazon Rekognition Video 不会分析通过 Kinesis 视频流传递给它的每一帧。

已发送到 Kinesis 数据流的帧记录包含以下信息：该帧位于哪个 Kinesis 视频流片段中、该帧位于片段中的哪个位置以及在该帧中识别的人脸。它还包含流处理器的状态信息。有关更多信息，请参阅 [了解 Kinesis 人脸识别 JSON 帧记录](streaming-video-kinesis-output-reference.md)。

Amazon Kinesis Video Streams 解析器库包含使用 Amazon Rekognition Video 结果并将其与原始 Kinesis 视频流集成的示例测试。有关更多信息，请参阅 [在本地使用 Kinesis 视频流显示 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**— 有关用于将视频流式传输到亚马逊 Rekognition Video 的 Kinesis 视频流的信息。有关更多信息，请参阅 [InputInformation](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-inputinformation)。
+ **StreamProcessorInformation**— 亚马逊 Rekognition Video 流处理器的状态信息。`Status` 字段的唯一可能值为 RUNNING。有关更多信息，请参阅 [StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md)。
+ **FaceSearchResponse**— 包含有关流视频中与输入集合中的人脸匹配的人脸的信息。 [FaceSearchResponse](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facesearchresponse)包含一个[DetectedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-detectedface)对象，即在分析的视频帧中检测到的人脸。对于每个检测到的人脸，数组 `MatchedFaces` 包含一组在输入集合中找到的匹配的人脸对象 ([MatchedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facematch)) 以及一个相似度得分。

## 将 Kinesis 视频流映射到 Kinesis 数据流
<a name="mapping-streams"></a>

您可能希望将 Kinesis 视频流帧映射到发送至 Kinesis 数据流的分析帧。例如，在流视频显示期间，您可能希望在识别出的人脸周围显示方框。边界框的坐标将作为 Kinesis 人脸识别记录的一部分发送给 Kinesis 数据流。为了正确显示边界框，您需要将随 Kinesis 人脸识别记录发送的时间信息映射到源 Kinesis 视频流中相应的帧。

将 Kinesis 视频流映射到 Kinesis 数据流所用的方法取决于流式处理的是实时媒体（如实时流视频）还是存档媒体（如存储的视频）。

### 流式处理实时媒体时的映射
<a name="mapping-streaming-video"></a>

**将 Kinesis 视频流帧映射到 Kinesis 数据流帧中**

1. 将[PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html)操作`FragmentTimeCodeType`的输入参数设置为`RELATIVE`。

1. 调用 `PutMedia` 将实时媒体传输到 Kinesis 视频流中。

1. 如果从 Kinesis 数据流接收 Kinesis 人脸识别记录，请存储 [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) 字段的 `ProducerTimestamp` 和 `FrameOffsetInSeconds` 值。

1. 同时添加 `ProducerTimestamp` 和 `FrameOffsetInSeconds` 字段值，计算与 Kinesis 视频流帧对应的时间戳。

### 流式处理存档媒体时的映射
<a name="map-stored-video"></a>

**将 Kinesis 视频流帧映射到 Kinesis 数据流帧中**

1. 致电[PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html)将存档的媒体传输到 Kinesis 视频流中。

1. 如果您从 `PutMedia` 操作的响应中接收到 `Acknowledgement` 对象，请存储 [Payload](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html#API_dataplane_PutMedia_ResponseSyntax) 字段的 `FragmentNumber` 字段值。`FragmentNumber` 是 MKV 集群的片段编号。

1. 如果从 Kinesis 数据流接收 Kinesis 人脸识别记录，请存储 [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) 字段的 `FrameOffsetInSeconds` 字段值。

1. 使用步骤 2 和步骤 3 中存储的 `FrameOffsetInSeconds` 和 `FragmentNumber` 值计算映射。`FrameOffsetInSeconds` 是发送至 Amazon Kinesis Data Streams 的具有特定 `FragmentNumber` 的片段中的偏移。有关获取已知片段编号的视频帧的更多信息，请参阅 [Amazon Kinesis Video Streams 存档媒体](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_Operations_Amazon_Kinesis_Video_Streams_Archived_Media.html)。

# 在本地使用 Kinesis 视频流显示 Rekognition 结果
<a name="displaying-rekognition-results-locally"></a>

 [你可以使用亚马逊 Kinesis Video Streams 解析器库的示例测试，查看亚马逊 Rekognition Video Streams 的结果显示在你来自亚马逊 Kinesis Video Streams 的提要中。KinesisVideo ](https://github.com/aws/amazon-kinesis-video-streams-parser-library#kinesisvideo---rekognition-examples)在检测到的人脸上方`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 视频流和 Rekognition 集成示例测试
<a name="step-3-run-kinesis-video-rekognition-example-test"></a>

 如果您正在向其进行流式传输，请确保您的 Kinesis 视频流正在接收媒体输入，然后在运行 Amazon Rekognition Video 流处理器的情况下开始分析您的流。有关更多信息，请参阅 [Amazon Rekognition Video 流处理器操作概述](streaming-video.md#using-rekognition-video-stream-processor)。将`KinesisVideoRekognitionIntegrationExampleTest`课程当作 JUnit测试来运行。短暂延迟后，将打开一个新窗口，其中包含来自您的 Kinesis 视频流的视频源，以及在检测到的人脸上绘制的边界框。

**注意**  
 本示例中使用的集合中的人脸必须以这种格式指定外部图像 ID（文件名），边界框标签才能显示有意义的文本： PersonName1-Trusted、 PersonName 2-Intruder、 PersonName 3-Neutral 等。标签也可以采用颜色编码，并且可以在 FaceType .java 文件中进行自定义。

# 了解 Kinesis 人脸识别 JSON 帧记录
<a name="streaming-video-kinesis-output-reference"></a>

您可以使用 Amazon Rekognition Video 来识别流视频中的人脸。对于每个分析过的帧，Amazon Rekognition Video 会将 JSON 帧记录输出到 Kinesis 数据流中。Amazon Rekognition Video 不会分析通过 Kinesis 视频流传递给它的每一帧。

JSON 帧记录包含以下信息：输入和输出流、流处理器的状态以及在分析过的帧中识别的人脸。本节包含 JSON 帧记录的参考信息。

以下是 Kinesis 数据流记录的 JSON 语法。有关更多信息，请参阅 [使用流视频事件](streaming-video.md)。

**注意**  
Amazon Rekognition Video API 的工作原理是将输入流中的人脸与人脸集合进行比较，并返回找到的最接近的匹配项以及相似度分数。

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

## JSON 记录
<a name="streaming-video-kinesis-output-reference-processorresult"></a>

JSON 记录包含有关由 Amazon Rekognition Video 处理的帧的信息。该记录包含有关流视频的信息、分析过的帧的状态信息以及有关在该帧中识别的人脸的信息。

**InputInformation**

有关用于将视频流式传输到 Amazon Rekognition Video 的 Kinesis 视频流的信息。

类型：[InputInformation](#streaming-video-kinesis-output-reference-inputinformation) 对象

**StreamProcessorInformation**

有关 Amazon Rekognition Video 流处理器的信息。这包括流处理器的当前状态的状态信息。

类型：[StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md) 对象 

**FaceSearchResponse**

有关在流视频帧中检测到的人脸与在输入集合中找到的匹配人脸的信息。

类型：[FaceSearchResponse](#streaming-video-kinesis-output-reference-facesearchresponse) 对象数组

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

有关 Amazon Rekognition Video 使用的源视频流的信息。有关更多信息，请参阅 [使用流视频事件](streaming-video.md)。

**KinesisVideo**

类型：[KinesisVideo](#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) 对象

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

有关将源视频流式传输到 Amazon Rekognition Video 的 Kinesis 视频流的信息。有关更多信息，请参阅 [使用流视频事件](streaming-video.md)。

**StreamArn**

Kinesis 数据流的 Amazon 资源名称 (ARN)。

类型：字符串 

**FragmentNumber**

一个流视频的片断，包含此记录表示的帧。

类型：字符串

**ProducerTimestamp**

片段的生成者端 Unix 时间戳。有关更多信息，请参阅 [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html)。

类型：数字

**ServerTimestamp**

片段的服务器端 Unix 时间戳。有关更多信息，请参阅 [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html)。

类型：数字

**FrameOffsetInSeconds**

片段内的帧的偏移量（以秒为单位）。

类型：数字 

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

有关流处理器的状态信息。

**状态**

流处理器的当前状态。一个可能的值为 RUNNING。

类型：字符串

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

有关在流视频帧中检测到的人脸与集合中的与检测到的人脸匹配的人脸的信息。您可在调用 [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) 时指定集合。有关更多信息，请参阅 [使用流视频事件](streaming-video.md)。

**DetectedFace**

在分析的视频帧中检测到的人脸的人脸详细信息。

类型：[DetectedFace](#streaming-video-kinesis-output-reference-detectedface) 对象

**MatchedFaces**

集合中的人脸的人脸详细信息数组，该集合与在 `DetectedFace` 中检测到的人脸匹配。

类型：[MatchedFace](#streaming-video-kinesis-output-reference-facematch) 对象数组

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

有关在流视频帧中检测到的人脸的信息。[MatchedFace](#streaming-video-kinesis-output-reference-facematch) 对象字段中提供了输入集合中的匹配人脸。

**BoundingBox**

在分析过的视频帧内检测到的人脸的边界框坐标。该 BoundingBox 对象与用于图像分析的 BoundingBox 对象具有相同的属性。

类型：[BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html) 对象 

置信度

Amazon Rekognition Video 对检测到的人脸是否真的是人脸的置信度 (1-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 Producer 插件](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/)。此过程假设您已成功设置 Amazon Rekognition Video 和 Amazon Kinesis 资源。有关更多信息，请参阅 [设置您的 Amazon Rekognition Video 和 Amazon Kinesis 资源](setting-up-your-amazon-rekognition-streaming-video-resources.md)。

## 步骤 1：安装 Gstreamer
<a name="step-1-install-gstreamer"></a>

 下载并安装第三方多媒体平台软件 Gstreamer。您可以使用 Homebrew（[Homebrew 上的 Gstreamer](https://formulae.brew.sh/formula/gstreamer)）等软件包管理软件，或直接从 [Freedesktop 网站](https://gstreamer.freedesktop.org/download/)获取。

 通过从命令行终端启动带有测试源的视频源，验证 Gstreamer 的安装是否成功。

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

## 步骤 2：安装 Kinesis Video Streams Producer 插件
<a name="step-2-install-kinesis-video-plugin"></a>

 在本节中，您将下载 [Amazon Kinesis Video Streams Producer Library](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：使用 Kinesis Video Streams 插件运行 Gstreamer
<a name="step-3-run-gstreamer-with-kinesis-video-plugin"></a>

 在开始从设备摄像头流式传输到 Kinesis 视频流之前，可能需要将媒体源转换为 Kinesis 视频流可接受的编解码器。要确定当前已连接到您的计算机的设备的规格和格式功能，请运行以下命令。

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

 要开始流式传输，请使用以下示例命令启动 Gstreamer，并添加您的凭证和 Amazon Kinesis Video Streams 信息。在[授予 Amazon Rekognition 访问您的 Kinesis 流的权限](https://docs.aws.amazon.com/rekognition/latest/dg/api-streaming-video-roles.html#api-streaming-video-roles-all-stream)时，您应该使用您创建的 IAM 服务角色的访问密钥和区域。有关访问密钥的更多信息，请参阅**《IAM 用户指南》中的[管理 IAM 用户的访问密钥](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)。此外，您还可以根据使用要求调整视频格式参数，这些参数可从您的设备中获取。

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

 有关更多启动命令，请参阅[ GStreamer 启动命令示例](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-gstreamer-plugin.html#examples-gstreamer-plugin-launch)。

**注意**  
 如果您的启动命令因非协商错误而终止，请检查设备显示器的输出，并确保 `videoconvert` 参数值是设备的有效功能。

 几秒钟后，您将在 Kinesis 视频流中看到来自设备摄像头的视频源。要开始使用 Amazon Rekognition 检测和匹配人脸，请启动您的 Amazon Rekognition Video 流处理器。有关更多信息，请参阅 [Amazon Rekognition Video 流处理器操作概述](streaming-video.md#using-rekognition-video-stream-processor)。

# 流视频问题排查
<a name="streaming-video-troubleshooting"></a>

本主题提供有关将 Amazon Rekognition Video 与流视频结合使用的问题排查信息。

**Topics**
+ [我不知道我的流处理器是否已成功创建](#ts-streaming-video-create-sp)
+ [我不知道我是否已正确配置我的流处理器](#ts-configured-sp)
+ [我的流处理器未返回结果](#ts-streaming-video-no-results-from-sp)
+ [我的流处理器的状态为 FAILED](#ts-failed-state)
+ [我的流处理器未返回预期结果](#w2aac27c79c27c15)

## 我不知道我的流处理器是否已成功创建
<a name="ts-streaming-video-create-sp"></a>

使用以下 AWS CLI 命令获取流处理器及其当前状态的列表。

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

您可以使用以下 AWS CLI 命令获取更多详细信息。将 `stream-processor-name` 替换为所需流处理器的名称。

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

## 我不知道我是否已正确配置我的流处理器
<a name="ts-configured-sp"></a>

如果您的代码未输出来自 Amazon Rekognition Video 的分析结果，则您的流处理器可能未正确配置。请执行以下操作来确认您的流处理器已正确配置并能够生成结果。

**确定您的解决方案是否已正确配置**

1. 运行以下命令来确认您的流处理器处于正在运行状态。将 `stream-processor-name` 更改为您的流处理器的名称。如果 `Status` 的值为 `RUNNING`，则表示流处理器正在运行。如果状态为 `RUNNING` 并且您未获得结果，请参阅 [我的流处理器未返回结果](#ts-streaming-video-no-results-from-sp)。如果状态为 `FAILED`，请参阅[我的流处理器的状态为 FAILED](#ts-failed-state)。

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

1. 如果您的流处理器正在运行，请运行以下 Bash 或 PowerShell 命令从输出 Kinesis 数据流中读取数据。

   **Bash**

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

   **PowerShell**

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

1. 使用 Base64 解码网站上的[解码工具](https://www.base64decode.org/)将输出解码为人类可读的字符串。有关更多信息，请参阅[步骤 3：获取记录](https://docs.aws.amazon.com/streams/latest/dev/fundamental-stream.html#get-records)。

1. 如果命令有效，并且您在 Kinesis 数据流看到人脸检测结果，则表示您的解决方案已正确配置。如果命令失败，请查看其他问题排查建议并参阅[允许 Amazon Rekognition Video 访问您的资源](api-streaming-video-roles.md)。

或者，您可以使用 “kinesis-process-record” AWS Lambda 蓝图将来自 Kinesis 数据流的消息记录到以 CloudWatch 实现持续可视化。这会产生 AWS Lambda 和 CloudWatch的额外成本。

## 我的流处理器未返回结果
<a name="ts-streaming-video-no-results-from-sp"></a>

出于以下几个原因，您的流处理器可能不会返回结果。

### 原因 1：您的流处理器未正确配置
<a name="w2aac27c79c27c11b5"></a>

您的流处理器可能未进行正确配置。有关更多信息，请参阅 [我不知道我是否已正确配置我的流处理器](#ts-configured-sp)。

### 原因 2：您的流处理器未处于 RUNNING 状态
<a name="w2aac27c79c27c11b7"></a>

**排查流处理器状态的问题**

1. 使用以下 AWS CLI 命令检查流处理器的状态。

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

1. 如果 `Status` 的值为 `STOPPED`，则使用以下命令启动您的流处理器：

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

1. 如果 `Status` 的值为 `FAILED`，请参阅[我的流处理器的状态为 FAILED](#ts-failed-state)。

1. 如果 `Status` 的值为 `STARTING`，则等待 2 分钟，然后重复步骤 1 以检查状态。如果 Status 的值仍为 `STARTING`，请执行以下操作：

   1. 使用以下命令删除流处理器。

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

   1. 使用相同配置创建新的流处理器。有关更多信息，请参阅 [使用流视频事件](streaming-video.md)。

   1. 如果您仍然遇到问题，请联系 Su AWS pport。

1. 如果 `Status` 的值为 `RUNNING`，请参阅[原因 3：Kinesis 视频流中没有有效数据](#ts-no-data)。

### 原因 3：Kinesis 视频流中没有有效数据
<a name="ts-no-data"></a>

**检查 Kinesis 视频流中是否有有效数据**

1. 登录并打开 Amazon Kinesis Video Streams 控制台 [https://console.aws.amazon.com/kinesisvideo/](https://console.aws.amazon.com/kinesisvideo/)，网址为。 AWS 管理控制台

1. 选择作为 Amazon Rekognition 流处理器输入的 Kinesis 视频流。

1. 如果预览表明**流上无数据**，则 Amazon Rekognition Video 的输入流中没有要处理的任何数据。

有关使用 Kinesis 视频流生成视频的信息，请参阅 [Kinesis 视频流创建者库](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html)。

## 我的流处理器的状态为 FAILED
<a name="ts-failed-state"></a>

您可以使用以下 AWS CLI 命令检查流处理器的状态。

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

如果 Status 的值为 FAILED，则查看以下错误消息的问题排查信息。

### 错误：“（对角色的访问被拒绝）”
<a name="w2aac27c79c27c13b9"></a>

流处理器所用的 IAM 角色不存在或 Amazon Rekognition Video 无权代入该角色。

**排查对 IAM 角色的访问权限问题**

1. 登录 AWS 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在左侧导航窗格中，选择**角色**并确认该角色存在。

1. 如果该角色存在，请检查该角色是否具有*AmazonRekognitionServiceRole*权限策略。

1. 如果该角色不存在或没有相应的权限，请参阅 [允许 Amazon Rekognition Video 访问您的资源](api-streaming-video-roles.md)。

1. 使用以下 AWS CLI 命令启动流处理器。

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

### 错误：“对 Kinesis 视频的访问被拒绝*或* 对 Kinesis 数据的访问被拒绝”
<a name="w2aac27c79c27c13c11"></a>

该角色无权访问 Kinesis Video Streams API 操作 `GetMedia` 和 `GetDataEndpoint`。此外，它可能无权访问 Kinesis Data Streams API 操作 `PutRecord` 和 `PutRecords`。

**排查 API 权限问题**

1. 登录 AWS 管理控制台 并打开 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/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 资源名称 (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
   ```

### 错误：“找*account-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)