Google 云视觉不接受 base64 编码的图像 python

Google cloud vision not accepting base64 encoded images python

我在发送到 Google Cloud Vision 的 base64 编码图像时遇到问题。有趣的是,如果我通过 URI 发送图像,它工作正常,所以我怀疑我的编码方式有问题。

这是交易:

from google.cloud import vision
import base64
client = vision.ImageAnnotatorClient()
image_path ='8720911950_91828a2aeb_b.jpg'
with open(image_path, 'rb') as image:
    image_content = image.read()
    content = base64.b64encode(image_content)   
    response = client.annotate_image({'image': {'content': content}, 'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION}],})
    print(response)

我得到的回复总是:

error {
  code: 3
  message: "Bad image data."
}

如果我尝试改用 URI:

response = client.annotate_image({'image': {'source': {'image_uri': 'https://farm8.staticflickr.com/7408/8720911950_91828a2aeb_b.jpg'}}, 'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION}],})

响应正常...

label_annotations {
  mid: "/m/0168g6"
  description: "factory"
  score: 0.7942917943000793
}
label_annotations {
  mid: "/m/03rnh"
  description: "industry"
  score: 0.7761002779006958
}

我关注了 Google

中的 recommended way to encode

知道这里出了什么问题吗?

我对 Google Cloud Vision 没有任何经验,但是在查看了他们的文档和示例之后,我的感觉是链接 documentation page about base64 encoding of image data 适用于创建和发送的情况您自己的 HTTP 请求,而不使用 vision.ImageAnnotatorClient。后者似乎自动对图像数据进行编码,因此在您的示例中应用了双重编码。因此,我认为您应该从代码中删除编码步骤:

from google.cloud import vision
import base64
client = vision.ImageAnnotatorClient()
image_path ='8720911950_91828a2aeb_b.jpg'
with open(image_path, 'rb') as image:
    content = image.read()
    response = client.annotate_image({'image': {'content': content}, 'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION}],})
    print(response)

好吧,如果您仍然想使用 base64 编码的图像数据,则必须在发送注释图像请求之前使用模块将其转换为字节数组。 在创建 API 或接收编码数据形式的输入而没有实际 path/url 时,应使用此 base64 到 bytearray。 否则,请按原样使用 @Leon 指出的路径或 url。

import binascii
content = binascii.a2b_base64(base64_encoded_image_data)

将此 content 作为 content 参数的值传递给 annotate_image 方法。 然后,您将得到正确的回复。