PythonでのGoogle Cloud Vision API(label_detection)を利用方法②【10月11日】
昨日言ってたlabel_detection
についてのプログラムを簡単に紹介します。例によってPythonです。request
を使っていない方式なのでerrorが出にくいと思います。
準備
- Googleアカウント(APIが利用できる)
- Google Cloud Platformにプロジェクトが有ること
- Python3.7(Python3系でなら動くと思いますが、必要ならアップデートしてください)
- ダウンロードしたjsonファイル
- 画像
コード
# -*- coding:utf-8 -*- #各種インポート import io import os import glob from google.protobuf.json_format import MessageToJson import json from google.cloud import vision from google.cloud.vision import types import config #今回の作業用ディレクトリ base_dir = 'sample/' #さっきのJSONファイルのファイル名 credential_path = config.Cloud_Vision_json #サービスアカウントキーへのパスを通す os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credential_path #visionクライアントの初期化 client = vision.ImageAnnotatorClient() #対象となる画像のファイル名 file_dir = base_dir files = glob.glob(file_dir + "**/*[jpg|png]",recursive=True) #画像を読み込み for file in files: with io.open(file, 'rb') as image_file: content = image_file.read() image = types.Image(content=content) #ラベル検出 response = client.label_detection(image=image) print(file) #print(response) labels = response.label_annotations #print(labels) for label in labels: print(label.description)
ryoyaku.hatenablog.com ここで紹介したのと少し似てるのですが、今回は画像を分類したりしてるわけじゃないのでターミナル上に表示して終わってます。
この画像のresponse
の中身は
label_annotations { mid: "/m/015p6" description: "Bird" score: 0.9816372394561768 topicality: 0.9816372394561768 }
label_annotations
となっています。
そこからlabels = response.label_annotations
で中身を取り出し
mid: "/m/015p6" description: "Bird" score: 0.9816372394561768 topicality: 0.9816372394561768
そして最後にlabels
を一つずつ取り出しlabel
とし、そこからdiscription
を取り出し、全部表示して
Bird Duck Water Water bird Ducks, geese and swans Waterfowl Goose Swan Beak Seaduck
midに関しては確証はないんですけど、検出した特徴の中央を指しているんですかね?
descriptionはラベル、scoreはその点数(どれだけその特徴であると言い切れるか)であってると思います。
topicalityは直訳「話題」とかそんな感じなんですけど、scoreと同じ値を示していてイマイチわからないです。
すいません...
ってな感じで、画像をラベリングしてくれるプログラムについて紹介しました。
本当は今日、TwitterAPIの申請再びをやろうと思ったんですけど、APEXやってたらこんな時間になってました。
余談ですが今日はサルゲッチュのウッキーレッドの誕生日です。
㊗おめでとうございます㊗
こいつが真に悪かったのはサルバトーレなどの乱戦系な。
こいつがいるだけで全てが崩れる。
難しいと思うけど、サルゲッチュシリーズまた作って欲しいなぁ。