在映像中偵測文字 - Amazon Rekognition

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

在映像中偵測文字

您提供的輸入映像可以是映像位元組陣列 (Base64 編碼映像位元組),或者 Amazon S3 物件。在此步驟中,需上傳 jpeg 或 png 映像到 S3 儲存貯體,並指定檔案名稱。

若要偵測映像中的文字 (API)
  1. 如果您尚未完成,請先完成事前準備:

    1. 建立或更新具有 AmazonRekognitionFullAccessAmazonS3ReadOnlyAccess 許可的使用者。如需詳細資訊,請參閱 步驟 1:設定 AWS 帳戶並建立使用者

    2. 安裝和設定 AWS Command Line Interface AWS 軟體開發套件。如需詳細資訊,請參閱 步驟 2:設定 AWS CLI 和開 AWS 發套件

  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 欄位。單字是一或多個指令碼字元,不以空格分隔。DetectText 最多可在一個映像中偵測 100 個單字。傳回的文字可能包含字元,讓單字無法辨識。例如,C@t 而不是 Cat。若要判斷 TextDetection 元素代表的是一行文字或單字,請使用 Type 欄位。

每個 TextDetection 元素都包含百分比值,代表 Amazon Rekognition 對於文字與文字周圍的週框方塊之偵測精確度的可信度。

單字和行的關係

每個 TextDetection 元素都有一個辨識碼欄位,IdId 會顯示單字在行中的位置。如果元素是一個單字,父系識別碼欄位 ParentId 將找出偵測到該單字的行。行的 ParentId 為 null。例如,範例映像中的「but keep」文字行具有下列 IdParentId 值:

文字

ID

父系 ID

但保留

3

8

3

保留

9

3

文字在映像中的位置

若要判定辨識到的文字在映像中的位置,請使用 DetectText 傳回的週框方塊 (幾何圖形) 資訊。Geometry 物件包含用於偵測到的行和單字之兩種類型的週框方塊資訊:

  • 物件中軸對齊的粗糙矩形外框 BoundingBox

  • 陣列中由多個 X 與 Y 座標組成的精密多邊形

週框方塊與多邊形座標將顯示文字在映像中所在的位置。座標值為整體映像大小的比例。如需詳細資訊,請參閱BoundingBox

下列來自 DetectText 操作的 JSON 回應將顯示在下列映像中偵測到的單字與行。

微笑, 咖啡杯子, 旁邊, 正文, 說,「它是, 星期一, 但, 保持, 微笑」, 上, a, 磚, 背景, 由于, 正文, 邊界, box.
{ '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'}