イメージ内のテキストの検出 - Amazon Rekognition

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

イメージ内のテキストの検出

入力イメージとして、イメージのバイト配列 (base64 エンコードされたイメージのバイト) を指定するか、Amazon S3 オブジェクトを指定できます。以下の手順では、JPEG イメージまたは PNG イメージを S3 バケットにアップロードし、そのファイル名を指定します。

イメージ内のテキストを検出するには (API)
  1. まだの場合、以下の前提条件を完了します。

    1. AmazonRekognitionFullAccessAmazonS3ReadOnlyAccess のアクセス権限を持つユーザーを作成または更新します。詳細については、「ステップ 1: AWS アカウントを設定してユーザーを作成する」を参照してください。

    2. AWS Command Line Interface と AWS SDK をインストールして設定します。詳細については、「ステップ 2: AWS CLI と AWS SDK をセットアップする」を参照してください。

  2. テキストが含まれているイメージを S3 バケットにアップロードします。

    手順については、Amazon Simple Storage Service ユーザーガイド の「Amazon S3 へのオブジェクトのアップロード」を参照してください。

  3. 以下の例を使用して、DetectText オペレーションを呼び出します。

    Java

    次のコード例では、イメージ内で検出された行と単語を表示します。

    bucketphoto の値は、ステップ 2 で使用した S3 バケット名とイメージ名に置き換えます。

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) package aws.example.rekognition.image; import com.amazonaws.services.rekognition.AmazonRekognition; import com.amazonaws.services.rekognition.AmazonRekognitionClientBuilder; import com.amazonaws.services.rekognition.model.AmazonRekognitionException; import com.amazonaws.services.rekognition.model.Image; import com.amazonaws.services.rekognition.model.S3Object; import com.amazonaws.services.rekognition.model.DetectTextRequest; import com.amazonaws.services.rekognition.model.DetectTextResult; import com.amazonaws.services.rekognition.model.TextDetection; import java.util.List; public class DetectText { public static void main(String[] args) throws Exception { String photo = "inputtext.jpg"; String bucket = "bucket"; AmazonRekognition rekognitionClient = AmazonRekognitionClientBuilder.defaultClient(); DetectTextRequest request = new DetectTextRequest() .withImage(new Image() .withS3Object(new S3Object() .withName(photo) .withBucket(bucket))); try { DetectTextResult result = rekognitionClient.detectText(request); List<TextDetection> textDetections = result.getTextDetections(); System.out.println("Detected lines and words for " + photo); for (TextDetection text: textDetections) { System.out.println("Detected: " + text.getDetectedText()); System.out.println("Confidence: " + text.getConfidence().toString()); System.out.println("Id : " + text.getId()); System.out.println("Parent Id: " + text.getParentId()); System.out.println("Type: " + text.getType()); System.out.println(); } } catch(AmazonRekognitionException e) { e.printStackTrace(); } } }
    Java V2

    このコードは、AWS ドキュメント SDK の例の GitHub リポジトリから引用しています。詳しい事例は こちら を参照してください。

    /** * To run this code example, ensure that you perform the Prerequisites as stated in the Amazon Rekognition Guide: * https://docs.aws.amazon.com/rekognition/latest/dg/video-analyzing-with-sqs.html * * Also, ensure that set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ //snippet-start:[rekognition.java2.detect_text.import] import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rekognition.RekognitionClient; import software.amazon.awssdk.services.rekognition.model.DetectTextRequest; import software.amazon.awssdk.services.rekognition.model.Image; import software.amazon.awssdk.services.rekognition.model.DetectTextResponse; import software.amazon.awssdk.services.rekognition.model.TextDetection; import software.amazon.awssdk.services.rekognition.model.RekognitionException; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; //snippet-end:[rekognition.java2.detect_text.import] /** * Before running this Java V2 code example, set up your development environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DetectTextImage { public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <sourceImage>\n\n" + "Where:\n" + " sourceImage - The path to the image that contains text (for example, C:\\AWS\\pic1.png). \n\n"; if (args.length != 1) { System.out.println(usage); System.exit(1); } String sourceImage = args[0] ; Region region = Region.US_WEST_2; RekognitionClient rekClient = RekognitionClient.builder() .region(region) .credentialsProvider(ProfileCredentialsProvider.create("default")) .build(); detectTextLabels(rekClient, sourceImage ); rekClient.close(); } // snippet-start:[rekognition.java2.detect_text.main] public static void detectTextLabels(RekognitionClient rekClient, String sourceImage) { try { InputStream sourceStream = new FileInputStream(sourceImage); SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream); Image souImage = Image.builder() .bytes(sourceBytes) .build(); DetectTextRequest textRequest = DetectTextRequest.builder() .image(souImage) .build(); DetectTextResponse textResponse = rekClient.detectText(textRequest); List<TextDetection> textCollection = textResponse.textDetections(); System.out.println("Detected lines and words"); for (TextDetection text: textCollection) { System.out.println("Detected: " + text.detectedText()); System.out.println("Confidence: " + text.confidence().toString()); System.out.println("Id : " + text.id()); System.out.println("Parent Id: " + text.parentId()); System.out.println("Type: " + text.type()); System.out.println(); } } catch (RekognitionException | FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(1); } } // snippet-end:[rekognition.java2.detect_text.main]
    AWS CLI

    この AWS CLI コマンドでは、detect-text CLI オペレーションの JSON 出力を表示します。

    BucketName の値は、ステップ 2 で使用した S3 バケット名とイメージ名に置き換えます。

    profile_name の値を自分のデベロッパープロファイル名に置き換えます。

    aws rekognition detect-text --image "{"S3Object":{"Bucket":"bucket-name","Name":"image-name"}}" --profile default

    Windows デバイスで CLI にアクセスする場合は、パーサーエラーの発生に対処するため、一重引用符の代わりに二重引用符を使用し、内側の二重引用符をバックスラッシュ (\) でエスケープします。例として以下を参照してください。

    aws rekognition detect-text --image "{\"S3Object\":{\"Bucket\":\"bucket-name\",\"Name\":\"image-name\"}}" --profile default
    Python

    次のコード例では、イメージ内で検出された行と単語を表示します。

    bucketphoto の値は、ステップ 2 で使用した S3 バケット名とイメージ名に置き換えます。Rekognition セッションを作成する行の profile_name の値を、自分のデベロッパープロファイル名に置き換えます。

    # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) import boto3 def detect_text(photo, bucket): session = boto3.Session(profile_name='default') client = session.client('rekognition') response = client.detect_text(Image={'S3Object': {'Bucket': bucket, 'Name': photo}}) textDetections = response['TextDetections'] print('Detected text\n----------') for text in textDetections: print('Detected text:' + text['DetectedText']) print('Confidence: ' + "{:.2f}".format(text['Confidence']) + "%") print('Id: {}'.format(text['Id'])) if 'ParentId' in text: print('Parent Id: {}'.format(text['ParentId'])) print('Type:' + text['Type']) print() return len(textDetections) def main(): bucket = 'bucket-name' photo = 'photo-name' text_count = detect_text(photo, bucket) print("Text detected: " + str(text_count)) if __name__ == "__main__": main()
    .NET

    次のコード例では、イメージ内で検出された行と単語を表示します。

    bucketphoto の値は、ステップ 2 で使用した S3 バケット名とイメージ名に置き換えます。

    //Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. //PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.) using System; using Amazon.Rekognition; using Amazon.Rekognition.Model; public class DetectText { public static void Example() { String photo = "input.jpg"; String bucket = "bucket"; AmazonRekognitionClient rekognitionClient = new AmazonRekognitionClient(); DetectTextRequest detectTextRequest = new DetectTextRequest() { Image = new Image() { S3Object = new S3Object() { Name = photo, Bucket = bucket } } }; try { DetectTextResponse detectTextResponse = rekognitionClient.DetectText(detectTextRequest); Console.WriteLine("Detected lines and words for " + photo); foreach (TextDetection text in detectTextResponse.TextDetections) { Console.WriteLine("Detected: " + text.DetectedText); Console.WriteLine("Confidence: " + text.Confidence); Console.WriteLine("Id : " + text.Id); Console.WriteLine("Parent Id: " + text.ParentId); Console.WriteLine("Type: " + text.Type); } } catch (Exception e) { Console.WriteLine(e.Message); } } }
    Node.JS

    次のコード例では、イメージ内で検出された行と単語を表示します。

    bucketphoto の値は、ステップ 2 で使用した S3 バケット名とイメージ名に置き換えます。region の値を、.aws 認証情報に入力されているリージョンに置き換えます。Rekognition セッションを作成する行の profile_name の値を、自分のデベロッパープロファイル名に置き換えます。

    var AWS = require('aws-sdk'); const bucket = 'bucket' // the bucketname without s3:// const photo = 'photo' // the name of file const config = new AWS.Config({ accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, }) AWS.config.update({region:'region'}); const client = new AWS.Rekognition(); const params = { Image: { S3Object: { Bucket: bucket, Name: photo }, }, } client.detectText(params, function(err, response) { if (err) { console.log(err, err.stack); // handle error if an error occurred } else { console.log(`Detected Text for: ${photo}`) console.log(response) response.TextDetections.forEach(label => { console.log(`Detected Text: ${label.DetectedText}`), console.log(`Type: ${label.Type}`), console.log(`ID: ${label.Id}`), console.log(`Parent ID: ${label.ParentId}`), console.log(`Confidence: ${label.Confidence}`), console.log(`Polygon: `) console.log(label.Geometry.Polygon) } ) } });

DetectText オペレーションリクエスト

DetectText オペレーションでは、入力イメージを base64 でエンコードされたバイト配列、または Amazon S3 バケットに保存されたイメージとして指定します。以下の JSON リクエストの例では、 Amazon S3 からロードしたイメージを表示します。

{ "Image": { "S3Object": { "Bucket": "bucket", "Name": "inputtext.jpg" } } }

フィルター

テキスト領域、サイズ、信頼スコアに基づくフィルタ処理により、テキスト検出出力をさらに柔軟に制御できるようになります。関心領域を使用することで、テキスト検出を関連する領域に簡単に制限できます。例えば、機械のイメージから部品番号を読み取るとき、この領域はプロフィール写真の右上や基準点からの相対位置などです。単語の境界ボックスサイズフィルタを使用すると、ノイズの多いテキストや無関係な小さな背景テキストを回避できます。単語信頼性フィルターを使用すると、ぼやけているか不鮮明であるために信頼できない結果を取り除けます。

フィルターの値については、「DetectTextFilters」を参照してください。

以下のフィルタを使用できます。

  • MinConfidence 単語検出の信頼性レベルを設定します。検出の信頼性がこのレベルより低い単語は、結果から除外されます。値は 0 から 100 の間で指定する必要があります。

  • MinBoundingBoxWidth 単語境界ボックスの最小幅を設定します。境界ボックスの幅がこの値より小さい単語は、結果から除外されます。値はイメージフレームの幅に対する相対値です。

  • MinBoundingBoxHeight 単語境界ボックスの最小の高さを設定します。境界ボックスの高さがこの値より小さい単語は、結果から除外されます。値はイメージフレームの高さに対する相対値です。

  • RegionsOfInterest 検出をイメージフレームの特定の領域に制限します。値はフレームの寸法に対する相対値です。領域内に部分的にしか含まれていないテキストの場合、レスポンスは不明となります。

DetectText オペレーションレスポンス

DetectText オペレーションでは、イメージを分析して配列 (TextDetections) を返します。この配列の各要素 (TextDetection) は、イメージ内で検出された行または単語を表します。DetectText により、要素ごとに以下の情報が返されます。

  • 検出されたテキスト (DetectedText)

  • 単語と行の関係 (IdParentId)

  • イメージ上のテキストの位置 (Geometry)

  • 検出されたテキストの精度を示す Amazon Rekognition の信頼度と境界ボックス (Confidence)

  • 検出されたテキストのタイプ (Type)

検出されたテキスト

TextDetection 要素には、DetectedText フィールドで認識されたテキスト (単語または行) が含まれます。単語とは、スペースで区切られていない、1 個以上のスクリプト文字です。DetectText は、イメージ内に最大 100 個の単語を検出できます。返されたテキストに含まれる文字によっては、単語が認識できない場合があります。例えば、Cat の代わりに C@t が返される場合があります。TextDetection 要素がテキスト行または単語のいずれであるかを確認するには、Type フィールドを使用します。

TextDetection 要素には、検出されたテキストおよびそのテキストを囲む境界ボックスの精度を示す Amazon Rekognition の信頼度 (%) が含まれます。

単語と行の関係

TextDetection 要素ごとに ID フィールド (Id) があります。Id は、行内での単語の位置を示します。要素が単語である場合、親識別子フィールド (ParentId) は単語が検出された行を識別します。行の ParentId は null です。例えば、例のイメージで「but keep」行の Id 値と ParentId 値は以下のとおりです。

[Text] (テキスト)

ID

親 ID

but keep

3

but

8

3

keep

9

3

イメージ上のテキストの位置

イメージ上で認識されたテキストの位置を確認するには、DetectText から返される境界ボックス (ジオメトリ) 情報を使用します。Geometry オブジェクトには、検出された行と単語に関する次の 2 種類の境界ボックス情報が含まれます。

  • BoundingBox オブジェクト内の座標軸に平行な大まかな長方形のアウトライン

  • ポイント配列の複数の X 座標と Y 座標で構成された精細な多角形

境界ボックスと多角形の座標は、ソースイメージ上のテキストの位置を示します。座標値は、イメージサイズ全体の比率です。詳細については、「BoundingBox」を参照してください。

次の DetectText オペレーションからの JSON レスポンスは、次のイメージで検出された単語と行を示しています。

{ 'TextDetections': [{'Confidence': 99.35693359375, 'DetectedText': "IT'S", 'Geometry': {'BoundingBox': {'Height': 0.09988046437501907, 'Left': 0.6684935688972473, 'Top': 0.18226495385169983, 'Width': 0.1461552083492279}, 'Polygon': [{'X': 0.6684935688972473, 'Y': 0.1838926374912262}, {'X': 0.8141663074493408, 'Y': 0.18226495385169983}, {'X': 0.8146487474441528, 'Y': 0.28051772713661194}, {'X': 0.6689760088920593, 'Y': 0.2821454107761383}]}, 'Id': 0, 'Type': 'LINE'}, {'Confidence': 99.6207275390625, 'DetectedText': 'MONDAY', 'Geometry': {'BoundingBox': {'Height': 0.11442459374666214, 'Left': 0.5566731691360474, 'Top': 0.3525116443634033, 'Width': 0.39574965834617615}, 'Polygon': [{'X': 0.5566731691360474, 'Y': 0.353712260723114}, {'X': 0.9522717595100403, 'Y': 0.3525116443634033}, {'X': 0.9524227976799011, 'Y': 0.4657355844974518}, {'X': 0.5568241477012634, 'Y': 0.46693623065948486}]}, 'Id': 1, 'Type': 'LINE'}, {'Confidence': 99.6160888671875, 'DetectedText': 'but keep', 'Geometry': {'BoundingBox': {'Height': 0.08314694464206696, 'Left': 0.6398131847381592, 'Top': 0.5267938375473022, 'Width': 0.2021435648202896}, 'Polygon': [{'X': 0.640289306640625, 'Y': 0.5267938375473022}, {'X': 0.8419567942619324, 'Y': 0.5295097827911377}, {'X': 0.8414806723594666, 'Y': 0.609940767288208}, {'X': 0.6398131847381592, 'Y': 0.6072247624397278}]}, 'Id': 2, 'Type': 'LINE'}, {'Confidence': 88.95134735107422, 'DetectedText': 'Smiling', 'Geometry': {'BoundingBox': {'Height': 0.4326171875, 'Left': 0.46289217472076416, 'Top': 0.5634765625, 'Width': 0.5371078252792358}, 'Polygon': [{'X': 0.46289217472076416, 'Y': 0.5634765625}, {'X': 1.0, 'Y': 0.5634765625}, {'X': 1.0, 'Y': 0.99609375}, {'X': 0.46289217472076416, 'Y': 0.99609375}]}, 'Id': 3, 'Type': 'LINE'}, {'Confidence': 99.35693359375, 'DetectedText': "IT'S", 'Geometry': {'BoundingBox': {'Height': 0.09988046437501907, 'Left': 0.6684935688972473, 'Top': 0.18226495385169983, 'Width': 0.1461552083492279}, 'Polygon': [{'X': 0.6684935688972473, 'Y': 0.1838926374912262}, {'X': 0.8141663074493408, 'Y': 0.18226495385169983}, {'X': 0.8146487474441528, 'Y': 0.28051772713661194}, {'X': 0.6689760088920593, 'Y': 0.2821454107761383}]}, 'Id': 4, 'ParentId': 0, 'Type': 'WORD'}, {'Confidence': 99.6207275390625, 'DetectedText': 'MONDAY', 'Geometry': {'BoundingBox': {'Height': 0.11442466825246811, 'Left': 0.5566731691360474, 'Top': 0.35251158475875854, 'Width': 0.39574965834617615}, 'Polygon': [{'X': 0.5566731691360474, 'Y': 0.3537122905254364}, {'X': 0.9522718787193298, 'Y': 0.35251158475875854}, {'X': 0.9524227976799011, 'Y': 0.4657355546951294}, {'X': 0.5568241477012634, 'Y': 0.46693626046180725}]}, 'Id': 5, 'ParentId': 1, 'Type': 'WORD'}, {'Confidence': 99.96778869628906, 'DetectedText': 'but', 'Geometry': {'BoundingBox': {'Height': 0.0625, 'Left': 0.6402802467346191, 'Top': 0.5283203125, 'Width': 0.08027780801057816}, 'Polygon': [{'X': 0.6402802467346191, 'Y': 0.5283203125}, {'X': 0.7205580472946167, 'Y': 0.5283203125}, {'X': 0.7205580472946167, 'Y': 0.5908203125}, {'X': 0.6402802467346191, 'Y': 0.5908203125}]}, 'Id': 6, 'ParentId': 2, 'Type': 'WORD'}, {'Confidence': 99.26438903808594, 'DetectedText': 'keep', 'Geometry': {'BoundingBox': {'Height': 0.0818721204996109, 'Left': 0.7344760298728943, 'Top': 0.5280686020851135, 'Width': 0.10748066753149033}, 'Polygon': [{'X': 0.7349520921707153, 'Y': 0.5280686020851135}, {'X': 0.8419566750526428, 'Y': 0.5295097827911377}, {'X': 0.8414806127548218, 'Y': 0.6099407076835632}, {'X': 0.7344760298728943, 'Y': 0.6084995269775391}]}, 'Id': 7, 'ParentId': 2, 'Type': 'WORD'}, {'Confidence': 88.95134735107422, 'DetectedText': 'Smiling', 'Geometry': {'BoundingBox': {'Height': 0.4326171875, 'Left': 0.46289217472076416, 'Top': 0.5634765625, 'Width': 0.5371078252792358}, 'Polygon': [{'X': 0.46289217472076416, 'Y': 0.5634765625}, {'X': 1.0, 'Y': 0.5634765625}, {'X': 1.0, 'Y': 0.99609375}, {'X': 0.46289217472076416, 'Y': 0.99609375}]}, 'Id': 8, 'ParentId': 3, 'Type': 'WORD'}], 'TextModelVersion': '3.0'}