nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

Google Cloud Vision API

Google Cloud Visionの設定について

Google Cloud Vision APIサンプルコード

画像から文字列を抽出して、実際に取り出してきた値と期待値を比較して類似度を求めます

import io
import os
import difflib
from google.cloud import vision


def detect_texts_from_image(image_path: str) -> list[str]:
    """
    画像から文字列を抽出して表示します

    Parameters:
        image_path (str): 画像ファイルパスを指定する

    Returns:
        list[str]: 画像から抽出した文字列のリスト。
                   API呼び出し時のエラー発生時、画像から文字列を検出できなかった場合はエラーを返す
    """
    try:
        # 画像をバイナリデータとして読み込む
        with io.open(image_path, 'rb') as image_file:
            content = image_file.read()

        # Google Cloud Vision APIのクライアントを作成
        client = vision.ImageAnnotatorClient()

        # 画像内のテキストを抽出する
        image = vision.Image(content=content)
        response = client.text_detection(image=image)

        # 画像内にテキストが存在しない場合
        if not response.text_annotations:
            print("画像内に文字列を検出できませんでした。")
            return None

        result_text: str = response.text_annotations[0].description
        print(result_text)
        return result_text.splitlines()

    except Exception as e:
        # エラーが発生した場合の処理
        print("エラーが発生しました:", str(e))
        return None


def calculate_similarity(actual: str, expected: str) -> float:

    # SequenceMatcherオブジェクトを作成
    seq_matcher = difflib.SequenceMatcher(None, actual, expected)
    # 類似度を取得
    result = seq_matcher.ratio()
    return result


image_path = os.path.abspath("{任意の画像ファイル}.jpg")
detect_text_lines = detect_texts_from_image(image_path)

for item_actual in detect_text_lines:
    類似度= calculate_similarity(item_actual , "期待値の文字列")