Google Cloud Vision API 一次 API 调用中的多个图像注释

Google Cloud Vision API multiple image annotations in one API call

我正在尝试使用 Cloud Vision API 客户端检测图像中的 'labels' 和人脸。

我可以检测像 this 这样的标签,关键代码行是:

response = client.label_detection(image=image)
labels = response.label_annotations

并用于检测 faces

response = client.face_detection(image=image)
faces = response.face_annotations

所以,目前我可以进行两次 API 调用来获取我需要的信息,但如果可能的话,我想将它们合并为一个 API 调用。

更新:

我发现 annotate_image() 方法可以接受此 page 上的特征列表:

response = client.annotate_image({
    'image': {'source': {'image_uri': 'gs://my-test-bucket/image.jpg'}},
    'features': [{'type': vision.enums.Feature.Type.FACE_DETECTION}],
})

但是图像源只接受 URL 图像或其在 Google 云端的路径。我想运行分析我保存在本地的图片,可以吗?

您要找的是 Batching Request,它允许您在一个 API 请求中发送多个文件或多个功能。查看 Batching Requests 文档。

要在一个 API 请求中使用多个功能,请查看此 Cloud Vision API Feature 文档。您会发现您可以请求的所有类型的不同功能。

我自己编写了一些代码,这对我很有用。它从本地存储中读取图像,并在一个 API 请求中打印标签和面部检测结果。你可以找到我的 GitHub code here.

可以使用本地图片。您必须在请求中放入图像字节 ("content") 而不是 "source"。 https://cloud.google.com/vision/docs/reference/rest/v1/AnnotateImageRequest#Image

这是 v2 的代码 API:

import io
from google.cloud import vision
from google.protobuf.json_format import MessageToDict, MessageToJson


with io.open("a_pic.jpg", "rb") as image_file:
    content = image_file.read()

image = vision.Image(content=content)

request = {
    "image": image,
    "features": [
        {"type_": vision.Feature.Type.FACE_DETECTION},
        {"type_": vision.Feature.Type.LABEL_DETECTION},
        {"type_": vision.Feature.Type.IMAGE_PROPERTIES},
    ],
}

response = client.annotate_image(request)
print(MessageToDict(response._pb))