👏

Google Cloud Vision API を使ってOCRをする(python)

に公開

ドキュメントからテキストを抽出して、必要な情報を抽出するために、Cloud Vision API を使って OCR をする方法を試しました。

API有効化

Cloud Vision の設定とクリーンアップの手順に従い、APIを有効化します.

  1. Enable the API をクリック
  2. プロジェクトを確認 次へをクリック
  3. APIを有効にする 「有効にする」をクリック

Google Cloud CLIをインストールして初期化する

gcloud CLIの概要の手順に従い、Google Cloud CLIをインストールして初期化します。

  1. ダウンロード
    Google Cloud CLI をインストールする」からダウンロードする
  2. インストール
    解凍して以下を実行します。
./google-cloud-sdk/install.sh
  1. gcloud CLI を初期化して承認する
% gcloud init     

ログインを求められため、ブラウザでログインして承認します。
プロジェクトを選択します。

You are signed in as: [XXXX].

Pick cloud project to use: 
 [1] 自身のプロジェクト
 [2] Enter a project ID
 [3] Create a new project

サンプルコードを実行する

サンプルコードを実行する前に、認証情報を環境変数 GOOGLE_APPLICATION_CREDENTIALS に設定します。

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json

サンプルコードは以下の通りです。

import argparse
import sys

from google.cloud import vision

def detect_text(image_path: str) -> str:
    client = vision.ImageAnnotatorClient()

    with open(image_path, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)
    response = client.document_text_detection(image=image)

    if response.error.message:
        raise RuntimeError(response.error.message)

    return response.full_text_annotation.text

def main() -> int:
    parser = argparse.ArgumentParser(description="Google Cloud Vision API OCR minimal sample.")
    parser.add_argument("image", help="OCRする画像ファイル")
    args = parser.parse_args()

    text = detect_text(args.image)
    print(text)
    return 0


if __name__ == "__main__":
    sys.exit(main())

実行するには、先に Vision API のクライアントライブラリをインストールします。

pip install google-cloud-vision

コードを ocr.py として保存した場合、以下のように OCR したい画像ファイルのパスを渡して実行します。

python ocr.py sample.png

このサンプルコードでは、まず vision.ImageAnnotatorClient() で Vision API にアクセスするためのクライアントを作成しています。
次に、引数で受け取った画像ファイルをバイナリとして読み込み、vision.Image(content=content) で Vision API に渡せる形式に変換します。

OCR の実行には document_text_detection() を使っています。
text_detection() でも文字検出はできますが、文章や複数行のテキストを読み取る用途では document_text_detection() の方が適しています。

API の実行結果にエラーが含まれている場合は response.error.message を確認して例外を発生させています。
正常に読み取れた場合は、response.full_text_annotation.text に OCR 結果の全文が入るため、その内容を print(text) で出力します。

Discussion