遷移到 Python 用戶端程式庫 v0.25.1

相較於先前的程式庫,Python 用戶端程式庫 v0.25.1 在設計上有一些重大的變更,以下是摘要說明:

  • 將模組合併成較少的類型

  • 將不具類型的參數取代為強類型的類別與列舉

這個主題提供您為了使用 v0.25.1 Python 用戶端程式庫,而需要對 Cloud Vision API 用戶端程式庫的 Python 程式碼進行變更的詳細資訊。

執行舊版用戶端程式庫

您不一定要將 Python 用戶端程式庫升級至 v0.25.1 版。如果您要繼續使用舊版 Python 用戶端程式庫,而且不想遷移程式碼,請指定應用程式使用的 Python 用戶端程式庫版本。如要指定特定程式庫版本,請編輯 requirements.txt 檔案,如下所示:

google-cloud-vision==0.25

移除的模組

Python 用戶端程式庫 v0.25.1 套件移除了下列模組。

  • google.cloud.vision.annotations

  • google.cloud.vision.batch

  • google.cloud.vision.client

  • google.cloud.vision.color

  • google.cloud.vision.crop_hint

  • google.cloud.vision.entity

  • google.cloud.vision.face

  • google.cloud.vision.feature

  • google.cloud.vision.geometry

  • google.cloud.vision.image

  • google.cloud.vision.likelihood

  • google.cloud.vision.safe_search

  • google.cloud.vision.text

  • google.cloud.vision.web

必要程式碼變更

匯入

包含新的 google.cloud.vision.types 模組,以存取 Python Client Library v0.25.1 中的新類型。

types 模組包含建立要求所需的新類別,例如 types.Image

from google.cloud import vision

此外,新的 google.cloud.vision.enums 模組包含適合用於剖析與理解 API 回應的列舉,例如 enums.Likelihood.UNLIKELYenums.FaceAnnotation.Landmark.Type.LEFT_EYE

建立用戶端

ImageAnnotatorClient 類別已取代 Client 類別。將 Client 類別的參照替換為 ImageAnnotatorClient

舊版用戶端程式庫:

old_client = vision.Client()

Python 用戶端程式庫 v0.25.1:

client = vision.ImageAnnotatorClient()

建構表示圖片內容的物件

如要從本機檔案、Google Cloud Storage URI 或網頁 URI 識別圖片內容,請使用新的 Image 類別。

建構表示本機檔案中圖片內容的物件

以下例子顯示表示本機檔案中圖片內容的新方式。

舊版用戶端程式庫:

with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = old_client.image(content=content)

Python 用戶端程式庫 v0.25.1:

with open(path, "rb") as image_file:
    content = image_file.read()

image = vision.Image(content=content)

建構表示 URI 中圖片內容的物件

以下例子顯示表示 Google Cloud Storage URI 或網路 URI 中圖片內容的新方式。uri 是 Google Cloud Storage 或網路上的圖片檔案 URI。

舊版用戶端程式庫:

image = old_client.image(source_uri=uri)

Python 用戶端程式庫 v0.25.1:

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

建立要求並處理回應

使用 Python 用戶端程式庫 v.0.25.1 時,API 方法 (例如 face_detection) 屬於 ImageAnnotatorClient 物件,而非 Image 物件。

如下所述,不同方法傳回的值會有所不同。

特別是,現在會將邊界框頂點儲存在 bounding_poly.vertices 中,而不是 bounds.vertices。每個頂點的座標都會儲存在 vertex.xvertex.y 中,而不是 vertex.x_coordinatevertex.y_coordinate

這項變更會影響 face_detectionlogo_detectiontext_detectiondocument_text_detection