Aws-sdk-android: AWS Rekognition Android Sample code

Created on 9 Jan 2019  路  10Comments  路  Source: aws-amplify/aws-sdk-android

I am not able to find the sample code for the face compare feature provided by AWS Rekognition in Android.

AWS Rekognition

Needs Info from Requester Rekognition Usage Question closing-soon-if-no-response

Most helpful comment

@VirRajpurohit Thank you for reporting to us.

Add the following in build.gradle

dependencies {
    implementation 'com.amazonaws:aws-android-sdk-rekognition:2.10.0'
}
public void compareFaces() {
        Float similarityThreshold = 70F;
        String sourceImage = "source.jpg";
        String targetImage = "target.jpg";
        ByteBuffer sourceImageBytes = null;
        ByteBuffer targetImageBytes = null;

        AmazonRekognition rekognitionClient = new AmazonRekognitionClient(new BasicAWSCredentials("", ""));


        //Load source and target images and create input parameters
        try (InputStream inputStream = new FileInputStream(new File(sourceImage))) {
            sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
        }
        catch(Exception e)
        {
            System.out.println("Failed to load source image " + sourceImage);
            System.exit(1);
        }
        try (InputStream inputStream = new FileInputStream(new File(targetImage))) {
            targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
        }
        catch(Exception e)
        {
            System.out.println("Failed to load target images: " + targetImage);
            System.exit(1);
        }

        Image source = new Image()
                .withBytes(sourceImageBytes);
        Image target = new Image()
                .withBytes(targetImageBytes);

        CompareFacesRequest request = new CompareFacesRequest()
                .withSourceImage(source)
                .withTargetImage(target)
                .withSimilarityThreshold(similarityThreshold);

        // Call operation
        CompareFacesResult compareFacesResult = rekognitionClient.compareFaces(request);


        // Display results
        List <CompareFacesMatch> faceDetails = compareFacesResult.getFaceMatches();
        for (CompareFacesMatch match: faceDetails){
            ComparedFace face= match.getFace();
            BoundingBox position = face.getBoundingBox();
            System.out.println("Face at " + position.getLeft().toString()
                    + " " + position.getTop()
                    + " matches with " + face.getConfidence().toString()
                    + "% confidence.");

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

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

Be sure to use import com.amazonaws.services.rekognition.model.Image; for the Image class referenced in the code and not the Image from android.media.

Also you have to change the file path to suit your app needs based on where the file is located (Internal Storage or SD card).

All 10 comments

@VirRajpurohit Thank you for reporting to us.

Add the following in build.gradle

dependencies {
    implementation 'com.amazonaws:aws-android-sdk-rekognition:2.10.0'
}
public void compareFaces() {
        Float similarityThreshold = 70F;
        String sourceImage = "source.jpg";
        String targetImage = "target.jpg";
        ByteBuffer sourceImageBytes = null;
        ByteBuffer targetImageBytes = null;

        AmazonRekognition rekognitionClient = new AmazonRekognitionClient(new BasicAWSCredentials("", ""));


        //Load source and target images and create input parameters
        try (InputStream inputStream = new FileInputStream(new File(sourceImage))) {
            sourceImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
        }
        catch(Exception e)
        {
            System.out.println("Failed to load source image " + sourceImage);
            System.exit(1);
        }
        try (InputStream inputStream = new FileInputStream(new File(targetImage))) {
            targetImageBytes = ByteBuffer.wrap(IOUtils.toByteArray(inputStream));
        }
        catch(Exception e)
        {
            System.out.println("Failed to load target images: " + targetImage);
            System.exit(1);
        }

        Image source = new Image()
                .withBytes(sourceImageBytes);
        Image target = new Image()
                .withBytes(targetImageBytes);

        CompareFacesRequest request = new CompareFacesRequest()
                .withSourceImage(source)
                .withTargetImage(target)
                .withSimilarityThreshold(similarityThreshold);

        // Call operation
        CompareFacesResult compareFacesResult = rekognitionClient.compareFaces(request);


        // Display results
        List <CompareFacesMatch> faceDetails = compareFacesResult.getFaceMatches();
        for (CompareFacesMatch match: faceDetails){
            ComparedFace face= match.getFace();
            BoundingBox position = face.getBoundingBox();
            System.out.println("Face at " + position.getLeft().toString()
                    + " " + position.getTop()
                    + " matches with " + face.getConfidence().toString()
                    + "% confidence.");

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

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

Be sure to use import com.amazonaws.services.rekognition.model.Image; for the Image class referenced in the code and not the Image from android.media.

Also you have to change the file path to suit your app needs based on where the file is located (Internal Storage or SD card).

Ok, so this certainly requires AWS api keys and other authentication things. Where all this needs to be kept in code?

@VirRajpurohit You can pass the AWS access key id and secret access key while instantiating that Rekognition client in the snippet above :

AmazonRekognition rekognitionClient = new AmazonRekognitionClient(new BasicAWSCredentials(<Access_key_id>, "secret_access_key"));

It is however recommended to use temporary credentials from a credentials provider for production apps as follows :

AmazonRekognition rekognitionClient = new AmazonRekognitionClient(AWSMobileClient.getInstance());

You can read more using and initializing AWsMobileClient in the documentation here.

@desokroshan
so,
AmazonRekognition rekognitionClient = new AmazonRekognitionClient(AWSMobileClient.getInstance()); This is we can take as a testing purpose

when we want to go live with the app
AmazonRekognition rekognitionClient = new AmazonRekognitionClient(new BasicAWSCredentials(<Access_key_id>, "secret_access_key"));
This is recommended.
Is it so?

Also,
without key must be having some limitations in compare to provoding keys in the clientBuilder?

Its the other way round actually. Providing key in the client builder is not recommended for security reasons. Hard coding keys into the app code makes it available to anyone with access to your app's apk file(which is everyone once the app is live on play store).
Hope it help!

@desokroshan
Understand!

My actual question rolls around the curiosity about the authentication procedure.

One must have AWS account to proceed with the AWS Rekognition integration. so where does this account credentials are being used?

Downloading the SDK and integrating the code @kvasukib provided is all about this?

As I am ending up with error Cognito Identity not configured

To be able to use AWS Rekognition you need to configure Cognito Identity pool. You would then have to create awsconfiguration.json file with Cognito identity pool Id and region, place it res/raw folder of your application. This information will be used by AWSMobile client during its initialization to configure Cognito Identity.
I would suggest going through the documentation and trying out some sample apps before getting started.

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

After going through samples and documentation it is being difficult to integrate Face Rekognition.

SDK and samples do not include steps and code for AWS Rekognition service integration in Android.

Hi i am working with aws reKognition in android i want to scan image and check whether it is s3 bucket is there any who can help me with that

Was this page helpful?
0 / 5 - 0 ratings