Annotate a batch of image files in Cloud Storage while off-line.

## Explore further


For detailed documentation that includes this code sample, see the following:

- [Annotate a batch of images asynchronously](https://docs.cloud.google.com/vision/docs/samples/vision-async-batch-annotate-images)
- [Batch image annotation offline](https://docs.cloud.google.com/vision/docs/batch)

## Code sample

### Java


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Java API
reference documentation](https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/overview).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.GcsDestination.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageSource.html;
    import com.google.cloud.vision.v1.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.OutputConfig.html;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;

    public class AsyncBatchAnnotateImages {

      public static void asyncBatchAnnotateImages()
          throws InterruptedException, ExecutionException, IOException {
        String inputImageUri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg";
        String outputUri = "gs://YOUR_BUCKET_ID/path/to/save/results/";
        asyncBatchAnnotateImages(inputImageUri, outputUri);
      }

      public static void asyncBatchAnnotateImages(String inputImageUri, String outputUri)
          throws IOException, ExecutionException, InterruptedException {
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests. After completing all of your requests, call
        // the "close" method on the client to safely clean up any remaining background resources.
        try (https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html imageAnnotatorClient = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html.create()) {

          // You can send multiple images to be annotated, this sample demonstrates how to do this with
          // one image. If you want to use multiple images, you have to create a `AnnotateImageRequest`
          // object for each image that you want annotated.
          // First specify where the vision api can find the image
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageSource.html source = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageSource.html.newBuilder().https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageSource.Builder.html#com_google_cloud_vision_v1_ImageSource_Builder_setImageUri_java_lang_String_(inputImageUri).build();
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html image = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.html.newBuilder().https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Image.Builder.html#com_google_cloud_vision_v1_Image_Builder_setSource_com_google_cloud_vision_v1_ImageSource_(source).build();

          // Set the type of annotation you want to perform on the image
          // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html feature = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.newBuilder().setType(https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.Feature.html.Type.LABEL_DETECTION).build();

          // Build the request object for that one image. Note: for additional images you have to create
          // additional `AnnotateImageRequest` objects and store them in a list to be used below.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html imageRequest =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AnnotateImageRequest.html.newBuilder().setImage(image).addFeatures(feature).build();

          // Set where to store the results for the images that will be annotated.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.GcsDestination.html gcsDestination = https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.GcsDestination.html.newBuilder().setUri(outputUri).build();
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.OutputConfig.html outputConfig =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.OutputConfig.html.newBuilder()
                  .https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.OutputConfig.Builder.html#com_google_cloud_vision_v1_OutputConfig_Builder_setGcsDestination_com_google_cloud_vision_v1_GcsDestination_(gcsDestination)
                  .https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.OutputConfig.Builder.html#com_google_cloud_vision_v1_OutputConfig_Builder_setBatchSize_int_(2) // The max number of responses to output in each JSON file
                  .build();

          // Add each `AnnotateImageRequest` object to the batch request and add the output config.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest.html request =
              https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesRequest.html.newBuilder()
                  .addRequests(imageRequest)
                  .setOutputConfig(outputConfig)
                  .build();

          // Make the asynchronous batch request.
          https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse.html response =
              imageAnnotatorClient.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.ImageAnnotatorClient.html#com_google_cloud_vision_v1_ImageAnnotatorClient_asyncBatchAnnotateImagesAsync_com_google_cloud_vision_v1_AsyncBatchAnnotateImagesRequest_(request).get();

          // The output is written to GCS with the provided output_uri as prefix
          String gcsOutputUri = response.https://docs.cloud.google.com/java/docs/reference/google-cloud-vision/latest/com.google.cloud.vision.v1.AsyncBatchAnnotateImagesResponse.html#com_google_cloud_vision_v1_AsyncBatchAnnotateImagesResponse_getOutputConfig__().getGcsDestination().getUri();
          System.out.format("Output written to GCS with prefix: %s%n", gcsOutputUri);
        }
      }
    }

### Node.js


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Node.js API
reference documentation](https://googleapis.dev/nodejs/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).

    /**
     * TODO(developer): Uncomment these variables before running the sample.
     */
    // const inputImageUri = 'gs://cloud-samples-data/vision/label/wakeupcat.jpg';
    // const outputUri = 'gs://YOUR_BUCKET_ID/path/to/save/results/';

    // Imports the Google Cloud client libraries
    const {ImageAnnotatorClient} = require('https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html').v1;

    // Instantiates a client
    const client = new https://docs.cloud.google.com/nodejs/docs/reference/vision/latest/overview.html();

    // You can send multiple images to be annotated, this sample demonstrates how to do this with
    // one image. If you want to use multiple images, you have to create a request object for each image that you want annotated.
    async function asyncBatchAnnotateImages() {
      // Set the type of annotation you want to perform on the image
      // https://cloud.google.com/vision/docs/reference/rpc/google.cloud.vision.v1#google.cloud.vision.v1.Feature.Type
      const features = [{type: 'LABEL_DETECTION'}];

      // Build the image request object for that one image. Note: for additional images you have to create
      // additional image request objects and store them in a list to be used below.
      const imageRequest = {
        image: {
          source: {
            imageUri: inputImageUri,
          },
        },
        features: features,
      };

      // Set where to store the results for the images that will be annotated.
      const outputConfig = {
        gcsDestination: {
          uri: outputUri,
        },
        batchSize: 2, // The max number of responses to output in each JSON file
      };

      // Add each image request object to the batch request and add the output config.
      const request = {
        requests: [
          imageRequest, // add additional request objects here
        ],
        outputConfig,
      };

      // Make the asynchronous batch request.
      const [operation] = await client.asyncBatchAnnotateImages(request);

      // Wait for the operation to complete
      const [filesResponse] = await operation.promise();

      // The output is written to GCS with the provided output_uri as prefix
      const destinationUri = filesResponse.outputConfig.gcsDestination.uri;
      console.log(`Output written to GCS with prefix: ${destinationUri}`);
    }

    asyncBatchAnnotateImages();

### Python


To learn how to install and use the client library for Vision API Product Search, see
[Vision API Product Search client libraries](https://docs.cloud.google.com/vision/product-search/docs/libraries).


For more information, see the
[Vision API Product Search Python API
reference documentation](https://docs.cloud.google.com/python/docs/reference/vision/latest).


To authenticate to Vision API Product Search, set up Application Default Credentials.
For more information, see

[Set up authentication for a local development environment](https://docs.cloud.google.com/docs/authentication/set-up-adc-local-dev-environment).


    from google.cloud import https://docs.cloud.google.com/python/docs/reference/vision/latest


    def sample_async_batch_annotate_images(
        input_image_uri="gs://cloud-samples-data/vision/label/wakeupcat.jpg",
        output_uri="gs://your-bucket/prefix/",
    ):
        """Perform async batch image annotation."""
        client = https://docs.cloud.google.com/python/docs/reference/vision/latest.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.services.image_annotator.ImageAnnotatorClient.html()

        source = {"image_uri": input_image_uri}
        image = {"source": source}
        features = [
            {"type_": https://docs.cloud.google.com/python/docs/reference/vision/latest.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.types.Feature.html.Type.LABEL_DETECTION},
            {"type_": https://docs.cloud.google.com/python/docs/reference/vision/latest.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.types.Feature.html.Type.IMAGE_PROPERTIES},
        ]

        # Each requests element corresponds to a single image.  To annotate more
        # images, create a request element for each image and add it to
        # the array of requests
        requests = [{"image": image, "features": features}]
        gcs_destination = {"uri": output_uri}

        # The max number of responses to output in each JSON file
        batch_size = 2
        output_config = {"gcs_destination": gcs_destination, "batch_size": batch_size}

        operation = client.https://docs.cloud.google.com/python/docs/reference/vision/latest/google.cloud.vision_v1.services.image_annotator.ImageAnnotatorClient.html#google_cloud_vision_v1_services_image_annotator_ImageAnnotatorClient_async_batch_annotate_images(
            requests=requests, output_config=output_config
        )

        print("Waiting for operation to complete...")
        response = operation.result(90)

        # The output is written to GCS with the provided output_uri as prefix
        gcs_output_uri = response.output_config.gcs_destination.uri
        print(f"Output written to GCS with prefix: {gcs_output_uri}")

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples?product=cloudvision).