画像に一括でアノテーションを付ける(v1p4beta1)

一括アノテーション リクエストを使用して、Cloud Storage に保存されている画像に対してラベル検出を実行します。

コードサンプル

Java

このサンプルを試す前に、Vision クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vision Java API のリファレンス ドキュメントをご覧ください。

Vision に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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());
        }
      }
    }
  }
}

次のステップ

他の Google Cloud プロダクトのコードサンプルを検索およびフィルタするには、Google Cloud サンプル ブラウザをご覧ください。