Skip to content
Advertisement

Amazon Rekognition label detection problem

Problem:

I’m starting to use Amazon Rekognition label detection, the problem is that I don’t know how to pass a url to the DetectLabelsRequest () object. That url contains an image which is the one I need to analyze.

Code:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        instantiateRekognition()
    }


    private fun instantiateRekognition(){
        val rekognitionClient: AmazonRekognition =
                AmazonRekognitionClient(BasicAWSCredentials("", ""))
        val sourceStream: InputStream = FileInputStream(
                "http://placehold.it/120x120&text=image1")

        var souImage: Image = Image()
        val byteBuffer = ByteBuffer.allocate(sourceStream.toString().length)
        souImage.withBytes(byteBuffer)


        val request = DetectLabelsRequest().withImage(souImage)
                .withMaxLabels(10)
                .withMinConfidence(75f)

        try {
            val result = rekognitionClient.detectLabels(request)
            val labels = result.labels
            for (label in labels) {

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

}

URL of image to analyze:

http://placehold.it/120×120&text=image1

Advertisement

Answer

Here is your solution using the Amazon Rekognition Java V2 API.

If you are not familiar with V2, please refer to this AWS Java Dev Guide topic:

Get started with the AWS SDK for Java 2.x

Code:

package com.example.rekognition;

// snippet-start:[rekognition.java2.detect_labels.import]
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.Image;
import software.amazon.awssdk.services.rekognition.model.DetectLabelsRequest;
import software.amazon.awssdk.services.rekognition.model.DetectLabelsResponse;
import software.amazon.awssdk.services.rekognition.model.Label;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
// snippet-end:[rekognition.java2.detect_labels.import]

/**
 * To run this Java V2 code example, ensure that you have setup your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DetectLabels {

    public static void main(String[] args) {

        final String USAGE = "n" +
                "Usage: " +
                "DetectLabels <sourceImage>nn" +
                "Where:n" +
                "sourceImage - the path to the image (for example, C:\AWS\pic1.png). nn";

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

        String sourceImage =  "C:\Users\scmacdon\lake.png"   ; // args[0] ;
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        detectImageLabels(rekClient, sourceImage );
        rekClient.close();
    }

    // snippet-start:[rekognition.java2.detect_labels.main]
    public static void detectImageLabels(RekognitionClient rekClient, String sourceImage) {

        try {

            InputStream sourceStream = new URL("http://placehold.it/120x120&text=image1").openStream();
           // InputStream sourceStream = new FileInputStream(sourceImage);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

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

            DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
                    .image(souImage)
                    .maxLabels(10)
                    .build();

            DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest);
            List<Label> labels = labelsResponse.labels();

            System.out.println("Detected labels for the given photo");
            for (Label label: labels) {
                System.out.println(label.name() + ": " + label.confidence().toString());
            }

        } catch (RekognitionException | FileNotFoundException | MalformedURLException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // snippet-end:[rekognition.java2.detect_labels.main]
}

Results given your image at the given URL:

enter image description here

I tested with the URL TOO

https://images.unsplash.com/photo-1557456170-0cf4f4d0d362?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bGFrZXxlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80

This produced: enter image description here

You can find many other Java V2 Amazon Rekognition examples here:

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/rekognition

Advertisement