👻

Go言語でGoogle Cloud Vision APIを使う

2020/10/01に公開

準備

Google Cloud ConsoleでCloud Vision APIを有効にします。Service Accountを作成しJSONファイルをダウンロードします。

your.json
{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "...",
  "token_uri": "...",
  "auth_provider_x509_cert_url": "...",
  "client_x509_cert_url": "..."
}

OAuth2でのアクセスに必要なファイルです。

なお、プロジェクトで課金設定を有効にしておく必要があります(現時点では1000 API callまでは無料枠ですが、設定だけは必要)。

import

"golang.org/x/net/context"
"golang.org/x/oauth2/google"

// package名はvisionになっている
"google.golang.org/api/vision/v1"

Service

// 前述のJSONファイルを読み込んでJWTのConfigを作成
cfg, err := google.JWTConfigFromJSON(
	[]byte(jsonData), vision.CloudPlatformScope)

// OAuth2の認可を付与したHTTPクライアントを作る
client := cfg.Client(context.Background())

// Vision APIのサービスを作る
svc, err := vision.New(client)

Annotate

// 画像ファイルを読み込んでBASE64エンコード
enc := base64.StdEncoding.EncodeToString(imgData)
img := &vision.Image{Content: enc}

// 使いたいVisionの機能
feature := &vision.Feature{
	Type:       "LABEL_DETECTION",
	MaxResults: 10,
}

// 1つの画像に対して複数のFeatureを指定できる
req := &vision.AnnotateImageRequest{
	Image:    img,
	Features: []*vision.Feature{feature},
}

// 1回の呼び出しで複数の処理を要求できる
batch := &vision.BatchAnnotateImagesRequest{
	Requests: []*vision.AnnotateImageRequest{req},
}

// 実際のAPIコールを実行
res, err := svc.Images.Annotate(batch).Do()

結果

// 結果をJSON出力してみる
body, err := json.Marshal(res.Responses[0].LabelAnnotations)
fmt.Println(string(body))

手元のステーキ写真の場合は、以下のような結果となった。

[
    {
        "description": "kobe beef", 
        "mid": "/m/03dzf4", 
        "score": 0.98839045
    }, 
    {
        "description": "food", 
        "mid": "/m/02wbm", 
        "score": 0.96780306
    }, 
    {
        "description": "dish", 
        "mid": "/m/02q08p0", 
        "score": 0.96229196
    }, 
    {
        "description": "sirloin steak", 
        "mid": "/m/04fyb1", 
        "score": 0.92836541
    }, 
    {
        "description": "roast beef", 
        "mid": "/m/01pldp", 
        "score": 0.92026973
    }, 
    {
        "description": "rib eye steak", 
        "mid": "/m/05853c", 
        "score": 0.91176695
    }, 
    {
        "description": "meat chop", 
        "mid": "/m/0272v_j", 
        "score": 0.90220582
    }, 
    {
        "description": "steak", 
        "mid": "/m/0grtl", 
        "score": 0.82390612
    }, 
    {
        "description": "dinner", 
        "mid": "/m/0jffp", 
        "score": 0.79311848
    }, 
    {
        "description": "lamb and mutton", 
        "mid": "/m/01hcps", 
        "score": 0.78561467
    }
]

JSONや画像ファイルの読み込みなどの処理は省略し、Visionまわりのコードの抜粋となっています。

この記事はQiitaの記事をエクスポートしたものです

Discussion