【问题标题】:How to upload an image at url for Google Vision API - Ruby如何在 Google Vision API 的 url 上传图片 - Ruby
【发布时间】:2017-04-28 19:49:11
【问题描述】:

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

我正在尝试根据下面列出的documentation 中的第二个选项使用 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

我尝试过this previous answer about 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

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

【问题讨论】:

    标签: ruby-on-rails ruby google-app-engine ruby-on-rails-4 google-cloud-vision


    【解决方案1】:

    如果您要使用 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
    

    【讨论】:

    • 啊啊,所以根本不要转换为 Base64。只需使用 tmpfile... 很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多