LoginSignup
21
19

More than 5 years have passed since last update.

Google Cloud Vision API sample for python

Last updated at Posted at 2016-10-11

この記事は、Google Cloud Vision API を使う為のサンプルコードとその解説です。このサンプルコードは、他のpythonコードにて import して使う事を想定しています。

動作確認を単体で行う場合は、##main 以下の部分のコメントアウトを外して単体テストしてください。

まず初めに、このサンプルを動かす為には Google Cloud Vision API の APIキーを取得しておく必要があります。また、解析したいサンプル画像は予め用意して実行するプログラムと同じ階層に data/sample.png として保存しておきます。

このコードを実行すると画像データを Google Cloud Vision API に送って、帰ってきた結果を画面表示してdescriptionの値をtmpに保存します。

応用として、update_json_fileのメソッドで帰ってきたJSONの値が違う場合のみ True を返すことで差異が発生したかを確認することができます。この値により、 twitter なり Line なり slack なりで bot 化して呟くという使い方ができます。

googlecv.py
# -*- coding: utf-8 -*-

import requests
import json
import base64
import os

GOOGLE_CLOUD_VISION_API_URL = 'https://vision.googleapis.com/v1/images:annotate?key='
API_KEY = 'YOUR-GOOGLE-CLOUD-VISION-API-KEY'
def goog_cloud_vison (image_content):
    api_url = GOOGLE_CLOUD_VISION_API_URL + API_KEY
    req_body = json.dumps({
        'requests': [{
            'image': {
                'content': image_content
            },
            'features': [{
                'type': 'LABEL_DETECTION',
                'maxResults': 10,
            }]
        }]
    })
    res = requests.post(api_url, data=req_body)
    return res.json()

def img_to_base64(filepath):
    with open(filepath, 'rb') as img:
        img_byte = img.read()
    return base64.b64encode(img_byte)

def get_descs_from_return(res_json):
    labels = res_json['responses'][0]['labelAnnotations']
    descs = []
    for value in labels:
        descs.append(value['description'])

    return json.dumps(descs)

def update_json_file(json_desc):
    fname = '/tmp/descs.json'
    if os.path.isfile(fname)==True:
        with open('/tmp/descs.json', 'r') as f:
            f_desc = json.load(f)
    else:
        f_desc = ''

    if json_desc != f_desc:
        with open('/tmp/descs.json', 'w') as f:
            json.dump(json_desc, f, sort_keys=True, indent=4)
        return True
    else:
        return False

##
## main
##
#dir = os.path.dirname(os.path.abspath(__file__))
#filename = os.path.join(dir, 'data', 'sample.png')
#print filename
#img = img_to_base64(filename)
#res_json = goog_cloud_vison(img)
#json_desc = get_descs_from_return(res_json)
#print json_desc
#update_json_file(json_desc)
21
19
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
21
19