\

GoogleのVision APIは、画像解析のための強力なツールで、Pythonから簡単に利用することができます。このAPIを使用すると、画像内のラベル、顔、ランドマークの検出、光学文字認識(OCR)、および不適切なコンテンツのタグ付けなど、アプリケーション内に視覚検出機能を簡単に統合できます。

以下に、PythonでGoogle Vision APIを使用して画像から文字を検出する方法を示します。

def detectFacesByGoogleVisionAPIFromF(localFilePath, bucket, dirPathOut):
    try:
        keyFile = "service-account-key.json"
        scope = ["https://www.googleapis.com/auth/cloud-vision"]
        api_name = "vision"
        api_version = "v1"
        service = getGoogleService(keyFile, scope, api_name, api_version)
        ctxt = None
        with open(localFilePath, 'rb') as f:
            ctxt = b64encode(f.read()).decode()
        service_request = service.images().annotate(body={
            "requests": [{
                "image":{
                    "content": ctxt
                },
                "features": [
                    { "type": "FACE_DETECTION" },
                    { "type": "TEXT_DETECTION" }
                ]
            }]
        })
        response = service_request.execute()
    except Exception as e:
        logger.exception(e)

def getGoogleService(keyFile, scope, api_name, api_version):
    credentials = ServiceAccountCredentials.from_json_keyfile_name(keyFile, scopes=scope)
    return build(api_name, api_version, credentials=credentials, cache_discovery=False)

このサンプルコードでは、FACE_DETECTIONTEXT_DETECTIONを指定しています。それ以外にもLABEL_DETECTION, LANDMARK_DETECTION, LOGO_DETECTIONなどが指定できますが、指定するとその分料金が加算されてきます。なので、目的が文字検出だけの場合にはTEXT_DETECTIONだけ指定するなどしたほうがいいですね。

以上がPythonとGoogle Vision APIを活用した画像解析の基本的な手順です。これを応用すれば、さまざまな画像解析タスクを自動化することが可能になります。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です