LoginSignup
8
8

More than 3 years have passed since last update.

Google Cloud Vision APIをPythonから利用する

Last updated at Posted at 2019-12-18

目的

ちょいちょいやり方を忘れるので備忘録として。

必要なもの

  • 有効なGoogleアカウント( Vision APIが有効になっていることが前提)
  • Google Cloud Platformプロジェクトが1つあること
  • Python 3.7
  • 分析したい画像

分析したい画像は今回はこちらを使います。
fujisan.png

やり方

サービスアカウントキーの発行

まずはここでサービスアカウントキーを発行します。

今回はJSON形式でダウンロードします。
このファイルはクラウド上のリソースへのアクセスを可能にするものなので、管理は厳重にしましょう。

Pythonコード

#各種インポート
import io 
import os
from google.protobuf.json_format import MessageToJson
import json
from google.cloud import vision
from google.cloud.vision import types

#今回の作業用ディレクトリ
base_dir = r'path\to\directory'

#さっきのJSONファイルのファイル名
credential_path = base_dir + r'さっきのJSONファイルのファイル名.json'

#サービスアカウントキーへのパスを通す
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path

#visionクライアントの初期化
client = vision.ImageAnnotatorClient()

#対象となる画像のファイル名
file_name = base_dir + r"\fujisan.png"

#画像を読み込み
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
image = types.Image(content=content)

#実際に扱うメソッド名はここを参照
#https://googleapis.dev/python/vision/latest/gapic/v1p4beta1/api.html

#たとえば、ラベル検出の場合
response = client.label_detection(image=image)

#結果を表示
print(response)

結果

label_annotations {
  mid: "/m/015kp7"
  description: "Stratovolcano"
  score: 0.7824147939682007
  topicality: 0.7824147939682007
}
label_annotations {
  mid: "/m/07j7r"
  description: "Tree"
  score: 0.6869218349456787
  topicality: 0.6869218349456787
}
label_annotations {
  mid: "/g/11jwzh3_l"
  description: "Volcanic landform"
  score: 0.5413353443145752
  topicality: 0.5413353443145752
}

"Volcanic Landform"だそうです!

ついでにsafe_searchも試してみる

# ~略~
response = client.safe_search_detection(image=image)
print(response)

めちゃめちゃセーフ画像ですね!

safe_search_annotation {
  adult: VERY_UNLIKELY
  spoof: VERY_UNLIKELY
  medical: VERY_UNLIKELY
  violence: VERY_UNLIKELY
  racy: VERY_UNLIKELY
}

以上!

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