如何从Amazon Textract中获取字符级数据(含单个单词的字符坐标)?
获取Amazon Textract字符级坐标的可行方案
当然可以拿到字符级的坐标和数据啦!Amazon Textract其实早就支持这个能力,只是得用对方法并正确解析返回结果~
核心步骤说明
1. 调用正确的API并配置参数
别只用基础的DetectDocumentText(它默认只返回行和单词级数据),改用AnalyzeDocument API,并且指定FeatureTypes参数包含"FORMS"或"TABLES"——这会触发Textract返回更细粒度的字符级信息。
2. 解析响应中的字符数据
Textract的响应是一个包含多个Blocks的数组,每个块都有明确的BlockType标识:
- 先筛选出
BlockType为"WORD"的块,每个单词块的Relationships字段里会有CHILD类型的关联,指向组成这个单词的所有字符块。 - 每个字符块(
BlockType为"CHARACTER")里:Text字段就是单个字符内容Geometry字段包含两种坐标格式:BoundingBox:相对文档尺寸的百分比坐标(比如Top: 0.2表示距离文档顶部20%的位置)Polygon:由四个坐标点组成的数组,对应字符区域的四个角,是绝对像素级的精确位置
简单代码示例(Python)
import boto3 def extract_characters_with_coords(document_file_path): # 初始化Textract客户端 textract_client = boto3.client('textract') # 读取本地文档并调用API with open(document_file_path, 'rb') as doc_file: api_response = textract_client.analyze_document( Document={'Bytes': doc_file.read()}, FeatureTypes=['FORMS'] # 选FORMS或TABLES都能触发字符级返回 ) character_list = [] # 先收集所有单词块 word_blocks = [block for block in api_response['Blocks'] if block['BlockType'] == 'WORD'] for word_block in word_blocks: # 检查该单词是否有子字符块的关联 if 'Relationships' in word_block: for relationship in word_block['Relationships']: if relationship['Type'] == 'CHILD': # 遍历所有字符块ID,找到对应的字符数据 for char_block_id in relationship['Ids']: char_block = next(block for block in api_response['Blocks'] if block['Id'] == char_block_id) if char_block['BlockType'] == 'CHARACTER': character_info = { 'char': char_block['Text'], 'relative_bounding_box': char_block['Geometry']['BoundingBox'], 'absolute_polygon': char_block['Geometry']['Polygon'] } character_list.append(character_info) return character_list # 使用示例 char_data = extract_characters_with_coords("your_input_image.png") for item in char_data: print(f"字符: {item['char']}, 相对位置: {item['relative_bounding_box']}")
额外注意事项
- 坐标单位:
BoundingBox是百分比相对值,适合适配不同尺寸的文档;Polygon是绝对像素值,适合需要精确位置的场景。 - PDF处理:如果是处理PDF文档,Textract会按页返回结果,你需要遍历
api_response['Blocks']中每个页面的内容(可以通过BlockType为"PAGE"的块来区分)。 - 权限配置:确保你的IAM角色拥有
textract:AnalyzeDocument的权限,避免调用API时出现权限错误。
内容的提问来源于stack exchange,提问作者N00b_Geek
相关产品推荐
相关产品推荐

