使用用戶端程式庫偵測圖片中的標籤

本頁說明如何以您慣用的程式語言開始使用 Vision API。


如要直接在 Cloud Shell 編輯器中按照逐步指南操作,請按一下「Guide me」(逐步引導)

逐步引導


事前準備

  1. 登入 Google Cloud 帳戶。如果您是 Google Cloud新手,歡迎 建立帳戶,親自評估產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。
  2. 安裝 Google Cloud CLI。

  3. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  4. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  5. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  6. 確認專案已啟用計費功能 Google Cloud

  7. 啟用 Vision API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable vision.googleapis.com
  8. 將角色授予使用者帳戶。針對下列每個 IAM 角色,執行一次下列指令: roles/storage.objectViewer

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    更改下列內容:

    • PROJECT_ID:專案 ID。
    • USER_IDENTIFIER:使用者帳戶的 ID。 例如:myemail@example.com
    • ROLE:授予使用者帳戶的 IAM 角色。
  9. 安裝 Google Cloud CLI。

  10. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  11. 執行下列指令,初始化 gcloud CLI:

    gcloud init
  12. 建立或選取 Google Cloud 專案

    選取或建立專案所需的角色

    • 選取專案:選取專案時,不需要具備特定 IAM 角色,只要您已獲授角色,即可選取任何專案。
    • 建立專案:如要建立專案,您需要具備專案建立者角色 (roles/resourcemanager.projectCreator),其中包含 resourcemanager.projects.create 權限。瞭解如何授予角色
    • 建立 Google Cloud 專案:

      gcloud projects create PROJECT_ID

      PROJECT_ID 替換為您要建立的 Google Cloud 專案名稱。

    • 選取您建立的 Google Cloud 專案:

      gcloud config set project PROJECT_ID

      PROJECT_ID 替換為 Google Cloud 專案名稱。

  13. 確認專案已啟用計費功能 Google Cloud

  14. 啟用 Vision API:

    啟用 API 時所需的角色

    如要啟用 API,您需要具備服務使用情形管理員 IAM 角色 (roles/serviceusage.serviceUsageAdmin),其中包含 serviceusage.services.enable 權限。瞭解如何授予角色

    gcloud services enable vision.googleapis.com
  15. 將角色授予使用者帳戶。針對下列每個 IAM 角色,執行一次下列指令: roles/storage.objectViewer

    gcloud projects add-iam-policy-binding PROJECT_ID --member="user:USER_IDENTIFIER" --role=ROLE

    更改下列內容:

    • PROJECT_ID:專案 ID。
    • USER_IDENTIFIER:使用者帳戶的 ID。 例如:myemail@example.com
    • ROLE:授予使用者帳戶的 IAM 角色。

安裝用戶端程式庫

Go

建立專案目錄、初始化 Go 模組,然後下載用戶端程式庫:

mkdir my-vision-app && cd my-vision-app
go mod init example.com/vision-app
go get cloud.google.com/go/vision/apiv1

Java

如要進一步瞭解如何設定 Java 開發環境,請參閱 Java 開發環境設定指南

如果您使用 Maven,請將下列指令新增到 pom.xml 檔案中。如要進一步瞭解 BOM,請參閱 Google Cloud Platform 程式庫 BOM

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.78.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
  </dependency>
</dependencies>

如果您使用 Gradle,請將下列指令新增到依附元件中:

implementation 'com.google.cloud:google-cloud-vision:3.85.0'

如果您使用 sbt,請在依附元件中加入以下指令:

libraryDependencies += "com.google.cloud" % "google-cloud-vision" % "3.85.0"

如果您使用 Visual Studio Code 或 IntelliJ,可以利用下列 IDE 外掛程式,將用戶端程式庫新增到專案中:

這些外掛程式會提供其他功能,例如服務帳戶的金鑰管理功能。詳情請參閱各外掛程式的說明文件。

Node.js

如要進一步瞭解如何設定 Node.js 開發環境,請參閱「Node.js 開發環境設定指南」。

npm install @google-cloud/vision

Python

如要進一步瞭解如何設定 Python 開發環境,請參閱「Python 開發環境設定指南」。

pip install --upgrade google-cloud-vision

標籤偵測範例

現在您可以使用 Vision API 要求取得圖片的資訊,例如標籤偵測。執行下列程式碼,即可進行您的第一個圖片標籤偵測要求。

Go

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vision 快速入門導覽課程」中的 Go 設定說明操作。詳情請參閱 Vision Go API 參考文件

如要向 Vision 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


// Sample vision-quickstart uses the Google Cloud Vision API to label an image.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	vision "cloud.google.com/go/vision/apiv1"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the image file to annotate.
	filename := "../testdata/cat.jpg"

	file, err := os.Open(filename)
	if err != nil {
		log.Fatalf("Failed to read file: %v", err)
	}
	defer file.Close()
	image, err := vision.NewImageFromReader(file)
	if err != nil {
		log.Fatalf("Failed to create image: %v", err)
	}

	labels, err := client.DetectLabels(ctx, image, nil, 10)
	if err != nil {
		log.Fatalf("Failed to detect labels: %v", err)
	}

	fmt.Println("Labels:")
	for _, label := range labels {
		fmt.Println(label.Description)
	}
}

Java

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vision 快速入門導覽課程」中的 Java 設定說明操作。詳情請參閱 Vision Java API 參考文件

如要向 Vision 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Imports the Google Cloud client library

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // 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 (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {

      // The path to the image file to annotate
      String fileName = "./resources/wakeupcat.jpg";

      // Reads the image file into memory
      Path path = Paths.get(fileName);
      byte[] data = Files.readAllBytes(path);
      ByteString imgBytes = ByteString.copyFrom(data);

      // Builds the image annotation request
      List<AnnotateImageRequest> requests = new ArrayList<>();
      Image img = Image.newBuilder().setContent(imgBytes).build();
      Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
      requests.add(request);

      // Performs label detection on the image file
      BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
      List<AnnotateImageResponse> responses = response.getResponsesList();

      for (AnnotateImageResponse res : responses) {
        if (res.hasError()) {
          System.out.format("Error: %s%n", res.getError().getMessage());
          return;
        }

        for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          annotation
              .getAllFields()
              .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
        }
      }
    }
  }
}

Node.js

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vision 快速入門導覽課程」中的 Node.js 設定說明操作。詳情請參閱 Vision Node.js API 參考文件

如要向 Vision 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

async function quickstart() {
  // Imports the Google Cloud client library
  const vision = require('@google-cloud/vision');

  // Creates a client
  const client = new vision.ImageAnnotatorClient();

  // Performs label detection on the image file
  const [result] = await client.labelDetection('./resources/wakeupcat.jpg');
  const labels = result.labelAnnotations;
  console.log('Labels:');
  labels.forEach(label => console.log(label.description));
}
quickstart();

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Vision 快速入門導覽課程」中的 Python 設定說明操作。詳情請參閱 Vision Python API 參考文件

如要向 Vision 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


# Imports the Google Cloud client library
from google.cloud import vision



def run_quickstart() -> vision.EntityAnnotation:
    """Provides a quick start example for Cloud Vision."""

    # Instantiates a client
    client = vision.ImageAnnotatorClient()

    # The URI of the image file to annotate
    file_uri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg"

    image = vision.Image()
    image.source.image_uri = file_uri

    # Performs label detection on the image file
    response = client.label_detection(image=image)
    labels = response.label_annotations

    print("Labels:")
    for label in labels:
        print(label.description)

    return labels

執行範例

如要執行先前的範例,請使用下列指令。如果您複製了特定範例語言的 GitHub 存放區,請取消註解第一行:

Go

# cd golang-samples/vision/vision_quickstart/
go run .

Java

# cd java-docs-samples/vision/snippets/src/main/java/com/example/vision/quickstart/
javac QuickstartSample.java
java QuickstartSample.java

Node.js

# cd nodejs-docs-samples/vision/
node quickstart.js

Python

# cd python-docs-samples/vision/snippets/quickstart
python -c 'import quickstart; quickstart.run_quickstart()'
恭喜!您已將第一個要求傳送至 Vision。

還順利嗎?

清除所用資源

如要避免系統向您的 Google 帳戶收取本快速入門導覽課程所用資源的費用,請按照下列步驟操作:

後續步驟

進一步瞭解 Vision API 用戶端程式庫