5
5

More than 5 years have passed since last update.

HubotにGoogle Cloud Vision APIで画像認識してもらう

Last updated at Posted at 2016-03-13

はじめに

AlphaGoで世の中が沸いている今、みなさんいかがお過ごしでしょうか。
この記事ではGoogleが提供しているCloud Vision APIをHubot経由で使い、画像認識を行います。

Cloud Vision APIについて

このAPIで現在提供されている機能は、OCR、顔・ロゴ・ランドマーク認識、セーフサーチ認識、物体検知です。
ここでは物体検知を用いて、Hubotくんに渡されたURLの画像に何が含まれているか当ててもらうことにします。

手順

APIキーの準備

Google Cloud Platformで課金1およびCloud Vision APIを有効にします。
その後、認証情報よりAPIキー(サーバーキー)を作成しましょう。このキーは後ほど使うのでメモしてください(キーが使えるようになるまで時間がかかる場合があるのでご注意)。

実装

Hubotは2016/03/13時点の最新版である2.18.0を用います。以下が実装2です。APIキーは前項で準備したものを使用してください。

APIのチュートリアルリファレンスが分かりやすかったのですんなりいきました。

scripts/example.coffee
  robot.respond /detect (https?:.*)/i, (msg) ->
    API_KEY = 'APIキー'

    imageUrl = msg.match[1]
    robot.http(imageUrl).encoding('binary').get() (err, res, body) ->
      imageBase64 = new Buffer(body, 'binary').toString('base64')
      req = JSON.stringify
        requests: [
            image:
              content: imageBase64
            features: [
                type: 'LABEL_DETECTION'
                maxResults: 16
            ]
        ]
      robot.http('https://vision.googleapis.com/v1/images:annotate?key=' + API_KEY)
        .header('Content-Type', 'application/json')
        .post(req) (err2, res2, body2) ->
          data = JSON.parse body2
          labels = (ano.description for ano in data.responses[0].labelAnnotations)
          msg.send labels.join(', ')

テスト

$ ./bin/hubot
myhubot> myhubot: detect https://pbs.twimg.com/profile_images/3204860916/c539ff0abea7adc9f455b0c68eb1002a.png
myhubot> art, font, emoticon, icon, technology, input device, mobile device

  1. 案外高いのでクラウド破産に注意しましょう。Quotaを設定するのがお薦めです。 

  2. async.waterfallとかmsg -> resとかどうするのがベストなのか分からなかったのでそのままです… (; _ _) 

5
5
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
5
5