LoginSignup
1
3

More than 5 years have passed since last update.

Ruby Cloud Vision API クライアント ライブラリ v0.32.0 への移行

Posted at

※本記事は2019年3月21日現在の情報です。

RubyでGoogle Cloud Vision を試そうと、GCP公式サイトのサンプルを実施すると、

undefined method `new' for Google::Cloud::Vision:Module (NoMethodError)

というエラーが発生した。

参考にしたCloud Vision 公式サンプルコード

# project_id = "Your Google Cloud project ID"
# image_path = "Path to local image file, eg. './image.png'"

require "google/cloud/vision"

vision = Google::Cloud::Vision.new project: project_id
image  = vision.image image_path

puts image.text

原因

Ruby クライアントの v0.32 から後方互換性のない仕様変更が入っていた
https://cloud.google.com/vision/docs/ruby-client-migration
サンプルコードも上記サイト内で紹介されている

Google::Cloud::Vision::ImageAnnotator を使うようになった。

image_annotator = Google::Cloud::Vision::ImageAnnotator.new

# The name of the image file to annotate
file_name = "./resources/cat.jpg"

response = image_annotator.text_detection(
  image: image_path,
  max_results: 1 # optional, defaults to 10
)

response.responses.each do |res|
  res.text_annotations.each do |text|
    puts text.description
  end
end

ちなみに、公式ドキュメントの英語ページの方はサンプルも最新の情報に更新されていた。
https://cloud.google.com/vision/docs/detecting-text?hl=en#vision-text-detection-ruby

GCP公式の日本語ドキュメントは更新が遅いことが過去にもあったので、なにか詰まったら英語ページを確認するのが吉。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3