[A-00095]pythonでVision API(GCP)を使用する
Google Cloudが提供するVision APIをpythonで使用する方法を記載する。
公式ドキュメントはこちら
https://cloud.google.com/vision/docs/detect-labels-image-client-libraries?hl=ja&cloudshell=false
・セットアップ
pythonライブラリをインストールします。
pip install --upgrade google-cloud-vision
・画像解析してみる
サンプルで使用する画像ファイルはこちら


画像の中のフルーツや色の情報を読み取り、プロパティとして列挙します。
import os
# Imports the Google Cloud client library
from google.cloud import vision
def run_quickstart() -> vision.EntityAnnotation:
"""Provides a quick start example for Cloud Vision."""
# Instantiates a client
client = vision.ImageAnnotatorClient()
# The name of the image file to annotate
file_name = os.path.abspath("/Users/anonymous/Documents/python_folder/test2_project/docs/fruits.jpg")
# Loads the image into memory
with open(file_name, "rb") as image_file:
content = image_file.read()
image = vision.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)
return labels
if __name__ == "__main__":
run_quickstart()
(.venv)MacBook-Pro:test2_project$ python3 visiontest.py
Labels:
Food
Rangpur
Clementine
Green
Fruit
Ingredient
Orange
Natural foods
Citrus
Plant
上の例だと少々結果が正しいのかわかりにくいですが、画像の中にあるオレンジなどは認識しているようです。
コメントを残す