LoginSignup
2
1

More than 1 year has passed since last update.

Vision クライアントライブラリを使わずに Python3 で Vision API を使う

Last updated at Posted at 2021-03-08

はじめに

この記事は Vision API を Vision クライアントライブラリ を使わずに Python で JavaScript の Fetch API のように使用するための内容を記載します。

結論

  • 使用する画像は base64 モジュールでエンコード
  • JSON リクエストを作成し、json モジュールから json.dumps() を用いて JSON 文字列に変換する
  • 最後に requests モジュールから requests.post() を使用して Vision API リクエスト(POST)を作成すれば OK

下にサンプルコードを置いておきます。

コード

import requests
import base64
import json
import pprint

GOOGLE_API_KEY = "YOUR API KEY"
GOOGLE_CLOUD_VISION_API_URL = f"https://vision.googleapis.com/v1/images:annotate?key={GOOGLE_API_KEY}"
IMG_PATH = "YOUR PHOTO PATH"
base64Image = base64.b64encode(open(IMG_PATH, "rb").read()).decode('utf-8')

headers = { "Content-Type" : "application/json" }
request_data = json.dumps({
    "requests": [
        {
            "image": {
                "content": base64Image
            },
            "features": [
                {
                    "type": "OBJECT_LOCALIZATION"
                }
            ]
        }
    ]
})

# Vision API にリクエストを行う
response = requests.post(GOOGLE_CLOUD_VISION_API_URL, headers=headers, data=request_data)

# データを表示
pprint.pprint(response.json())

以前行ったスープカレー屋さんの画像を POST した結果を貼っておきます。
カレー屋さんのホームページ - 矢巾店 - スープカレーハウスしっぽ
上のコードで Vision API を通した結果の画像

おわりに

手っ取り早く API を使用したい人はこちらの方法のほうが楽なのではないでしょうか。
参考になれば幸いです。

2
1
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
2
1