Created
February 24, 2016 07:59
-
-
Save YuheiNakasaka/f0520979565dec360829 to your computer and use it in GitHub Desktop.
Cloud Vision APIをRubyで試すときの簡易スクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# 【使い方】 | |
# CLOUD_VISION_API_KEYにkeyをセットして引数に画像urlを指定してスクリプト実行する | |
# 【例】 | |
# CLOUD_VISION_API_KEY=hoge ruby cloud-vision-api-test.rb https://cloud.google.com/vision/docs/images/faulkner.jpg | |
require 'open-uri' | |
require 'base64' | |
require 'net/http' | |
require 'json' | |
image = ARGV[0] | |
scheme = image.match(/(http[s]?).+/) | |
b64_image = Base64.strict_encode64(open(image).read) | |
uri = URI.parse("https://vision.googleapis.com/v1/images:annotate?key=#{ENV['CLOUD_VISION_API_KEY']}") | |
request = Net::HTTP::Post.new(uri.request_uri, initheader = {'Content-Type' => 'application/json'}) | |
request.body = { | |
requests: [ | |
image: { | |
content: b64_image | |
}, | |
features: [ | |
{ | |
type: 'LABEL_DETECTION', | |
maxResults: 1 | |
} | |
] | |
] | |
}.to_json | |
http = Net::HTTP::new(uri.host, uri.port) | |
http.use_ssl = true | |
if scheme[1] == 'https' | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
end | |
response = nil | |
results = nil | |
http.start do |h| | |
response = h.request(request) | |
results = JSON.parse(response.body) | |
end | |
p results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment