【Vision API】Web上の画像を画像認識するには【Python】

  • 2022-04-23
  • 2022-06-03
  • AI
AI

Cloud Vision APIでWeb上の画像を画像認識するには、image.source.image_uriを使用します。

Web上の画像を読み込むには

まずimageオブジェクトを作成し、image.source.image_uriで画像のURLを設定します。

image = vision.Image()
image.source.image_uri = "http://tekuzo.org/wp-content/uploads/2022/04/23328723_s.jpg"

上記のimageオブジェクトを使って、画像認識するためにCloud Vision APIにアクセスし、responseを受け取ります。

response = client.object_localization(image=image)

サンプルプログラム

### sample.py ###
#Web上の画像から物体検出するサンプル #

from google.cloud import vision
from google.oauth2 import service_account

# 身元証明書のjson読み込み
credentials = service_account.Credentials.from_service_account_file('key.json')
client = vision.ImageAnnotatorClient(credentials=credentials)

#Web上の画像を読み込み、imageオブジェクト作成
image = vision.Image()
image.source.image_uri = "http://tekuzo.org/wp-content/uploads/2022/04/23328723_s.jpg"

#Cloud Vision APIにアクセスして、物体検出
response = client.object_localization(image=image)

# 物体検出結果を表示
print("物体検出:http://tekuzo.org/wp-content/uploads/2022/04/23328723_s.jpg")
labels = response.localized_object_annotations
for label in labels:
    print(label.name + ":" + str(label.score))

# エラー処理
if response.error.message:
    raise Exception(
        '{}\nFor more info on error messages, check: '
        'https://cloud.google.com/apis/design/errors'.format(response.error.message))

入力画像

例として、サンプルプログラムで次のWeb上のjpg画像を、画像認識してみます。


http://tekuzo.org/wp-content/uploads/2022/04/23328723_s.jpg

実行コマンド

>py sample.py

結果表示

実行すると、以下の物体検出スコアが表示されます。

物体検出:http://tekuzo.org/wp-content/uploads/2022/04/23328723_s.jpg
Cat:0.962284505367279

猫が、96%のスコアで認識できています。

まとめ

本記事では、Google Cloud Vision APIで、Web上の画像を画像認識する方法をまとめました。
みなさんも、よろしければ周りの人にGoogle Cloud Vision APIの使い方を教えてあげると、喜ばれるかもしれません。

今回は以上です。