迁移至 Python 客户端库 v0.25.1

Python 客户端库 v0.25.1 针对以前的客户端库设计进行了一些重大更改。这些更改可以总结如下:

  • 整合模块合以减少类型

  • 将无类型参数替换为强类型的类和枚举

本主题详细介绍您需要针对 Cloud Vision API 客户端库对 Python 代码进行什么更改,才能使用 v0.25.1 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 客户端库 v0.25.1 中的新类型。

types 模块包含创建请求所需的新类,例如 types.Image

from google.cloud import vision

此外,新的 google.cloud.vision.enums 模块包含用于解析和理解 API 响应的枚举,如 enums.Likelihood.UNLIKELYenums.FaceAnnotation.Landmark.Type.LEFT_EYE

创建客户端

Client 类已替换为 ImageAnnotatorClient 类。请将对 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 中,face_detection 等 API 方法属于 ImageAnnotatorClient 对象,而非 Image 对象。

如下文所述,多种方法返回的值有所不同。

需特别注意,边界框顶点现在存储在 bounding_poly.vertices(而不是 bounds.vertices)中。每个顶点的坐标存储在 vertex.xvertex.y 中(而不是 vertex.x_coordinatevertex.y_coordinate 中)。

边界框更改会影响 face_detectionlogo_detectiontext_detectiondocument_text_detectioncrop_hints

发出人脸检测请求并处理响应

现在,情绪可能性以枚举的形式返回(存储在 face.surprise_likelihood 而不是 face.emotions.surprise 中)。可能性标签的名称可以通过导入 google.cloud.vision.enums.Likelihood 来恢复。

以前版本的客户端库

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

image = old_client.image(content=content)

faces = image.detect_faces()

for face in faces:
    print('anger: {}'.format(face.emotions.anger))
    print('joy: {}'.format(face.emotions.joy))
    print('surprise: {}'.format(face.emotions.surprise))

    vertices = (['({},{})'.format(bound.x_coordinate, bound.y_coordinate)
                for bound in face.bounds.vertices])

    print('face bounds: {}'.