・ Rails 6.0.3.3 ・ Ruby 2.7.1
Google Cloud Vision API documentation 1、https://cloud.google.com/vision/docs/libraries?hl=ja
Described in gemfile
source "https://rubygems.org"
gem "google-cloud-vision"
After that,
bundle installl
* Officially, the method of "gem install google-cloud-vision" is recommended, but it didn't work with my app. </ font> Will come out later
require "google/cloud/vision"
An error occurred and I got stuck. (I ate a lot of time because of this)
In order to use the Google Cloud Vision API, you need to create a dedicated json file and load it into the target rails app. ・ Create json file ▶ ︎ Do not get stuck with the procedure according to the document. The completed file looks like this
{
"type": "",
"project_id": "",
"private_key_id": "private_key_Contents of id",
"private_key": "-----BEGIN PRIVATE KEY-----Contents\=\n-----END PRIVATE KEY-----\n",
"client_email": "",
"client_id": "",
"auth_uri": "",
"token_uri": "",
"auth_provider_x509_cert_url": "",
"client_x509_cert_url": ""
}
・ Load into rails app ▶ ︎.Enter in bash_profile and pass the path
export GOOGLE_APPLICATION_CREDENTIALS="$PATH:Write the path/file name.json"
routes.rb
get "contents/index" => "contents#index"
contents_controller.rb
class ContentsController < ApplicationController
def index
end
end
index.erb
<%=
#Load the gem you just installed
require "google/cloud/vision"
#Instantiation
image_annotator = Google::Cloud::Vision.image_annotator
#Enter the image path (local or online image is fine)
file_name = "./resources/cat.jpg "
#Return value returned after recognizing the image
response = image_annotator.label_detection image: file_name
response.responses.each do |res|
puts "Labels:"
res.label_annotations.each do |label|
puts label.description
end
end
%>
If you see a return value like this, you're successful! (Since I captured the image of a cat as a trial, "Cat" appears. Lol)
From here, you can get the information you want and format it so that you can use it for good! Thank you for reading !!
Recommended Posts