とらりもんHOME  Index  Search  Changes  Login

Google Cloud Platform (GCP)

Linux & Pythonで使う

GCP_key_window.jpg
  • ダウンロードしたキーファイル(なんちゃら.json)を適当なディレクトリに置いて, 以下を打つ(.bashrcにも入れておく)
$ export GOOGLE_APPLICATION_CREDENTIALS="そのファイルのパス"
  • 必要なライブラリ(API)をインストールする:
$ pip3 install --upgrade google-cloud-vision
  • 適当な画像を用意する(ファイル名は2020_0102_1316_dscn1374s.jpg):
2020_0102_1316_dscn1374s.jpg
  • 以下のようなpythonスクリプトを書く(Googleのサンプルをちょっと改変; vision_test.py):
import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

# Instantiates a client
client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
file_name = os.path.join(
   os.path.dirname(__file__),
   '2020_0102_1316_dscn1374s.jpg')    # ここだけ変える!!
print(file_name)

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
   content = image_file.read()

image = types.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations

print('Labels:')
for label in labels:
   print(label.description)
  • それを走らせる:
$ ipython3 vision_test.py 
2020_0102_1316_dscn1374s.jpg
Labels:
Bird
Vertebrate
Beak
Freshwater marsh
Little blue heron
Heron
Wildlife
Shorebird
Water bird
Great blue heron
Last modified:2020/01/08 11:46:41
Keyword(s):
References: