

# Searching faces in a collection
<a name="collections"></a>

Amazon Rekognition lets you use an input face to search for matches in a collection of stored faces. You start by storing information about detected faces in server-side containers called "collections". Collections store both individual faces and users (several faces of the same person). Individual faces are stored as face vectors, a mathematical representation of the face (not an actual image of the face). Different images of the same person can be used to create and store multiple face vectors in the same collection. You can then aggregate multiple face vectors of the same person to create a user vector. User vectors can offer higher face search accuracy with more robust depictions, containing varying degrees of lighting, sharpness, pose, appearance, etc.

Once you've created a collection you can use an input face to search for matching user vectors or face vectors in a collection. Searching against user vectors can significantly improve accuracy compared to searching against individual face vectors. You can use faces detected in images, stored videos, and streaming videos to search against stored face vectors. You can use faces detected in images to search against stored user vectors.

To store face information, you’ll need to do the following:

1. Create a Collection - To store facial information, you must first create ([CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html)) a face collection in one of the AWS Regions in your account. You specify this face collection when you call the `IndexFaces` operation.

1. Index Faces - The [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) operation detects face(s) in an image, extracts, and stores the face vector(s) in the collection. You can use this operation to detect faces in an image and persist information about facial features that are detected into a collection. This is an example of a *storage-based* API operation because the service stores the face vector information on the server.

To create a user and associate multiple face vectors with a user, you'll need to do the following:

1. Create a User - You must first create a user with [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html). You can improve face matching accuracy by aggregating multiple face vectors of the same person into a user vector. You can associate up to 100 face vectors with a user vector. 

1. Associate Faces - After creating the user, you can add existing face vectors to that user with the [AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateFaces.html) operation. Face vectors must reside in the same collection as a user vector in order to be associated to that user vector. 

After creating a collection and storing face and user vectors, you can use the following operations to search for face matches:
+ [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) - To search against stored individual faces with a face from an image.
+ [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) - To search against stored individual faces with a supplied face ID.
+ [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html) - To search against stored users with a supplied face ID or user ID.
+ [SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html) - To search against stored users with a face from an image.
+ [StartFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceSearch.html) - To search for faces in a stored video.
+ [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) - To search for faces in a streaming video.

**Note**  
Collections store face vectors, which are mathematical representations of faces. Collections do not store images of faces.

The following diagrams shows the order for calling operations, based on your goals for using collections:

**For maximum accuracy matching with User Vectors:**

![\[Diagram depicting storing and searching user facial vectors in a collection, lists operations like CreateCollection, IndexFaces, CreateUser, AssociateFaces, SearchUsersByImage, and SearchUsers.\]](http://docs.aws.amazon.com/rekognition/latest/dg/images/uservectorsCollection.png)


**For high accuracy matching with individual Face Vectors:**

![\[Diagram depicting storing and searching faces in a collection, lists operations like CreateCollection, IndexFaces, StartFaceSearch, CreateStreamProcessor, SearchFacesByImage, and SearchFaces.\]](http://docs.aws.amazon.com/rekognition/latest/dg/images/facevectorsCollection.png)


You can use collections in a variety of scenarios. For example, you might create a face collection which stores detected faces from scanned employee badge images and government issued IDs by using the `IndexFaces` and `AssociateFaces` operations. When an employee enters the building, an image of the employee's face is captured and sent to the `SearchUsersByImage` operation. If the face match produces a sufficiently high similarity score (say 99%), you can authenticate the employee. 

# Managing face collections, faces, and users
<a name="managing-face-collections"></a>

 The face collection is the resource used by Amazon Rekognition for containing information related to faces and users. You use various Rekognition API operations to manage the collection itself, as well as any faces or face vectors stored in the collection. 

## Managing a collection
<a name="managing-collections"></a>

The face collection is the primary Amazon Rekognition resource, and each face collection you create has a unique Amazon Resource Name (ARN). You create each face collection in a specific AWS Region in your account. When a collection is created, it's associated with the most recent version of the face detection model. For more information, see [Understanding model versioning](face-detection-model.md). 

You can perform the following management operations on a collection:
+ Create a collection with [CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html). For more information, see [Creating a collection](create-collection-procedure.md).
+ List the available collections with [ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html). For more information, see [Listing collections](list-collection-procedure.md).
+ Describe a collection with [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html). For more information, see [Describing a collection](describe-collection-procedure.md).
+ Delete a collection with [DeleteCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteCollection.html). For more information, see [Deleting a collection](delete-collection-procedure.md).

## Managing faces in a collection
<a name="collections-index-faces"></a>

After you create a face collection, you can store faces in it. Amazon Rekognition provides the following operations for managing faces in a collection:
+  The [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) operation detects faces in the input image (JPEG or PNG), and adds them to the specified face collection. A unique face ID is returned for each face that's detected in the image. After you persist faces, you can search the face collection for face matches. For more information, see [Adding faces to a collection](add-faces-to-collection-procedure.md).
+ The [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) operation lists the faces in a collection. For more information, see [Adding faces to a collection](add-faces-to-collection-procedure.md).
+ The [DeleteFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteFaces.html) operation deletes faces from a collection. For more information, see [Deleting faces from a collection](delete-faces-procedure.md).

## Managing users in a collection
<a name="collections-manage-users"></a>

After you store multiple face vectors from the same person, you can improve accuracy by associating all of those face vectors into one user vector. You can use the following operations to manage your users:
+ [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html) - Operation creates a new user in a collection with a provided unique user ID.
+ [AssociateUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateUsers.html) - Add 1 - 100 unique face IDs to a user ID. After you associate at least one face ID to a user, you can search for matches against that user in your collection.
+ [ListUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListUsers.html) - Lists the users in a collection.
+ [DeleteUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteUsers.html) - Deletes a user from a collection with the provided user ID.
+ [DisassociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DisassociateFaces.html) - Removes one or more face IDs from a user.

# Using similarity thresholds for associating and matching faces
<a name="thresholds-collections"></a>

Similarity thresholds are used for both associating and matching faces. What follows is guidance for using similarity thresholds for both use cases.

## Using similarity thresholds for associating faces
<a name="thresholds-collections-associating-faces"></a>

When associating faces using the [AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociateFaces.html) operation, it’s important to ensure that faces being associated with a user are all from the same person. To help, the `UserMatchThreshold` parameter specifies the minimum user match confidence required for the new face to be associated with a `UserID` containing at least one `FaceID` already. This helps ensures that the `FaceIds` are associated with the right `UserID`. The value ranges from 0-100 and the default value is 75. 

## Using similarity thresholds to match faces
<a name="thresholds-face-match-similarity"></a>

We allow you to control the results of all search operations ([CompareFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CompareFaces.html), [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html), [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html), [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html), [SearchUsersByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsersByImage.html)) by providing a similarity threshold as an input parameter.

`FaceMatchThreshold`, is the similarity threshold input attribute for `SearchFaces` and `SearchFacesByImage`, and it controls how many results are returned based on the similarity to the face being matched. The similarity threshold attribute for `SearchUsers` and `SearchUsersByImage` is `UserMatchThreshold`, and it controls how many results are returned based on the similarity to the user vector being matched. The threshold attribute is `SimilarityThreshold` for `CompareFaces`. 

Responses with a `Similarity` response attribute value that's lower than the threshold aren't returned. This threshold is important to calibrate for your use case, because it can determine how many false positives are included in your match results. This controls the recall of your search results—the lower the threshold, the higher the recall. 

All machine learning systems are probabilistic. You should use your judgment in setting the right similarity threshold, depending on your use case. For example, if you're looking to build a photos app to identify similar-looking family members, you might choose a lower threshold (such as 80%). On the other hand, for many law enforcement use cases, we recommend using a high threshold value of 99% or above to reduce accidental misidentification. 

In addition to `FaceMatchThreshold` and `UserMatchThreshold`, you can use the `Similarity` response attribute as a means to reduce accidental misidentification. For instance, you can choose to use a low threshold (like 80%) to return more results. Then you can use the response attribute Similarity (percentage of similarity) to narrow the choice and filter for the right responses in your application. Again, using a higher similarity (such as 99% and above) reduces the risk of misidentification. 

# Guidance for indexing faces in common scenarios
<a name="guidance-index-faces"></a>

The following is guidance for using `IndexFaces` in common scenarios.

## Critical or public safety applications
<a name="guidance-index-faces-critical"></a>
+ Call [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) with images which contain only one face in each image and associate the returned Face ID with the identifier for the subject of the image.
+ You can use [DetectFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DetectFaces.html) ahead of indexing to verify there is only one face in the image. If more than one face is detected, re-submit the image after review and with only one face present. This prevents inadvertently indexing multiple faces and associating them with the same person.

## Photo sharing and social media applications
<a name="guidance-index-faces-social"></a>
+ You should call `IndexFaces` without restrictions on images that contain multiple faces in use cases such as family albums. In such cases, you need to identify each person in every photo and use that information to group photos by the people present in them. 

## General usage
<a name="guidance-index-faces-general"></a>
+ Index multiple different images of the same person, particularly with different face attributes (facial poses, facial hair, etc), create a user, and associate the different faces to that user to improve matching quality.
+ Include a review process so that failed matches can be indexed with the correct face identifier to improve subsequent face matching ability.
+ For information about image quality, see [Recommendations for facial comparison input images](recommendations-facial-input-images.md). 

# Searching for faces and users within a collection
<a name="collections-search-faces"></a>

After you create a face collection and store face vectors and/or user vectors, you can search a face collection for face matches. With Amazon Rekognition, you can search for faces in a collection that match:
+ A supplied face ID ([SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html)). For more information, see [Searching for a face with a face ID](search-face-with-id-procedure.md).
+ The largest face in a supplied image ([SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html)). For more information, see [Searching for a face with an image](search-face-with-image-procedure.md).
+ Faces in a stored video. For more information, see [Searching stored videos for faces](procedure-person-search-videos.md).
+ Faces in a streaming video. For more information, see [Working with streaming video events](streaming-video.md).

You can use the `CompareFaces` operation to compare a face in a source image with faces in the target image. The scope of this comparison is limited to the faces that are detected in the target image. For more information, see [Comparing faces in images](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html).

The various Search operations seen in the following list compare a face (identified either by a `FaceId` or an input image) with all faces stored in a given face collection: 
+ [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)

# Use cases that involve public safety
<a name="considerations-public-safety-use-cases"></a>

 In addition to the recommendations listed in [Best practices for sensors, input images, and videos](best-practices.md) and [Guidance for indexing faces in common scenarios](guidance-index-faces.md), you should use the following best practices when deploying face detection and comparison systems in use cases that involve public safety. First, you should use confidence thresholds of 99% or higher to reduce errors and false positives. Second, you should involve human reviewers to verify results received from a face detection or comparison system, and you should not make decisions based on system output without additional human review. Face detection and comparison systems should serve as a tool to help narrow the field and allow humans to expeditiously review and consider options. Third, we recommend that you should be transparent about the use of face detection and comparison systems in these use cases, including, wherever possible, informing end users and subjects about the use of these systems, obtaining consent for such use, and providing a mechanism where end users and subjects can provide feedback to improve the system.

 If you are a law enforcement agency that is using the Amazon Rekognition face comparison feature in connection with criminal investigations, you must follow the requirements listed in the [AWS Service Terms](https://aws.amazon.com/service-terms/). This includes the following.
+ Have appropriately trained humans review all decisions to take action that might impact a person’s civil liberties or equivalent human rights.
+ Train personnel on responsible use of facial recognition systems.
+ Provide public disclosures of your use of facial recognition systems.
+ Don't use Amazon Rekognition for sustained surveillance of a person without independent review or exigent circumstances.

In all cases, facial comparison matches should be viewed in the context of other compelling evidence, and shouldn't be used as the sole determinant for taking action. However, if facial comparison is used for non-law-enforcement scenarios (for example, for unlocking a phone or authenticating an employee’s identity to access a secure, private office building), these decisions wouldn't require a manual audit because they wouldn't impact a person's civil liberties or equivalent human rights. 

If you're planning to use a face detection or face comparison system for use cases that involve public safety you should employ the best practices mentioned previously. In addition, you should consult published resources on the use of face comparison. This includes the [Face Recognition Policy Development Template For Use In Criminal Intelligence and Investigative Activities](https://www.bja.gov/Publications/Face-Recognition-Policy-Development-Template-508-compliant.pdf) provided by the Bureau of Justice Assistance of the Department of Justice. The template provides several facial comparison and biometric-related resources and is designed to provide law enforcement and public safety agencies with a framework for developing face comparison policies that comply with applicable laws, reduce privacy risks, and establish entity accountability and oversight. Additional resources include [ Best Privacy Practices for Commercial Use of Facial Recognition](https://www.ntia.doc.gov/files/ntia/publications/privacy_best_practices_recommendations_for_commercial_use_of_facial_recogntion.pdf) by the National Telecommunications and Information Administration and [ Best Practices for Common Uses of Facial Recognition](https://www.ftc.gov/sites/default/files/documents/reports/facing-facts-best-practices-common-uses-facial-recognition-technologies/121022facialtechrpt.pdf) by the staff of the Federal Trade Commission. Other resources may be developed and published in the future, and you should continuously educate yourself on this important topic.

As a reminder, you must comply with all applicable laws in their use of AWS services, and you may not use any AWS service in a manner that violates the rights of others or may be harmful to others. This means that you may not use AWS services for public safety use cases in a way that illegally discriminates against a person or violates a person’s due process, privacy, or civil liberties. You should obtain appropriate legal advice as necessary to review any legal requirements or questions regarding your use case. 

## Using Amazon Rekognition to help public safety
<a name="public-safety"></a>

Amazon Rekognition can help in public safety and law enforcement scenarios—such as finding lost children, combating human trafficking, or preventing crimes. In public safety and law enforcement scenarios, consider the following:
+ Use Amazon Rekognition as the first step in finding possible matches. The responses from Amazon Rekognition face operations allow you to quickly get a set of potential matches for further consideration.
+ Don’t use Amazon Rekognition responses to make autonomous decisions for scenarios that require analysis by a human. If you are a law enforcement agency using Amazon Rekognition to assist in identifying a person in connection with a criminal investigation, and actions will be taken based on the identification that could impact that person’s civil liberties or equivalent human rights, the decision to take action must be made by an appropriately trained person based on their independent examination of the identification evidence.
+ Use a 99% similarity threshold for scenarios where highly accurate face similarity matches are necessary. An example of this is authenticating access to a building.
+ When civil rights are a concern, such as use cases involving law enforcement, use confidence thresholds of 99% or higher and employ human review of facial comparison predictions to ensure that a person’s civil rights aren't violated.
+ Use a similarity threshold lower than 99% for scenarios that benefit from a larger set of potential matches. An example of this is finding missing persons. If necessary, you can use the Similarity response attribute to determine how similar potential matches are to the person you want to recognize. 
+ Have a plan for false-positive face matches that are returned by Amazon Rekognition. For example, improve matching by using multiple images of the same person when you build the index with the [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) operation. For more information, see [Guidance for indexing faces in common scenarios](guidance-index-faces.md).

In other use cases (such as social media), we recommend you use your best judgement to assess if the Amazon Rekognition results need human review. Also, depending on your application’s requirements, the similarity threshold can be lower. 

# Creating a collection
<a name="create-collection-procedure"></a>

You can use the [CreateCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateCollection.html) operation to create a collection.

For more information, see [Managing a collection](managing-face-collections.md#managing-collections). 

**To create a collection (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `CreateCollection` operation.

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

   The following example creates a collection and displays its Amazon Resource Name (ARN).

   Change the value of `collectionId` to the name of the collection you want to create.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javav2/example_code/rekognition/src/main/java/com/example/rekognition/CreateCollection.java).

    Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This AWS CLI command displays the JSON output for the `create-collection` CLI operation. 

   Replace the value of `collection-id` with the name of the collection you want to create.

    Replace the value of `profile_name` with the name of your developer profile. 

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

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

   The following example creates a collection and displays its Amazon Resource Name (ARN). 

   Change the value of `collection_id` to the name of collection you want to create. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

   The following example creates a collection and displays its Amazon Resource Name (ARN).

   Change the value of `collectionId` to the name of collection you want to create.

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

   In the following example, replace the value of `region` with the name of the region associated with your account and replace the value of `collectionName` with the desired name of your collection.

    Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

   ```
   //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 operation request
<a name="createcollection-request"></a>

The input to `CreationCollection` is the name of the collection that you want to create.

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

## CreateCollection operation response
<a name="createcollection-operation-response"></a>

Amazon Rekognition creates the collection and returns the Amazon Resource Name (ARN) of the newly created collection.

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

# Tagging collections
<a name="tag-collections"></a>

You can identify, organize, search for, and filter Amazon Rekognition collections by using tags. Each tag is a label consisting of a user-defined key and value.

You can also use tags to control access for a collection by using Identity and Access Management (IAM). For more information, see [Controlling access to AWS resources using resource tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_tags.html).

**Topics**
+ [Add tags to a new collection](#add-tag-new-collection)
+ [Add tags to an existing collection](#add-tag-existing-collection)
+ [List tags in a collection](#list-tags-collection)
+ [Delete tags from a collection](#delete-tag-collection)

## Add tags to a new collection
<a name="add-tag-new-collection"></a>

You can add tags to a collection as you create it using the `CreateCollection` operation. Specify one or more tags in the `Tags` array input parameter.

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

 Replace the value of `profile_name` with the name of your developer profile. 

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

For Windows devices:

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

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

 Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

------

## Add tags to an existing collection
<a name="add-tag-existing-collection"></a>

To add one or more tags to an existing collection, use the `TagResource` operation. Specify the collection's Amazon Resource Name (ARN) (`ResourceArn`) and the tags (`Tags`) that you want to add. The following example shows how to add two tags.

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

 Replace the value of `profile_name` with the name of your developer profile. 

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

 For Windows devices: 

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

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

 Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

------

**Note**  
If you do not know the collection's Amazon Resource Name, you can use the `DescribeCollection` operation.

## List tags in a collection
<a name="list-tags-collection"></a>

To list the tags attached to a collection, use the `ListTagsForResource` operation and specify the ARN of the collection (`ResourceArn`). The response is a map of tag keys and values that are attached to the specified collection.

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

 Replace the value of `profile_name` with the name of your developer profile. 

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

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

 Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

------

The output displays a list of tags attached to the collection:

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

## Delete tags from a collection
<a name="delete-tag-collection"></a>

To remove one or more tags from a collection, use the `UntagResource` operation. Specify the ARN of the model (`ResourceArn`) and the tag keys (`Tag-Keys`) that you want to remove.

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

Replace the value of `profile_name` with the name of your developer profile.

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

Alternatively, you can specify tag-keys in this format:

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

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

 Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

------

# Listing collections
<a name="list-collection-procedure"></a>

You can use the [ListCollections](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListCollections.html) operation to list the collections in the region that you are using.

For more information, see [Managing a collection](managing-face-collections.md#managing-collections). 



**To list collections (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `ListCollections` operation.

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

   The following example lists the collections in the current region.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `list-collections` CLI operation. Replace the value of `profile_name` with the name of your developer profile. 

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

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

   The following example lists the collections in the current region.

    Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   The following example lists the collections in the current region.

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

    Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

   ```
   //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 operation request
<a name="listcollections-request"></a>

The input to `ListCollections` is the maximum number of collections to be returned. 

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

If the response has more collections than are requested by `MaxResults`, a token is returned that you can use to get the next set of results, in a subsequent call to `ListCollections`. For example:

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

## ListCollections operation response
<a name="listcollections-operation-response"></a>

Amazon Rekognition returns an array of collections (`CollectionIds`). A separate array (`FaceModelVersions`) provides the version of the face model used to analyze faces in each collection. For example, in the following JSON response, the collection `MyCollection` analyzes faces by using version 2.0 of the face model. The collection `AnotherCollection` uses version 3.0 of the face model. For more information, see [Understanding model versioning](face-detection-model.md).

`NextToken` is the token that's used to get the next set of results, in a subsequent call to `ListCollections`. 

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

# Describing a collection
<a name="describe-collection-procedure"></a>

You can use the [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html) operation to get the following information about a collection: 
+ The number of faces that are indexed into the collection.
+ The version of the model being used with the collection. For more information, see [Understanding model versioning](face-detection-model.md).
+ The Amazon Resource Name (ARN) of the collection.
+ The creation date and time of the collection.

**To describe a collection (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `DescribeCollection` operation.

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

   This example describes a collection.

   Change the value `collectionId` to the ID of the desired collection.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `describe-collection` CLI operation. Change the value of `collection-id` to the ID of the desired collection. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

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

   This example describes a collection.

   Change the value `collection_id` to the ID of the desired collection. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example describes a collection.

   Change the value `collectionId` to the ID of the desired collection.

   ```
   //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 operation request
<a name="describe-collection-request"></a>

The input to `DescribeCollection` is the ID of the desired collection, as shown in the following JSON example. 

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

## DescribeCollection operation response
<a name="describe-collection-operation-response"></a>

The response includes: 
+ The number of faces that are indexed into the collection, `FaceCount`.
+ The version of the face model being used with the collection, `FaceModelVersion`. For more information, see [Understanding model versioning](face-detection-model.md).
+ The collection Amazon Resource Name, `CollectionARN`. 
+ The creation time and date of the collection, `CreationTimestamp`. The value of `CreationTimestamp` is the number of milliseconds since the Unix epoch time until the creation of the collection. The Unix epoch time is 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. For more information, see [Unix Time](https://en.wikipedia.org/wiki/Unix_time).

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

# Deleting a collection
<a name="delete-collection-procedure"></a>

You can use the [DeleteCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteCollection.html) operation to delete a collection.

For more information, see [Managing a collection](managing-face-collections.md#managing-collections). 



**To delete a collection (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `DeleteCollection` operation.

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

   This example deletes a collection.

   Change the value `collectionId` to the collection that you want to delete.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `delete-collection` CLI operation. Replace the value of `collection-id` with the name of the collection that you want to delete. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

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

   This example deletes a collection.

   Change the value `collection_id` to the collection that you want to delete. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example deletes a collection.

   Change the value `collectionId` to the collection that you want to delete.

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

    Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

   ```
   //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 operation request
<a name="deletecollection-request"></a>

The input to `DeleteCollection` is the ID of the collection to be deleted, as shown in the following JSON example. 

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

## DeleteCollection operation response
<a name="deletecollection-operation-response"></a>

The `DeleteCollection` response contains an HTTP status code that indicates the success or failure of the operation. `200` is returned if the collection is successfully deleted.

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

# Adding faces to a collection
<a name="add-faces-to-collection-procedure"></a>

You can use the [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) operation to detect faces in an image and add them to a collection. For each face detected, Amazon Rekognition extracts facial features and stores the feature information in a database. In addition, the command stores metadata for each face that's detected in the specified face collection. Amazon Rekognition doesn't store the actual image bytes.

For information about providing suitable faces for indexing, see [Recommendations for facial comparison input images](recommendations-facial-input-images.md).

For each face, the `IndexFaces` operation persists the following information:
+ **Multidimensional facial features** – `IndexFaces` uses facial analysis to extract multidimensional information about the facial features and stores the information in the face collection. You can't access this information directly. However, Amazon Rekognition uses this information when it searches a face collection for face matches.

   
+ **Metadata** – The metadata for each face includes a bounding box, confidence level (that the bounding box contains a face), IDs assigned by Amazon Rekognition (face ID and image ID), and an external image ID (if you provided it) in the request. This information is returned to you in response to the `IndexFaces` API call. For an example, see the `face` element in the following example response.

  The service returns this metadata in response to the following API calls:

   
  +  `[ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html)` 
  + Search faces operations – The responses for [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) and [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) return the confidence in the match for each matching face, along with this metadata of the matched face.

The number of faces indexed by `IndexFaces` depends on the version of the face detection model that's associated with the input collection. For more information, see [Understanding model versioning](face-detection-model.md). 

Information about indexed faces is returned in an array of [FaceRecord](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceRecord.html) objects.

You might want to associate indexed faces with the image they were detected in. For example, you might want to maintain a client-side index of images and faces in the images. To associate faces with an image, specify an image ID in the `ExternalImageId` request parameter. The image ID can be the file name or another ID that you create.

In addition to the preceding information that the API persists in the face collection, the API also returns face details that aren't persisted in the collection. (See the `faceDetail` element in the following example response). 

**Note**  
`DetectFaces` returns the same information, so you don't need to call both `DetectFaces` and `IndexFaces` for the same image. 

## Filtering faces
<a name="index-faces-filtering"></a>

The IndexFaces operation enables you to filter the faces that are indexed from an image. With `IndexFaces` you can specify a maximum number of faces to index, or you can choose to only index faces detected with a high quality. 

You can specify the maximum number of faces that are indexed by `IndexFaces` by using the `MaxFaces` input parameter. This is useful when you want to index the largest faces in an image and don't want to index smaller faces, such as faces of people standing in the background.

By default, `IndexFaces` chooses a quality bar that's used to filter out faces. You can use the `QualityFilter` input parameter to explicitly set the quality bar. The values are:
+ `AUTO` — Amazon Rekognition chooses the quality bar that's used to filter out faces (default value).
+ `LOW` — All except the lowest quality faces are indexed.
+ `MEDIUM`
+ `HIGH` — Only the highest quality faces are indexed.
+ `NONE` - No faces are filtered out based on quality.

`IndexFaces` filters faces for the following reasons:
+ The face is too small compared to the image dimensions.
+ The face is too blurry.
+ The image is too dark.
+ The face has an extreme pose.
+ The face doesn’t have enough detail to be suitable for face search.

**Note**  
To use quality filtering, you need a collection that's associated with version 3, or higher, of the face model. To get the version of the face model associated with a collection, call [DescribeCollection](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DescribeCollection.html). 

Information about faces that aren't indexed by `IndexFaces` is returned in an array of [UnindexedFace](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_UnindexedFace.html) objects. The `Reasons` array contains a list of reasons why a face isn't indexed. For example, a value of `EXCEEDS_MAX_FACES` is a face that's not indexed because the number of faces specified by `MaxFaces` has already been detected. 

For more information, see [Managing faces in a collection](managing-face-collections.md#collections-index-faces). 



**To add faces to a collection (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` and `AmazonS3ReadOnlyAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Upload an image (containing one or more faces) to your Amazon S3 bucket. 

   For instructions, see [Uploading Objects into Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html) in the *Amazon Simple Storage Service User Guide*.

1. Use the following examples to call the `IndexFaces` operation.

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

   This example displays the face identifiers for faces added to the collection.

   Change the value of `collectionId` to the name of the collection that you want to add a face to. Replace the values of `bucket` and `photo` with the names of the Amazon S3 bucket and image that you used in step 2. The `.withMaxFaces(1)` parameter restricts the number of indexed faces to 1. Remove or change its value to suit your needs.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `index-faces` CLI operation. 

   Replace the value of `collection-id` with the name of the collection you want the face to be stored in. Replace the values of `Bucket` and `Name` with the Amazon S3 bucket and image file that you used in step 2. The `max-faces` parameter restricts the number of indexed faces to 1. Remove or change its value to suit your needs. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

    If you are accessing the CLI on a Windows device, use double quotes instead of single quotes and escape the inner double quotes by backslash (i.e. \$1) to address any parser errors you may encounter. For an example, see the following: 

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

   This example displays the face identifiers for faces added to the collection.

   Change the value of `collectionId` to the name of the collection that you want to add a face to. Replace the values of `bucket` and `photo` with the names of the Amazon S3 bucket and image that you used in step 2. The `MaxFaces` input parameter restricts the number of indexed faces to 1. Remove or change its value to suit your needs. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example displays the face identifiers for faces added to the collection.

   Change the value of `collectionId` to the name of the collection that you want to add a face to. Replace the values of `bucket` and `photo` with the names of the Amazon S3 bucket and image that you used in step 2. 

   ```
   //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 operation request
<a name="indexfaces-request"></a>

The input to `IndexFaces` is the image to be indexed and the collection to add the face or faces to. 

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

## IndexFaces operation response
<a name="indexfaces-operation-response"></a>

`IndexFaces` returns information about the faces that were detected in the image. For example, the following JSON response includes the default detection attributes for faces detected in the input image. The example also shows faces not indexed because the value of the `MaxFaces` input parameter has been exceeded — the `Reasons` array contains *EXCEEDS\$1MAX\$1FACES*. If a face is not indexed for quality reasons, `Reasons` contains values such as *LOW\$1SHARPNESS* or *LOW\$1BRIGHTNESS*. For more information, see [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"
            ]
        }
    ]
}
```

To get all facial information, specify 'ALL' for the `DetectionAttributes` request parameter. For example, in the following example response, note the additional information in the `faceDetail` element, which isn't persisted on the server:
+ 25 facial landmarks (compared to only five in the preceding example)
+ Ten facial attributes (eyeglasses, beard, occlusion, eye gaze direction, and so on) 
+ Emotions (see the `emotion` element)

The `face` element provides metadata that's persisted on the server.

 `FaceModelVersion` is the version of the face model that's associated with the collection. For more information, see [Understanding model versioning](face-detection-model.md).

`OrientationCorrection` is the estimated orientation of the image. Orientation correction information is not returned if you are using a version of the face detection model that is greater than version 3. For more information, see [Getting image orientation and bounding box coordinates](images-orientation.md).

The following sample response shows the returned JSON when specifying ["ALL"]:

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

# Listing faces and associated users in a collection
<a name="list-faces-in-collection-procedure"></a>

You can use the [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) operation to list faces and their associated users in a collection.

For more information, see [Managing faces in a collection](managing-face-collections.md#collections-index-faces). 



**To list faces in a collection (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `ListFaces` operation.

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

   This example displays a list of faces in a collection.

   Change the value of `collectionId` to the desired collection.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `list-faces` CLI operation. Replace the value of `collection-id` with the name of the collection you want to list. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

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

   This example displays a list of faces in a collection.

   Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example displays a list of faces in a collection.

   Change the value of `collectionId` to the desired collection.

   ```
   //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 operation request
<a name="listfaces-request"></a>

The input to `ListFaces` is the ID of the collection that you want to list faces for. `MaxResults` is the maximum number of faces to return. ListFaces also takes in a list of face IDs to filter the results with, and a user ID provided to list only faces associated with the given user.

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

If the response has more faces than are requested by `MaxResults`, a token is returned that you can use to get the next set of results, in a subsequent call to `ListFaces`. For example:

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

## ListFaces operation response
<a name="listfaces-response"></a>

The response from `ListFaces` is information about the face metadata that's stored in the specified collection.
+ **FaceModelVersion** – The version of the face model that's associated with the collection. For more information, see [Understanding model versioning](face-detection-model.md).
+  **Faces** – Information about the faces in the collection. This includes information about [BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html), confidence, image identifiers, and the face ID. For more information, see [Face](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Face.html). 
+  **NextToken** – The token that's used to get the next set of results. 

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

# Deleting faces from a collection
<a name="delete-faces-procedure"></a>

You can use the [DeleteFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteFaces.html) operation to delete faces from a collection. For more information, see [Managing faces in a collection](managing-face-collections.md#collections-index-faces). 



**To delete faces from a collection**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `DeleteFaces` operation.

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

   This example deletes a single face from a collection.

   Change the value of `collectionId` to the collection that contains the face that you want to delete. Change the value of `faces` to the ID of the face that you want to delete. To delete multiple faces, add the face IDs to the `faces` array.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `delete-faces` CLI operation. Replace the value of `collection-id` with the name of the collection that contains the face you want to delete. Replace the value of `face-ids` with an array of face IDs that you want to delete. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

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

   This example deletes a single face from a collection.

   Change the value of `collectionId` to the collection that contains the face that you want to delete. Change the value of `faces` to the ID of the face that you want to delete. To delete multiple faces, add the face IDs to the `faces` array. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

   This example deletes a single face from a collection.

   Change the value of `collectionId` to the collection that contains the face that you want to delete. Change the value of `faces` to the ID of the face that you want to delete. To delete multiple faces, add the face IDs to the `faces` list.

   ```
   //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 operation request
<a name="deletefaces-request"></a>

The input to `DeleteFaces` is the ID of the collection that contains the faces, and an array of face IDs for the faces to be deleted. 

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

## DeleteFaces operation response
<a name="deletefaces-operation-response"></a>

The `DeleteFaces` response contains an array of face IDs for the faces that were deleted.

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

 If the face IDs provided in the input are currently associated with an User, they will be returned as part of UnsuccessfulFaceDeletions with valid reasons. 

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

# Creating a user
<a name="create-user"></a>

You can use the [CreateUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateUser.html) operation to create a new user in a collection using a unique user ID you provide. You can then associate multiple faces with the newly created user.

**To create a user (SDK)**

1. If you haven't already:

   1. Create or update an IAM user account with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `CreateUser` operation.

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

   This Java code example creates a user. 

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

   This AWS CLI command creates a user, using the `create-user` CLI operation. 

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

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

   This Python code example creates a user. 

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

   This Go code example uses the AWS Go SDK V2 and it creates a user. 

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

------

# Deleting a user
<a name="delete-user"></a>

You can use the [DeleteUser](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DeleteUser.html) operation to delete a user from a collection, based on the provided UserID. Note that any faces that associated with the UserID are disassociated from the UserID before the specified UserID is deleted.

**To delete a user (SDK)**

1. If you haven't already:

   1. Create or update an IAM user account with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `DeleteUser` operation.

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

   This Java code example deletes a user. 

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

   This AWS CLI command deletes a user, using the `create-user` CLI operation. 

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

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

   This Python code example deletes a user. 

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

------

# Associating faces to a user
<a name="associate-faces"></a>

You can use the [AssociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_AssociatingFaces.html) operation to associate multiple individual faces with a single user. In order to associate a face with a user, you must first create a collection and a user. Note that the face vectors must reside in the same collection where the user vector resides.

**To associate faces (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `AssociateFaces` operation.

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

   This Java code example associates a face with a user.

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

   This AWS CLI command associates a face with a user, using the `associate-faces` CLI operation.

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

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

   This Python code example associates a face with a user. 

   ```
   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 operation response
<a name="associatefaces-operation-response"></a>

The response for `AssociateFaces` includes the `UserStatus`, which is the status of the disassociation request, as well as a list of `FaceIds` to be associated. A list of `UnsuccessfulFaceAssociations` is also returned. After submitting a request to `AssociateFaces`, the operation may take a minute or so to complete. 

For this reason, the UserStatus is returned, which can have the following values: 
+ CREATED - Denotes that the ‘User’ is created successfully and no faces are associated to it currently. ‘User’ will be in this state before any successful ‘AssociateFaces’ call is made.
+ UPDATING - Denotes that the ‘User’ is being updated to reflect the newly associated/disassociated faces and will become ACTIVE in few seconds. Search results may contain ‘User’ in this state and customers can choose to ignore them from the returned results.
+ ACTIVE - Denotes that the** ‘**User**’ **is updated to reflect all associated/disassociated faces and is in a searchable state.

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

# Disassociating faces from a user
<a name="disassociate-faces"></a>

You can use the [DisassociateFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_DisassociateFaces.html) operation to remove the association between a user ID and a face ID.

**To disassociate faces (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `DisassociateFaces` operation.

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

   This Java example removes the association between a FaceID and a UserID with the `DisassociateFaces` operation.

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

   This AWS CLI command removes the association between a FaceID and a UserID with the `DisassociateFaces` operation.

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

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

   The following example removes the association between a FaceID and a UserID with the `DisassociateFaces` operation.

   ```
   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 operation response
<a name="disassociate-faces-response"></a>

The response for `DisassociateFaces` includes the `UserStatus`, which is the status of the disassociation request, as well as a list of `FaceIds` to be unassociated. A list of `UnsuccessfulFaceDisassociations` is also returned. After submitting a request to DisassociateFaces, the operation may take a minute or so to complete. For this reason, the UserStatus is returned, which can have the following values: 
+ CREATED - Denotes that the ‘User’ is created successfully and no faces are associated to it currently. ‘User’ will be in this state before any successful ‘AssociateFaces’ call is made.
+ UPDATING - Denotes that the ‘User’ is being updated to reflect the newly associated/disassociated faces and will become ACTIVE in few seconds. Search results may contain ‘User’ in this state and customers can choose to ignore them from the returned results.
+ ACTIVE - Denotes that the** ‘**User**’ **is updated to reflect all associated/disassociated faces and is in a searchable state.

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

# Listing users in a collection
<a name="list-users"></a>

You can use the [ListUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListUsers.html) operation to list UserIds and the UserStatus. To see the FaceIDs that are associated with a UserID, use the [ListFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ListFaces.html) operation.

**To list users (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `ListUsers` operation.

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

   This Java example lists the users in a collection using the `ListUsers` operation.

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

   This AWS CLI command lists the users in a collection with the `ListUsers` operation.

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

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

   The following example lists the users in a collection with the `ListUsers` operation.

   ```
   # 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 operation response
<a name="list-users-response"></a>

The response for a request to ListUsers includes a list of the `Users` in the collection along with the `UsedId` and `UserStatus` of the User.

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

# Searching for a face with a face ID
<a name="search-face-with-id-procedure"></a>

You can use the [SearchFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFaces.html) operation to search for users in a collection that match the largest face in a supplied image.

The face ID is returned in the [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html) operation response when the face is detected and added to a collection. For more information, see [Managing faces in a collection](managing-face-collections.md#collections-index-faces).



**To search for a face in a collection using its face ID (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `SearchFaces` operation.

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

   This example displays information about faces that match a face identified by its ID.

   Change the value of `collectionID` to the collection that contains the required face. Change the value of `faceId` to the identifier of the face you want to find.

   ```
   //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();
         }
       }
   
   }
   ```

   Run the example code. Information about matching faces is displayed.

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `search-faces` CLI operation. Replace the value of `face-id` with the face identifier that you want to search for, and replace the value of `collection-id` with the collection you want to search in. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

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

   This example displays information about faces that match a face identified by its ID.

   Change the value of `collectionID` to the collection that contains the required face. Change the value of `faceId` to the identifier of the face you want to find. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example displays information about faces that match a face identified by its ID.

   Change the value of `collectionID` to the collection that contains the required face. Change the value of `faceId` to the identifier of the face that you want to find.

   ```
   //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);
       }
   }
   ```

   Run the example code. Information about matching faces is displayed.

------

## SearchFaces operation request
<a name="searchfaces-operation-request"></a>

Given a face ID (each face stored in the face collection has a face ID), `SearchFaces` searches the specified face collection for similar faces. The response doesn't include the face you are searching for. It includes only similar faces. By default, `SearchFaces` returns faces for which the algorithm detects similarity of greater than 80%. The similarity indicates how closely the face matches with the input face. Optionally, you can use `FaceMatchThreshold` to specify a different value. 

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

## SearchFaces operation response
<a name="searchfaces-operation-response"></a>

The operation returns an array of face matches that were found and the face ID you provided as input.

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

For each face match that was found, the response includes similarity and face metadata, as shown in the following example response: 

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

# Searching for a face with an image
<a name="search-face-with-image-procedure"></a>

You can use the [SearchFacesByImage](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchFacesByImage.html) operation to search for faces in a collection that match the largest face in a supplied image.

For more information, see [Searching for faces and users within a collection](collections-search-faces.md). 



**To search for a face in a collection using an image (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` and `AmazonS3ReadOnlyAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Upload an image (that contains one or more faces) to your S3 bucket. 

   For instructions, see [Uploading Objects into Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UploadingObjectsintoAmazonS3.html) in the *Amazon Simple Storage Service User Guide*.

1. Use the following examples to call the `SearchFacesByImage` operation.

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

   This example displays information about faces that match the largest face in an image. The code example specifies both the `FaceMatchThreshold` and `MaxFaces` parameters to limit the results that are returned in the response.

   In the following example, change the following: change the value of `collectionId` to the collection you want to search, change the value of `bucket` to the bucket containing the input image, and change the value of `photo` to the input image. 

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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 ]

   This AWS CLI command displays the JSON output for the `search-faces-by-image` CLI operation. Replace the value of `Bucket` with the S3 bucket that you used in step 2. Replace the value of `Name` with the image file name that you used in step 2. Replace the value of `collection-id` with the collection you want to search in. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile.

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

    If you are accessing the CLI on a Windows device, use double quotes instead of single quotes and escape the inner double quotes by backslash (i.e. \$1) to address any parser errors you may encounter. For an example, see the following: 

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

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

   This example displays information about faces that match the largest face in an image. The code example specifies both the `FaceMatchThreshold` and `MaxFaces` parameters to limit the results that are returned in the response.

   In the following example, change the following: change the value of `collectionId` to the collection you want to search, and replace the values of `bucket` and `photo` with the names of the Amazon S3 bucket and image that you used in Step 2. Replace the value of `profile_name` in the line that creates the Rekognition session with the name of your developer profile. 

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

   This example displays information about faces that match the largest face in an image. The code example specifies both the `FaceMatchThreshold` and `MaxFaces` parameters to limit the results that are returned in the response.

   In the following example, change the following: change the value of `collectionId` to the collection you want to search, and replace the values of `bucket` and `photo` with the names of the Amazon S3 bucket and image that you used in step 2. 

   ```
   //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 operation request
<a name="searchfacesbyimage-operation-request"></a>

The input parameters to `SearchFacesImageByImage` are the collection to search in and the source image location. In this example, the source image is stored in an Amazon S3 bucket (`S3Object`). Also specified are the maximum number of faces to return (`Maxfaces`) and the minimum confidence that must be matched for a face to be returned (`FaceMatchThreshold`).

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

## SearchFacesByImage operation response
<a name="searchfacesbyimage-operation-response"></a>

Given an input image (.jpeg or .png), the operation first detects the face in the input image, and then searches the specified face collection for similar faces. 

**Note**  
If the service detects multiple faces in the input image, it uses the largest face that's detected for searching the face collection.

The operation returns an array of face matches that were found, and information about the input face. This includes information such as the bounding box, along with the confidence value, which indicates the level of confidence that the bounding box contains a face. 

By default, `SearchFacesByImage` returns faces for which the algorithm detects similarity of greater than 80%. The similarity indicates how closely the face matches with the input face. Optionally, you can use `FaceMatchThreshold` to specify a different value. For each face match found, the response includes similarity and face metadata, as shown in the following example response: 

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

# Searching for users (face ID/ user ID)
<a name="search-users"></a>

You can use the [SearchUsers](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_SearchUsers.html) operation to to search for users in a specified collection that match a supplied face ID or user ID. The operation lists the returned `UserIds` ranked by the highest similarity score above the requested UserMatchThreshold. The user ID is created in the CreateUsers operation. For more information, see [Managing users in a collection](managing-face-collections.md#collections-manage-users).

**To search users (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `SearchUsers` operation.

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

   This Java example searchers the users in a collection using the `SearchUsers` operation.

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

   This AWS CLI command searches the users in a collection with the `SearchUsers` operation.

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

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

   The following example searches the users in a collection with the `SearchUsers` operation.

   ```
   # 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 operation request
<a name="search-users-request"></a>

Given a FaceID or UserID, SearchUsers searches the specified CollectionID for user matches. By default, SearchUsers returns UserIDs for which the similarity score is greater than 80%. The similarity indicates how closely the UserID matches the provided FaceID or UserID. If multiple UserIDs are returned, they are listed in order of highest similarity score to lowest. Optionally, you can use the UserMatchThreshold to specify a different value. For more information, see [Managing users in a collection](managing-face-collections.md#collections-manage-users). 

The following is an example of a SearchUsers request using `UserId`:

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

The following is an example of a SearchUsers request using `FaceId`:

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

## SearchUsers operation response
<a name="search-users-response"></a>

If searching with a `FaceId`, the response for SearchUsers includes the `FaceId` for the `SearchedFace`, as well as a list of `UserMatches` and the `UserId` and `UserStatus` for each User.

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

If searching with a `UserId`, the response for SearchUsers includes the `UserId` for the `SearchedUser`, in addition to the other response elements.

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

# Searching for users (image)
<a name="search-users-by-image"></a>

`SearchUsersByImage`searches the specified CollectionID for users in a collection that match the largest face detected in a supplied image. By default, SearchUsersByImage returns UserIDs for which the similarity score is greater than 80%. The similarity indicates how closely the UserID matches the largest face detected in the supplied image. If multiple UserIDs are returned, they are listed in order of highest similarity score to lowest. Optionally, you can use the UserMatchThreshold to specify a different value. For more information, see [Managing users in a collection](managing-face-collections.md#collections-manage-users). 



**To search users by image (SDK)**

1. If you haven't already:

   1. Create or update a user with `AmazonRekognitionFullAccess` permissions. For more information, see [Step 1: Set up an AWS account and create a User](setting-up.md#setting-up-iam).

   1. Install and configure the AWS CLI and the AWS SDKs. For more information, see [Step 2: Set up the AWS CLI and AWS SDKs](setup-awscli-sdk.md).

1. Use the following examples to call the `SearchUsersByImage` operation.

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

   This Java example searchers the users in a collection based off an inpute image, using the `SearchUsersByImage` operation.

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

   This AWS CLI command searches the users in a collection based on an input image, with the `SearchUsersByImage` operation.

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

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

   The following example searches the users in a collection based on an input image, with the `SearchUsersByImage` operation.

   ```
   # 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 operation request
<a name="search-users-by-image-request"></a>

The request for `SearchUsersByImage` includes the the collection to search in and the source image location. In this example, the source image is stored in an Amazon S3 bucket ( `S3Object` ). Also specified are the maximum number of users to return ( `MaxUsers` ) and the minimum confidence that must be matched for a user to be returned ( `UserMatchThreshold`).

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

## SearchUsersByImage operation response
<a name="search-users-by-image-response"></a>

The response for `SearchUsersByImage` includes a `FaceDetail` object for the `SearchedFace`, as well as a list of UserMatches with the `UserId`, `Similarity`, and `UserStatus` for each. If the input image contained more than one face, a list of UnsearchedFaces will be also returned.

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

# Searching stored videos for faces
<a name="procedure-person-search-videos"></a>

You can search a collection for faces that match faces of people who are detected in a stored video or a streaming video. This section covers searching for faces in a stored video. For information about searching for faces in a streaming video, see [Working with streaming video events](streaming-video.md).

The faces that you search for must first be indexed into a collection by using [IndexFaces](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_IndexFaces.html). For more information, see [Adding faces to a collection](add-faces-to-collection-procedure.md). 

Amazon Rekognition Video face searching follows the same asynchronous workflow as other Amazon Rekognition Video operations that analyze videos stored in an Amazon S3 bucket. To start searching for faces in a stored video, call [StartFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartFaceSearch.html) and provide the ID of the collection that you want to search. Amazon Rekognition Video publishes the completion status of the video analysis to an Amazon Simple Notification Service (Amazon SNS) topic. If the video analysis is successful, call [GetFaceSearch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_GeFaceSearch.html) to get the search results. For more information about starting video analysis and getting the results, see [Calling Amazon Rekognition Video operations](api-video.md). 

The following procedure shows how to search a collection for faces that match the faces of people who are detected in a video. The procedure also shows how to get the tracking data for people who are matched in the video. The procedure expands on the code in [Analyzing a video stored in an Amazon S3 bucket with Java or Python (SDK)](video-analyzing-with-sqs.md), which uses an Amazon Simple Queue Service (Amazon SQS) queue to get the completion status of a video analysis request. 

**To search a video for matching faces (SDK)**

1. [Create a collection](create-collection-procedure.md).

1. [Index a face into the collection](add-faces-to-collection-procedure.md).

1. Perform [Analyzing a video stored in an Amazon S3 bucket with Java or Python (SDK)](video-analyzing-with-sqs.md).

1. Add the following code to the class `VideoDetect` that you created in step 3.

------
#### [ 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);
   
      }
   ```

   In the function `main`, replace the lines: 

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

   with:

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

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

   This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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()
   ```

   In the function `main`, replace the lines:

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

   with:

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

------

   If you've already run a video example other than [Analyzing a video stored in an Amazon S3 bucket with Java or Python (SDK)](video-analyzing-with-sqs.md), the code to replace might be different.

1. Change the value of `collection` to the name of the collection you created in step 1.

1. Run the code. A list of people in the video whose faces match those in the input collection is displayed. The tracking data for each matched person is also displayed.

## GetFaceSearch operation response
<a name="searchfacesvideo-operation-response"></a>

The following is an example JSON response from `GetFaceSearch`.

The response includes an array of people (`Persons`) detected in the video whose faces match a face in the input collection. An array element, [PersonMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonMatch.html), exists for each time the person is matched in the video. Each `PersonMatch` includes an array of face matches from the input collection, [FaceMatch](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_FaceMatch.html), information about the matched person, [PersonDetail](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_PersonDetail.html), and the time the person was matched in the video. 

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

# Searching faces in a collection in streaming video
<a name="collections-streaming"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

You can use Amazon Rekognition Video to detect and recognize faces from a collection in streaming video. With Amazon Rekognition Video you can create a stream processor ([CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)) to start and manage the analysis of streaming video. 

To detect a known face in a video stream (face search), Amazon Rekognition Video uses Amazon Kinesis Video Streams to receive and process a video stream. The analysis results are output from Amazon Rekognition Video to a Kinesis data stream and then read by your client application. 

To use Amazon Rekognition Video with streaming video, your application needs to implement the following:
+ A Kinesis video stream for sending streaming video to Amazon Rekognition Video. For more information, see the [Amazon Kinesis Video Streams Developer Guide](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/what-is-kinesis-video.html). 
+ An Amazon Rekognition Video stream processor to manage the analysis of the streaming video. For more information, see [Overview of Amazon Rekognition Video stream processor operations](streaming-video.md#using-rekognition-video-stream-processor).
+ A Kinesis data stream consumer to read the analysis results that Amazon Rekognition Video sends to the Kinesis data stream. For more information, see [Kinesis Data Streams Consumers](https://docs.aws.amazon.com/streams/latest/dev/amazon-kinesis-consumers.html). 

This section contains information about writing an application that creates the Kinesis video stream and other necessary resources, streams video into Amazon Rekognition Video, and receives the analysis results.

**Topics**
+ [Setting up your Amazon Rekognition Video and Amazon Kinesis resources](setting-up-your-amazon-rekognition-streaming-video-resources.md)
+ [Searching faces in a streaming video](rekognition-video-stream-processor-search-faces.md)
+ [Streaming using a GStreamer plugin](streaming-using-gstreamer-plugin.md)
+ [Troubleshooting streaming video](streaming-video-troubleshooting.md)

# Setting up your Amazon Rekognition Video and Amazon Kinesis resources
<a name="setting-up-your-amazon-rekognition-streaming-video-resources"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

 The following procedures describe the steps you take to provision the Kinesis video stream and other resources that are used to recognize faces in a streaming video.

## Prerequisites
<a name="streaming-video-prerequisites"></a>

To run this procedure, you need to have the AWS SDK for Java installed. For more information, see [Getting started with Amazon Rekognition](getting-started.md). The AWS account you use must have access permissions to the Amazon Rekognition API. For more information, see [Actions Defined by Amazon Rekognition](https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonrekognition.html#amazonrekognition-actions-as-permissions) in the *IAM User Guide*. 

**To recognize faces in a video stream (AWS SDK)**

1. If you haven't already, create an IAM service role to give Amazon Rekognition Video access to your Kinesis video streams and your Kinesis data streams. Note the ARN. For more information, see [Giving access to streams using AmazonRekognitionServiceRole](api-streaming-video-roles.md#api-streaming-video-roles-all-stream).

1. [Create a collection](create-collection-procedure.md) and note the collection identifier you used.

1. [Index the faces](add-faces-to-collection-procedure.md) you want to search for into the collection you created in step 2.

1. [Create a Kinesis video stream](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/gs-createstream.html) and note the stream's Amazon Resource Name (ARN).

1. [Create a Kinesis data stream](https://docs.aws.amazon.com/streams/latest/dev/learning-kinesis-module-one-create-stream.html). Prepend the stream name with *AmazonRekognition* and note the stream's ARN.

You can then [create the face search stream processor](rekognition-video-stream-processor-search-faces.md#streaming-video-creating-stream-processor) and [start the stream processor](rekognition-video-stream-processor-search-faces.md#streaming-video-starting-stream-processor) using the stream processor name that you chose.

**Note**  
 You should start the stream processor only after you have verified you can ingest media into the Kinesis video stream. 

## Streaming video into Amazon Rekognition Video
<a name="video-streaming-kinesisvideostreams-stream"></a>

To stream video into Amazon Rekognition Video, you use the Amazon Kinesis Video Streams SDK to create and use a Kinesis video stream. The `PutMedia` operation writes video data *fragments* into a Kinesis video stream that Amazon Rekognition Video consumes. Each video data fragment is typically 2–10 seconds in length and contains a self-contained sequence of video frames. Amazon Rekognition Video supports H.264 encoded videos, which can have three types of frames (I, B, and P). For more information, see [Inter Frame](https://en.wikipedia.org/wiki/Inter_frame). The first frame in the fragment must be an I-frame. An I-frame can be decoded independent of any other frame. 

As video data arrives into the Kinesis video stream, Kinesis Video Streams assigns a unique number to the fragment. For an example, see [PutMedia API Example](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-putmedia.html).
+  If you are streaming from an Matroska (MKV) encoded source, use the [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) operation to stream the source video into the Kinesis video stream that you created. For more information, see [PutMedia API Example](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-putmedia.html). 
+  If you are streaming from a device camera, see [Streaming using a GStreamer plugin](streaming-using-gstreamer-plugin.md).

# Giving Amazon Rekognition Video access to your resources
<a name="api-streaming-video-roles"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

You use an AWS Identity and Access Management (IAM) service role to give Amazon Rekognition Video read access to Kinesis video streams. If you are using a face search stream processor, you use an IAM service role to give Amazon Rekognition Video write access to Kinesis data streams. If you are using a security monitoring stream processor, you use IAM roles to give Amazon Rekognition Video access to your Amazon S3 bucket and to an Amazon SNS topic.

## Giving access for face search stream processors
<a name="api-streaming-video-roles-single-stream"></a>

You can create a permissions policy that allows Amazon Rekognition Video access to individual Kinesis video streams and Kinesis data streams.

**To give Amazon Rekognition Video access for a face search stream processor**

1. [ Create a new permissions policy with the IAM JSON policy editor](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor), and use the following policy. Replace `video-arn` with the ARN of the desired Kinesis video stream. If you are using a face search stream processor, replace `data-arn` with the ARN of the desired Kinesis data stream.

1. [Create an IAM service role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console), or update an existing IAM service role. Use the following information to create the IAM service role:

   1. Choose **Rekognition** for the service name.

   1. Choose **Rekognition** for the service role use case.

   1. Attach the permissions policy that you created in step 1.

1. Note the ARN of the service role. You need it to start video analysis operations.

## Giving access to streams using AmazonRekognitionServiceRole
<a name="api-streaming-video-roles-all-stream"></a>

 As an alternative option for setting up access to Kinesis video streams and data streams, you can use the `AmazonRekognitionServiceRole` permissions policy. IAM provides the *Rekognition* service role use case that, when used with the `AmazonRekognitionServiceRole` permissions policy, can write to multiple Kinesis data streams and read from all your Kinesis video streams. To give Amazon Rekognition Video write access to multiple Kinesis data streams, you can prepend the names of the Kinesis data streams with *AmazonRekognition*—for example, `AmazonRekognitionMyDataStreamName`. 

**To give Amazon Rekognition Video access to your Kinesis video stream and Kinesis data stream**

1. [Create an IAM service role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html?icmpid=docs_iam_console). Use the following information to create the IAM service role:

   1. Choose **Rekognition** for the service name.

   1. Choose **Rekognition** for the service role use case.

   1. Choose the **AmazonRekognitionServiceRole** permissions policy, which gives Amazon Rekognition Video write access to Kinesis data streams that are prefixed with *AmazonRekognition* and read access to all your Kinesis video streams.

1. To ensure your AWS account is secure, limit the scope of Rekognition's access to just the resources you are using. This can be done by attaching a trust policy to your IAM service role. For information on how to do this, see [Cross-service confused deputy prevention](cross-service-confused-deputy-prevention.md).

1. Note the Amazon Resource Name (ARN) of the service role. You need it to start video analysis operations.

# Searching faces in a streaming video
<a name="rekognition-video-stream-processor-search-faces"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

Amazon Rekognition Video can search faces in a collection that match faces that are detected in a streaming video. For more information about collections, see [Searching faces in a collection](collections.md).

**Topics**
+ [Creating the Amazon Rekognition Video face search stream processor](#streaming-video-creating-stream-processor)
+ [Starting the Amazon Rekognition Video face search stream processor](#streaming-video-starting-stream-processor)
+ [Using stream processors for face searching (Java V2 example)](#using-stream-processors-v2)
+ [Using stream processors for face searching (Java V1 example)](#using-stream-processors)
+ [Reading streaming video analysis results](streaming-video-kinesis-output.md)
+ [Displaying Rekognition results with Kinesis Video Streams locally](displaying-rekognition-results-locally.md)
+ [Understanding the Kinesis face recognition JSON frame record](streaming-video-kinesis-output-reference.md)

The following diagram shows how Amazon Rekognition Video detects and recognizes faces in a streaming video.

![\[Diagram of workflow for using Amazon Rekognition Video to process video streams from Amazon Kinesis.\]](http://docs.aws.amazon.com/rekognition/latest/dg/images/VideoRekognitionStream.png)


## Creating the Amazon Rekognition Video face search stream processor
<a name="streaming-video-creating-stream-processor"></a>

Before you can analyze a streaming video, you create an Amazon Rekognition Video stream processor ([CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html)). The stream processor contains information about the Kinesis data stream and the Kinesis video stream. It also contains the identifier for the collection that contains the faces you want to recognize in the input streaming video. You also specify a name for the stream processor. The following is a JSON example for the `CreateStreamProcessor` request.

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

The following is an example response from `CreateStreamProcessor`.

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

## Starting the Amazon Rekognition Video face search stream processor
<a name="streaming-video-starting-stream-processor"></a>

You start analyzing streaming video by calling [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html) with the stream processor name that you specified in `CreateStreamProcessor`. The following is a JSON example for the `StartStreamProcessor` request.

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

If the stream processor successfully starts, an HTTP 200 response is returned, along with an empty JSON body.

## Using stream processors for face searching (Java V2 example)
<a name="using-stream-processors-v2"></a>

The following example code shows how to call various stream processor operations, such as [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) and [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html), using the AWS SDK for Java version 2.

This code is taken from the AWS Documentation SDK examples GitHub repository. See the full example [here](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.");
    }
}
```

## Using stream processors for face searching (Java V1 example)
<a name="using-stream-processors"></a>

The following example code shows how to call various stream processor operations, such as [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html) and [StartStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_StartStreamProcessor.html), using Java V1. The example includes a stream processor manager class (StreamManager) that provides methods to call stream processor operations. The starter class (Starter) creates a StreamManager object and calls various operations. 

**To configure the example:**

1. Set the values of the Starter class member fields to your desired values.

1. In the Starter class function `main`, uncomment the desired function call.

### Starter class
<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 class
<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());
        }
    }
}
```

# Reading streaming video analysis results
<a name="streaming-video-kinesis-output"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

You can use the Amazon Kinesis Data Streams Client Library to consume analysis results that are sent to the Amazon Kinesis Data Streams output stream. For more information, see [Reading Data from a Kinesis Data Stream](https://docs.aws.amazon.com/streams/latest/dev/building-consumers.html). Amazon Rekognition Video places a JSON frame record for each analyzed frame into the Kinesis output stream. Amazon Rekognition Video doesn't analyze every frame that's passed to it through the Kinesis video stream. 

A frame record that's sent to a Kinesis data stream contains information about which Kinesis video stream fragment the frame is in, where the frame is in the fragment, and faces that are recognized in the frame. It also includes status information for the stream processor. For more information, see [Understanding the Kinesis face recognition JSON frame record](streaming-video-kinesis-output-reference.md).

The Amazon Kinesis Video Streams Parser Library contains example tests that consume Amazon Rekognition Video results and integrates it with the original Kinesis video stream. For more information, see [Displaying Rekognition results with Kinesis Video Streams locally](displaying-rekognition-results-locally.md).

Amazon Rekognition Video streams Amazon Rekognition Video analysis information to the Kinesis data stream. The following is a JSON example for a single record. 

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

In the JSON example, note the following:
+ **InputInformation** – Information about the Kinesis video stream that's used to stream video into Amazon Rekognition Video. For more information, see [InputInformation](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-inputinformation).
+ **StreamProcessorInformation** – Status information for the Amazon Rekognition Video stream processor. The only possible value for the `Status` field is RUNNING. For more information, see [StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md).
+ **FaceSearchResponse** – Contains information about faces in the streaming video that match faces in the input collection. [FaceSearchResponse](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facesearchresponse) contains a [DetectedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-detectedface) object, which is a face that was detected in the analyzed video frame. For each detected face, the array `MatchedFaces` contains an array of matching face objects ([MatchedFace](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-facematch)) found in the input collection, along with a similarity score. 

## Mapping the Kinesis video stream to the Kinesis data stream
<a name="mapping-streams"></a>

You might want to map the Kinesis video stream frames to the analyzed frames that are sent to the Kinesis data stream. For example, during the display of a streaming video, you might want to display boxes around the faces of recognized people. The bounding box coordinates are sent as part of the Kinesis Face Recognition Record to the Kinesis data stream. To display the bounding box correctly, you need to map the time information that's sent with the Kinesis Face Recognition Record with the corresponding frames in the source Kinesis video stream.

The technique that you use to map the Kinesis video stream to the Kinesis data stream depends on if you're streaming live media (such as a live streaming video), or if you're streaming archived media (such as a stored video).

### Mapping when you're streaming live media
<a name="mapping-streaming-video"></a>

**To map a Kinesis video stream frame to a Kinesis data stream frame**

1. Set the input parameter `FragmentTimeCodeType` of the [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) operation to `RELATIVE`. 

1. Call `PutMedia` to deliver live media into the Kinesis video stream.

1. When you receive a Kinesis Face Recognition Record from the Kinesis data stream, store the values of `ProducerTimestamp` and `FrameOffsetInSeconds` from the [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) field.

1. Calculate the time stamp that corresponds to the Kinesis video stream frame by adding the `ProducerTimestamp` and `FrameOffsetInSeconds` field values together. 

### Mapping when you're streaming archived media
<a name="map-stored-video"></a>

**To map a Kinesis video stream frame to a Kinesis data stream frame**

1. Call [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html) to deliver archived media into the Kinesis video stream.

1. When you receive an `Acknowledgement` object from the `PutMedia` operation response, store the `FragmentNumber` field value from the [Payload](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html#API_dataplane_PutMedia_ResponseSyntax) field. `FragmentNumber` is the fragment number for the MKV cluster. 

1. When you receive a Kinesis Face Recognition Record from the Kinesis data stream, store the `FrameOffsetInSeconds` field value from the [KinesisVideo](streaming-video-kinesis-output-reference.md#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) field. 

1. Calculate the mapping by using the `FrameOffsetInSeconds` and `FragmentNumber` values that you stored in steps 2 and 3. `FrameOffsetInSeconds` is the offset into the fragment with the specific `FragmentNumber` that's sent to the Amazon Kinesis data stream. For more information about getting the video frames for a given fragment number, see [Amazon Kinesis Video Streams Archived Media](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_Operations_Amazon_Kinesis_Video_Streams_Archived_Media.html).

# Displaying Rekognition results with Kinesis Video Streams locally
<a name="displaying-rekognition-results-locally"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

 You can see the results of Amazon Rekognition Video displayed in your feed from Amazon Kinesis Video Streams using the Amazon Kinesis Video Streams Parser Library’s example tests provided at [KinesisVideo - Rekognition Examples](https://github.com/aws/amazon-kinesis-video-streams-parser-library#kinesisvideo---rekognition-examples). The `KinesisVideoRekognitionIntegrationExample` displays bounding boxes over detected faces and renders the video locally through JFrame. This process assumes you have successfully connected a media input from a device camera to a Kinesis video stream and started an Amazon Rekognition Stream Processor. For more information, see [Streaming using a GStreamer plugin](streaming-using-gstreamer-plugin.md). 

## Step 1: Installing Kinesis Video Streams Parser Library
<a name="step-1-install-parser-library"></a>

 To create a directory and download the Github repository, run the following command: 

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

 Navigate to the library directory and run the following Maven command to perform a clean installation: 

```
$ mvn clean install
```

## Step 2: Configuring the Kinesis Video Streams and Rekognition integration example test
<a name="step-2-configure-kinesis-video-rekognition-example-test"></a>

 Open the `KinesisVideoRekognitionIntegrationExampleTest.java` file. Remove the `@Ignore` right after the class header. Populate the data fields with the information from your Amazon Kinesis and Amazon Rekognition resources. For more information, see [Setting up your Amazon Rekognition Video and Amazon Kinesis resources](setting-up-your-amazon-rekognition-streaming-video-resources.md). If you are streaming video to your Kinesis video stream, remove the `inputStream` parameter. 

 See the following code example: 

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

## Step 3: Running the Kinesis Video Streams and Rekognition integration example test
<a name="step-3-run-kinesis-video-rekognition-example-test"></a>

 Ensure that your Kinesis video stream is receiving media input if you are streaming to it and start analyzing your stream with an Amazon Rekognition Video Stream Processor running. For more information, see [Overview of Amazon Rekognition Video stream processor operations](streaming-video.md#using-rekognition-video-stream-processor). Run the `KinesisVideoRekognitionIntegrationExampleTest` class as a JUnit test. After a short delay, a new window opens with a video feed from your Kinesis video stream with bounding boxes drawn over detected faces. 

**Note**  
 The faces in the collection used in this example must have External Image Id (the file name) specified in this format in order for bounding box labels to display meaningful text: PersonName1-Trusted, PersonName2-Intruder, PersonName3-Neutral, etc. The labels can also be color-coded and are customizable in the FaceType.java file. 

# Understanding the Kinesis face recognition JSON frame record
<a name="streaming-video-kinesis-output-reference"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

Amazon Rekognition Video can recognize faces in a streaming video. For each analyzed frame, Amazon Rekognition Video outputs a JSON frame record to a Kinesis data stream. Amazon Rekognition Video doesn't analyze every frame that's passed to it through the Kinesis video stream. 

The JSON frame record contains information about the input and output stream, the status of the stream processor, and information about faces that are recognized in the analyzed frame. This section contains reference information for the JSON frame record.

The following is the JSON syntax for a Kinesis data stream record. For more information, see [Working with streaming video events](streaming-video.md).

**Note**  
The Amazon Rekognition Video API works by comparing the faces in your input stream to a collection of faces, and returning the closest found matches, along with a similarity score.

```
{
    "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 record
<a name="streaming-video-kinesis-output-reference-processorresult"></a>

The JSON record includes information about a frame that's processed by Amazon Rekognition Video. The record includes information about the streaming video, the status for the analyzed frame, and information about faces that are recognized in the frame.

**InputInformation**

Information about the Kinesis video stream that's used to stream video into Amazon Rekognition Video.

Type: [InputInformation](#streaming-video-kinesis-output-reference-inputinformation) object

**StreamProcessorInformation**

Information about the Amazon Rekognition Video stream processor. This includes status information for the current status of the stream processor.

Type: [StreamProcessorInformation](streaming-video-kinesis-output-reference-streamprocessorinformation.md) object 

**FaceSearchResponse**

Information about the faces detected in a streaming video frame and the matching faces found in the input collection.

Type: [FaceSearchResponse](#streaming-video-kinesis-output-reference-facesearchresponse) object array

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

Information about a source video stream that's used by Amazon Rekognition Video. For more information, see [Working with streaming video events](streaming-video.md).

**KinesisVideo**

Type: [KinesisVideo](#streaming-video-kinesis-output-reference-kinesisvideostreams-kinesisvideo) object

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

Information about the Kinesis video stream that streams the source video into Amazon Rekognition Video. For more information, see [Working with streaming video events](streaming-video.md).

**StreamArn**

The Amazon Resource Name (ARN) of the Kinesis video stream.

Type: String 

**FragmentNumber**

The fragment of streaming video that contains the frame that this record represents.

Type: String

**ProducerTimestamp**

The producer-side Unix time stamp of the fragment. For more information, see [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html).

Type: Number

**ServerTimestamp**

The server-side Unix time stamp of the fragment. For more information, see [PutMedia](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html).

Type: Number

**FrameOffsetInSeconds**

The offset of the frame (in seconds) inside the fragment.

Type: Number 

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

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

Status information about the stream processor.

**Status**

The current status of the stream processor. The one possible value is RUNNING.

Type: String

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

Information about a face detected in a streaming video frame and the faces in a collection that match the detected face. You specify the collection in a call to [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html). For more information, see [Working with streaming video events](streaming-video.md). 

**DetectedFace**

Face details for a face detected in an analyzed video frame.

Type: [DetectedFace](#streaming-video-kinesis-output-reference-detectedface) object

**MatchedFaces**

An array of face details for faces in a collection that matches the face detected in `DetectedFace`.

Type: [MatchedFace](#streaming-video-kinesis-output-reference-facematch) object array

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

Information about a face that's detected in a streaming video frame. Matching faces in the input collection are available in [MatchedFace](#streaming-video-kinesis-output-reference-facematch) object field.

**BoundingBox**

The bounding box coordinates for a face that's detected within an analyzed video frame. The BoundingBox object has the same properties as the BoundingBox object that's used for image analysis.

Type: [BoundingBox](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_BoundingBox.html) object 

**Confidence**

The confidence level (1-100) that Amazon Rekognition Video has that the detected face is actually a face. 1 is the lowest confidence, 100 is the highest.

Type: Number

**Landmarks**

An array of facial landmarks.

Type: [Landmark](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Landmark.html) object array

**Pose**

Indicates the pose of the face as determined by its pitch, roll, and yaw.

Type: [Pose](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Pose.html) object

**Quality**

Identifies face image brightness and sharpness. 

Type: [ImageQuality](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_ImageQuality.html) object

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

Information about a face that matches a face detected in an analyzed video frame.

**Face**

Face match information for a face in the input collection that matches the face in the [DetectedFace](#streaming-video-kinesis-output-reference-detectedface) object. 

Type: [Face](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_Face.html) object 

**Similarity**

The level of confidence (1-100) that the faces match. 1 is the lowest confidence, 100 is the highest.

Type: Number 

# Streaming using a GStreamer plugin
<a name="streaming-using-gstreamer-plugin"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

Amazon Rekognition Video can analyze a live streaming video from a device camera. To access media input from a device source, you need to install GStreamer. GStreamer is a third-party multimedia framework software that connects media sources and processing tools together in workflow pipelines. You also need to install the [Amazon Kinesis Video Streams Producer Plugin](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/) for Gstreamer. This process assumes that you have successfully set up your Amazon Rekognition Video and Amazon Kinesis resources. For more information, see [Setting up your Amazon Rekognition Video and Amazon Kinesis resources](setting-up-your-amazon-rekognition-streaming-video-resources.md).

## Step 1: Install Gstreamer
<a name="step-1-install-gstreamer"></a>

 Download and install Gstreamer, a third-party multi-media platform software. You can use a package management software like Homebrew ([Gstreamer on Homebrew](https://formulae.brew.sh/formula/gstreamer)) or get it directly from the [Freedesktop website](https://gstreamer.freedesktop.org/download/). 

 Verify the successful installation of Gstreamer by launching a video feed with a test source from your command line terminal. 

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

## Step 2: Install the Kinesis Video Streams Producer plugin
<a name="step-2-install-kinesis-video-plugin"></a>

 In this section, you will download the [ Amazon Kinesis Video Streams Producer Library](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/) and install the Kinesis Video Streams Gstreamer plugin. 

 Create a directory and clone the source code from the Github repository. Be sure to include the `--recursive` parameter. 

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

Follow the [instructions provided by the library](https://github.com/awslabs/amazon-kinesis-video-streams-producer-sdk-cpp/blob/master/README.md) to configure and build the project. Make sure you use the platform-specific commands for your operating system. Use the `-DBUILD_GSTREAMER_PLUGIN=ON` parameter when you run `cmake` to install the Kinesis Video Streams Gstreamer plugin. This project requires the following additional packages that are included in the installation: GCC or Clang, Curl, Openssl and Log4cplus. If your build fails because of a missing package, verify that the package is installed and in your PATH. If you encounter a "can’t run C compiled program" error while building, run the build command again. Sometimes, the correct C compiler is not found. 

 Verify the installation of the Kinesis Video Streams plugin by running the following command. 

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

 The following information, such as factory and plugin details, should appear: 

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

## Step 3: Run Gstreamer with the Kinesis Video Streams plugin
<a name="step-3-run-gstreamer-with-kinesis-video-plugin"></a>

 Before you begin streaming from a device camera to Kinesis Video Streams, you might need to convert the media source to an acceptable codec for Kinesis Video Streams. To determine the specifications and format capabilities of devices currently connected to your machine, run the following command.

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

 To begin streaming, launch Gstreamer with the following sample command and add your credentials and Amazon Kinesis Video Streams information. You should use the access keys and region for the IAM service role you created while [giving Amazon Rekognition access to your Kinesis streams](https://docs.aws.amazon.com/rekognition/latest/dg/api-streaming-video-roles.html#api-streaming-video-roles-all-stream). For more information on access keys, see [Managing Access Keys for IAM Users](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) in the *IAM User Guide*. Also, you may adjust the video format argument parameters as required by your usage and available from your device. 

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

 For more launch commands, see [Example GStreamer Launch Commands](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/examples-gstreamer-plugin.html#examples-gstreamer-plugin-launch). 

**Note**  
 If your launch command terminates with a non-negotiation error, check the output from the Device Monitor and make sure that the `videoconvert` parameter values are valid capabilities of your device. 

 You will see a video feed from your device camera on your Kinesis video stream after a few seconds. To begin detecting and matching faces with Amazon Rekognition, start your Amazon Rekognition Video stream processor. For more information, see [Overview of Amazon Rekognition Video stream processor operations](streaming-video.md#using-rekognition-video-stream-processor). 

# Troubleshooting streaming video
<a name="streaming-video-troubleshooting"></a>

**Note**  
Amazon Rekognition Streaming Video Analysis will no longer be open to new customers starting April 30, 2026. If you would like to use Streaming Video Analysis, sign up prior to that date. Existing customers for accounts that have used this feature within the last 12 months can continue to use the service as normal. For more information, see [Rekognition Streaming Video Analysis availability change](https://docs.aws.amazon.com/rekognition/latest/dg/rekognition-streaming-video-analysis-availability-change.html). 

This topic provides troubleshooting information for using Amazon Rekognition Video with streaming videos.

**Topics**
+ [I don't know if my stream processor was successfully created](#ts-streaming-video-create-sp)
+ [I don't know if I've configured my stream processor correctly](#ts-configured-sp)
+ [My stream processor isn't returning results](#ts-streaming-video-no-results-from-sp)
+ [The state of my stream processor is FAILED](#ts-failed-state)
+ [My stream processor isn't returning the expected results](#w2aac27c79c29c17)

## I don't know if my stream processor was successfully created
<a name="ts-streaming-video-create-sp"></a>

Use the following AWS CLI command to get a list of stream processors and their current status.

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

You can get additional details by using the following AWS CLI command. Replace `stream-processor-name` with the name of the required stream processor.

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

## I don't know if I've configured my stream processor correctly
<a name="ts-configured-sp"></a>

If your code isn't outputting the analysis results from Amazon Rekognition Video, your stream processor might not be configured correctly. Do the following to confirm that your stream processor is configured correctly and able to produce results.

**To determine if your solution is configured correctly**

1. Run the following command to confirm that your stream processor is in the running state. Change `stream-processor-name` to the name of your stream processor. The stream processor is running if the value of `Status` is `RUNNING`. If the status is `RUNNING` and you aren't getting results, see [My stream processor isn't returning results](#ts-streaming-video-no-results-from-sp). If the status is `FAILED`, see [The state of my stream processor is FAILED](#ts-failed-state).

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

1. If your stream processor is running, run the following Bash or PowerShell command to read data from the output Kinesis data stream. 

   **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. Use the [Decode tool](https://www.base64decode.org/) on the Base64 Decode website to decode the output into a human-readable string. For more information, see [Step 3: Get the Record](https://docs.aws.amazon.com/streams/latest/dev/fundamental-stream.html#get-records).

1. If the commands work and you see face detection results in the Kinesis data stream, then your solution is properly configured. If the command fails, check the other troubleshooting suggestions and see [Giving Amazon Rekognition Video access to your resources](api-streaming-video-roles.md).

Alternatively, you can use the "kinesis-process-record" AWS Lambda blueprint to log messages from the Kinesis data stream to CloudWatch for continuous visualization. This incurs additional costs for AWS Lambda and CloudWatch. 

## My stream processor isn't returning results
<a name="ts-streaming-video-no-results-from-sp"></a>

Your stream processor might not return results for several reasons. 

### Reason 1: Your stream processor isn't configured correctly
<a name="w2aac27c79c29c13b5"></a>

Your stream processor might not be configured correctly. For more information, see [I don't know if I've configured my stream processor correctly](#ts-configured-sp).

### Reason 2: Your stream processor isn't in the RUNNING state
<a name="w2aac27c79c29c13b7"></a>

**To troubleshoot the status of a stream processor**

1. Check the status of the stream processor with the following AWS CLI command.

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

1. If the value of `Status` is `STOPPED`, start your stream processor with the following command:

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

1. If the value of `Status` is `FAILED`, see [The state of my stream processor is FAILED](#ts-failed-state).

1. If the value of `Status` is `STARTING`, wait for 2 minutes and check the status by repeating step 1. If the value of Status is still `STARTING`, do the following:

   1. Delete the stream processor with the following command.

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

   1. Create a new stream processor with the same configuration. For more information, see [Working with streaming video events](streaming-video.md).

   1. If you're still having problems, contact AWS Support.

1. If the value of `Status` is `RUNNING`, see [Reason 3: There isn't active data in the Kinesis video stream](#ts-no-data).

### Reason 3: There isn't active data in the Kinesis video stream
<a name="ts-no-data"></a>

**To check if there's active data in the Kinesis video stream**

1. Sign in to the AWS Management Console, and open the Amazon Kinesis Video Streams console at [https://console.aws.amazon.com/kinesisvideo/](https://console.aws.amazon.com/kinesisvideo/).

1. Select the Kinesis video stream that's the input for the Amazon Rekognition stream processor.

1. If the preview states **No data on stream**, then there's no data in the input stream for Amazon Rekognition Video to process.

For information about producing video with Kinesis Video Streams, see [Kinesis Video Streams Producer Libraries](https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk.html). 

## The state of my stream processor is FAILED
<a name="ts-failed-state"></a>

You can check the state of a stream processor by using the following AWS CLI command.

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

If the value of Status is FAILED, check the troubleshooting information for the following error messages.

### Error: "Access denied to Role"
<a name="w2aac27c79c29c15b9"></a>

The IAM role that's used by the stream processor doesn't exist or Amazon Rekognition Video doesn't have permission to assume the role.

**To troubleshoot access to the IAM role**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. From the left navigation pane, choose **Roles**and confirm that the role exists. 

1. If the role exists, check that the role has the *AmazonRekognitionServiceRole* permissions policy.

1. If the role doesn't exist or doesn't have the right permissions, see [Giving Amazon Rekognition Video access to your resources](api-streaming-video-roles.md).

1. Start the stream processor with the following AWS CLI command.

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

### Error: "Access denied to Kinesis Video *or* Access denied to Kinesis Data"
<a name="w2aac27c79c29c15c11"></a>

The role doesn't have access to the Kinesis Video Streams API operations `GetMedia` and `GetDataEndpoint`. It also might not have access to the Kinesis Data Streams API operations `PutRecord` and `PutRecords`. 

**To troubleshoot API permissions**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Open the role and make sure that it has the following permissions policy attached.

1. If any of the permissions are missing, update the policy. For more information, see [Giving Amazon Rekognition Video access to your resources](api-streaming-video-roles.md).

### Error: "Stream *input-video-stream-name* doesn't exist"
<a name="w2aac27c79c29c15c13"></a>

The Kinesis video stream input to the stream processor doesn't exist or isn't configured correctly. 

**To troubleshoot the Kinesis video stream**

1. Use the following command to confirm that the stream exists. 

   ```
   aws kinesisvideo list-streams
   ```

1. If the stream exists, check the following.
   + The Amazon Resource Name (ARN) is same as the ARN of the input stream for the stream processor.
   + The Kinesis video stream is in the same Region as the stream processor.

   If the stream processor isn't configured correctly, delete it with the following AWS CLI command.

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

1. Create a new stream processor with the intended Kinesis video stream. For more information, see [Creating the Amazon Rekognition Video face search stream processor](rekognition-video-stream-processor-search-faces.md#streaming-video-creating-stream-processor).

### Error: "Collection not found"
<a name="w2aac27c79c29c15c15"></a>

The Amazon Rekognition collection that's used by the stream processor to match faces doesn't exist, or the wrong collection is being used.

**To confirm the collection**

1. Use the following AWS CLI command to determine if the required collection exists. Change `region` to the AWS Region in which you're running your stream processor.

   ```
   aws rekognition list-collections --region region
   ```

   If the required collection doesn't exist, create a new collection and add face information. For more information, see [Searching faces in a collection](collections.md).

1. In your call to [CreateStreamProcessor](https://docs.aws.amazon.com/rekognition/latest/APIReference/API_CreateStreamProcessor.html), check that the value of the `CollectionId` input parameter is correct.

1. Start the stream processor with the following AWS CLI command.

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

### Error: "Stream *output-kinesis-data-stream-name* under account *account-id* not found"
<a name="w2aac27c79c29c15c17"></a>

The output Kinesis data stream that's used by the stream processor doesn't exist in your AWS account or isn't in the same AWS Region as your stream processor.

**To troubleshoot the Kinesis data stream**

1. Use the following AWS CLI command to determine if the Kinesis data stream exists. Change `region` to the AWS Region in which you're using your stream processor.

   ```
   aws kinesis list-streams --region region
   ```

1. If the Kinesis data stream exists, check that the Kinesis data stream name is same as the name of the output stream that's used by the stream processor.

1. If the Kinesis data stream doesn't exist, it might exist in another AWS Region. The Kinesis data stream must be in the same Region as the stream processor.

1. If necessary, create a new Kinesis data stream. 

   1. Create a Kinesis data stream with the same name as the name used by the stream processor. For more information, see [ Step 1: Create a Data Stream](https://docs.aws.amazon.com/streams/latest/dev/learning-kinesis-module-one-create-stream.html).

   1. Start the stream processor with the following AWS CLI command.

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

## My stream processor isn't returning the expected results
<a name="w2aac27c79c29c17"></a>

If your stream processor isn't returning the expected face matches, use the following information.
+ [Searching faces in a collection](collections.md)
+ [Recommendations for camera setup (streaming video)](recommendations-camera-streaming-video.md)