Can't connect to AWS rekognition API from IntelliJ

1.2k views Asked by At

I've been playing with the new rekognition API from Amazon and I am having trouble running their example Java application from IntelliJ. I'm using Maven to build the project and have included the AWS SDK in my pom.xml as follows:

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>${aws-java-sdk.version}</version>
</dependency>

From what I can tell, my application seems to be failing somewhere around here:

AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(credentials)
        .withEndpoint("s3-us-west-2.amazonaws.com");
rekognitionClient.setSignerRegionOverride("us-west-2");
try {
    DetectFacesResult result = rekognitionClient.detectFaces(request);
    ObjectMapper objectMapper = new ObjectMapper();
    System.out.println("Result = " + objectMapper.writeValueAsString(result));
} catch (AmazonRekognitionException e) {
    e.printStackTrace();
}

...And the error that I'm getting is:

com.amazonaws.services.rekognition.model.AmazonRekognitionException: null (Service: AmazonRekognition; Status Code: 400; Error Code: null; Request ID: null)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1545)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1183)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:964)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:676)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:650)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:633)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$300(AmazonHttpClient.java:601)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:583)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:447)
    at com.amazonaws.services.rekognition.AmazonRekognitionClient.doInvoke(AmazonRekognitionClient.java:1130)
    at com.amazonaws.services.rekognition.AmazonRekognitionClient.invoke(AmazonRekognitionClient.java:1106)
    at com.amazonaws.services.rekognition.AmazonRekognitionClient.detectFaces(AmazonRekognitionClient.java:599)
    at com.github.jhenningsgaard.DetectFaces.main(DetectFaces.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

I should also note that I ran the operation (see below) in AWS CLI and was successful.

aws rekognition detect-faces \
--image '{"S3Object":{"Bucket":"Bucketname","Name":"s3ObjectKey"}}' \
--attributes "ALL" \
--region us-east-1 \
--profile adminuser
2

There are 2 answers

1
siom On

You can use the following code to create an instance of the rekognition client:

AWSCredentials credentials;
try {
    credentials = new ProfileCredentialsProvider("default").getCredentials();
} catch (Exception e) {
    throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
            + "Please make sure that your credentials file is at the correct "
            + "location (/Users/<userid>/.aws/credentials), and is in a valid format.", e);
}
AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(credentials)
        .withEndpoint("rekognition.eu-west-1.amazonaws.com");
rekognitionClient.setSignerRegionOverride("eu-west-1");
0
smac2020 On

Here is a full code example of using the software.amazon.awssdk.services.rekognition.RekognitionClient Object (which is Version 2 of the API) to compare two faces.

You can find more examples of using Version 2 of the RekognitionClient in the AWS Docs.

Also to run these examples from IntelliJ, you need to ensure that you have the correct POM. In the AWS Github examples, the corresponding POM is always listed.

package com.example.rekognition;

// snippet-start:[rekognition.java2.compare_faces.import]
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.Image;
import software.amazon.awssdk.services.rekognition.model.CompareFacesRequest;
import software.amazon.awssdk.services.rekognition.model.CompareFacesResponse;
import software.amazon.awssdk.services.rekognition.model.CompareFacesMatch;
import software.amazon.awssdk.services.rekognition.model.ComparedFace;
import software.amazon.awssdk.services.rekognition.model.BoundingBox;
import software.amazon.awssdk.core.SdkBytes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
// snippet-end:[rekognition.java2.compare_faces.import]


public class CompareFaces {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "CompareFaces - how to compare two faces in two images\n\n" +
                "Usage: CompareFaces <pathSource> <pathTarget>\n\n" +
                "Where:\n" +
                "pathSource - the path to the source image (ie, C:\\AWS\\pic1.png) \n " +
                "pathTarget - the path to the target image (ie, C:\\AWS\\pic2.png) \n\n";

        Float similarityThreshold = 70F;
        String sourceImage = args[0];
        String targetImage = args[1];

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

        compareTwoFaces(rekClient, similarityThreshold, sourceImage, targetImage);
   }

    // snippet-start:[rekognition.java2.compare_faces.main]
    public static void compareTwoFaces(RekognitionClient rekClient, Float similarityThreshold, String sourceImage, String targetImage) {

        try {
            InputStream sourceStream = new FileInputStream(new File(sourceImage));
            InputStream tarStream = new FileInputStream(new File(targetImage));

            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
            SdkBytes targetBytes = SdkBytes.fromInputStream(tarStream);

            // Create an Image object for the source image
            Image souImage = Image.builder()
            .bytes(sourceBytes)
            .build();

            // Create an Image object for the target image
            Image tarImage = Image.builder()
                    .bytes(targetBytes)
                    .build();

            // Create a CompareFacesRequest object
            CompareFacesRequest facesRequest = CompareFacesRequest.builder()
                    .sourceImage(souImage)
                    .targetImage(tarImage)
                    .similarityThreshold(similarityThreshold)
                    .build();

            // Compare the two images
            CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest);

            // Display results
            List<CompareFacesMatch> faceDetails = compareFacesResult.faceMatches();
            for (CompareFacesMatch match: faceDetails){
                ComparedFace face= match.face();
                BoundingBox position = face.boundingBox();
                System.out.println("Face at " + position.left().toString()
                        + " " + position.top()
                        + " matches with " + face.confidence().toString()
                        + "% confidence.");

            }
            List<ComparedFace> uncompared = compareFacesResult.unmatchedFaces();

            System.out.println("There was " + uncompared.size()
                    + " face(s) that did not match");
            System.out.println("Source image rotation: " + compareFacesResult.sourceImageOrientationCorrection());
            System.out.println("target image rotation: " + compareFacesResult.targetImageOrientationCorrection());

        } catch(RekognitionException | FileNotFoundException e) {
            System.out.println("Failed to load source image " + sourceImage);
            System.exit(1);
        }
        // snippet-end:[rekognition.java2.compare_faces.main]
    }
}

You can find full examples for Java V2 here: https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/rekognition