PHP Google_Service_Visionを使うには?

ショコラ
ショコラ

PHP Google_Service_Visionを使うには?

Google Cloud プラットフォーム を使う。

ここも初めはかなり謎の部分ですので、インターネットで調べるしかないです。

おおざっぱに下の手順が必要です。
①プロジェクトを作成する。
②Marketplaceから「Cloud Vision API」を「有効化」する。
③認証情報を作成する。(サービスアカウント作る)
④サービスアカウントの秘密鍵(JSON)の作成する。

その秘密鍵(JSONファイル)で認証して使います。
※サービスアカウント使わなくてもAPIキーでいけましたが、サービスアカウントを使う流れでいきます。

もっさん先輩
もっさん先輩

Laravel のコマンドで Google Vision API を使ってみます。

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;

class GoogleVisionSample extends Command
{
  protected $signature = 'vision';
  protected $description = '';

  public function handle()
  {
    // サービスアカウントのJSON
    $google_credentials_json =<<< 'GOOGLE_CREDENTIALS_JSON'
{
  "type": "service_account",
  :
  "universe_domain": "googleapis.com"
}
GOOGLE_CREDENTIALS_JSON;

    $client = new \Google_Client();
    $client->setScopes( \Google_Service_Vision::CLOUD_VISION );

    // 認証
    $auth = tempnam(sys_get_temp_dir(),'auth-');
    file_put_contents($auth,$google_credentials_json);
    $client->setAuthConfig($auth);
    unlink($auth);

    // Google_Service_Visionオブジェクトを作成
    $service = new \Google_Service_Vision($client);

    // 画像を読み込む
    $menkyo = file_get_contents('/deploy/laravel/app/Console/Commands/menkyo.jpg');
    $img = new \Google_Service_Vision_Image(['content' => base64_encode($menkyo)]);

    // 画像分析リクエストを送信
    $request = new \Google_Service_Vision_AnnotateImageRequest();
    $request->setImage( $img );
    $request->setFeatures([
      new \Google_Service_Vision_Feature([
        'type' => 'TEXT_DETECTION', // テキスト検出を指定
        'maxResults' => 10          // 最大検出結果数
      ])
    ]);
    $batchRequest = new \Google_Service_Vision_BatchAnnotateImagesRequest();
    $batchRequest->setRequests([$request]);
    $response = $service->images->annotate($batchRequest);
    $text =  $response[0]->fullTextAnnotation->text;
    dd( $text );
  }
}

こんな感じで出力できます。内容はボカしてあります。

# ./artisan vision-sample

"""
氏名\n
もっさん 昭和64年1月9日生\n
住所 東京都文京区〇〇1-2-3-4\n
交付 令和04年12月15日 70000\n
2028年(今和10年)02月09日下有効\n
運転免許証\n
免許の 中型車中型車(t)限る\n
条件等\n
「優良\n
番号 第 459900000000号\n
三小恒令和00年00月00日\n
他 平成14年01月25日\n
二種令和00年00月00日\n
東京都\n
公安委員会\n
[税
""" // app/Console/Commands/GoogleVisionSample.php:64

以上

関連記事

Scroll to Top