1

如何为 Google Vision 正确上传 S3 URL 图片?

我正在尝试按照下面列出的文档中的第二个选项使用 Base64 编码将图像(保存在 AWS S3 URL)发送到 Google Vision:

发送到 Google Cloud Vision API 的图像可以通过两种方式提供:

  1. 使用 gs://bucketname/path/to/image_filename 形式的 Google Cloud Storage URI

  2. 作为 JSON 请求中发送的图像数据。因为图像数据必须作为 ASCII 文本提供,所以所有图像数据都应该使用 base64 编码进行转义。

我正在使用Google-Cloud-Vision Gem

我已经尝试过这个关于 Base64 encoding 的先前答案,稍作修改:

require 'google/cloud/vision'
require 'base64'
require 'googleauth'
require 'open-uri'

encoded_image = Base64.strict_encode64(open(image_url, &:read))

@vision = Google::Cloud::Vision.new
image = @vision.image(encoded_image)
annotation = @vision.annotate(image, labels: true, text: true)

我尝试过 AWS URL 上的图像和其他 url 上的图像。

每次我从 Google-Cloud-Vision gem 收到此错误时: ArgumentError: Unable to convert (my_base_64_encoded_image) to an image

更新 - 仅在 ruby​​ 中成功编码和解码图像

我已确认此代码:encoded_image = Base64.strict_encode64(open(image_url, &:read))通过以下方式工作:

# Using a random image from the interwebs
image_url = "https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png"
encoded_image = Base64.strict_encode64(open(image_url, &:read))

### now try to decode the encoded_image
File.open("my-new-image.jpg", "wb") do |file|
  file.write(Base64.strict_decode64(encoded_image))
end
### great success

那么谷歌的问题是什么?我被正确编码。

4

1 回答 1

3

如果您要使用 Google-Cloud-Vision gem,您需要遵循 gem 文档(使用非编码图像),也许他是在幕后做到的。

根据 gem google-cloud-vision的文档,您可以像下面的代码一样转换您的图像

open image_url do |img|
  @vision = Google::Cloud::Vision.new

  image = @vision.image(img)
  # you can also use the class method from_io
  # image = Google::Cloud::Vision::Image.from_io(img, @vision)

  annotation = @vision.annotate(image, labels: true, text: true)
end
于 2016-12-13T18:03:36.777 回答