批次註解圖片 (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 範例瀏覽工具。