Batch annotate images (v1p4beta1)

Perform label detection on an image stored in Cloud Storage using a batch annotation request.

Code sample

Java

Before trying this sample, follow the Java setup instructions in the Vision quickstart using client libraries. For more information, see the Vision Java API reference documentation.

To authenticate to Vision, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.vision.v1p4beta1.AnnotateImageRequest;
import com.google.cloud.vision.v1p4beta1.AnnotateImageResponse;
import com.google.cloud.vision.v1p4beta1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1p4beta1.EntityAnnotation;
import com.google.cloud.vision.v1p4beta1.Feature;
import com.google.cloud.vision.v1p4beta1.Image;
import com.google.cloud.vision.v1p4beta1.ImageAnnotatorClient;
import com.google.cloud.vision.v1p4beta1.ImageSource;
import java.util.ArrayList;
import java.util.List;

public class BatchAnnotateImages {

  public static void main(String[] args) throws Exception {
    batchAnnotateImages();
  }

  public static void batchAnnotateImages() throws Exception {
    try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      ImageSource imageSource =
          ImageSource.newBuilder()
              .setImageUri("gs://cloud-samples-data/vision/label/wakeupcat.jpg")
              .build();
      Image image = Image.newBuilder().setSource(imageSource).build();
      Feature feature =
          Feature.newBuilder()
              .setType(Feature.Type.LABEL_DETECTION)
              .setMaxResults(5)
              .build();
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder()
              .setImage(image)
              .addFeatures(feature)
              .build();

      List<AnnotateImageRequest> requests = new ArrayList<>();
      requests.add(request);

      BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
      for (AnnotateImageResponse res : response.getResponsesList()) {
        if (res.hasError()) {
          System.out.printf("Error: %s%n", res.getError().getMessage());
          return;
        }

        for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          System.out.printf("Description: %s%n", annotation.getDescription());
          System.out.printf("Score: %f%n", annotation.getScore());
        }
      }
    }
  }
}

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.