使用AWS Textract处理PDF时OCR遮蔽标记的方向偏移问题
问题分析与解决方案
你的问题核心是PDF页面本身带有旋转属性(比如90度),但代码中未处理该属性,导致Textract返回的BoundingBox基于旋转后的图像尺寸,与PDF原页面的坐标系统不匹配,最终出现遮蔽标记偏移。
关键解决步骤
1. 获取PDF页面的旋转角度
PyMuPDF(fitz)的page对象自带rotation属性,直接返回页面的旋转角度(0、90、180、270),这是解决坐标错位的核心依据。
2. 根据旋转角度调整坐标映射
当页面存在旋转时,你传给Textract的JPG图像是旋转后的状态,其宽高与PDF原页面的宽高互换(比如90度旋转后,原宽变高、原高变宽)。需要将Textract返回的BoundingBox坐标转换回PDF原页面的坐标系统。
3. 修改代码逻辑
在你的代码中加入旋转处理逻辑,以下是关键修改部分:
for page in doc: fileTotalPages += 1 # 递增页面计数 myText = page.get_text().encode("utf8") page.wrap_contents() # 获取页面旋转角度 page_rotation = page.rotation pix = page.get_pixmap() page_jpg = pix.tobytes(output = 'jpg') img = np.asarray(bytearray(page_jpg), dtype="uint8") img = cv2.imdecode(img, 0) iHeight, iWidth = img.shape[:2] # 隐藏原有文本 page.add_redact_annot(page.rect, fill = None, text="", text_color = None) page.apply_redactions(images = PDF_REDACT_IMAGE_NONE) ocrDict = ocr_page_textract(page, page.number) for item in ocrDict["Blocks"]: if item["BlockType"] == "LINE" or item["BlockType"] == "WORD": ocrText = item["Text"] ocrConf = item["Confidence"] geo = item["Geometry"] box = geo["BoundingBox"] # 根据旋转角度调整坐标计算 if page_rotation == 90: # 页面顺时针旋转90度:Textract的BoundingBox基于旋转后的图像(宽为原高,高为原宽) # 转换回原页面坐标 x0 = box["Top"] * page.rect.width y0 = (1 - box["Left"] - box["Width"]) * page.rect.height width = box["Height"] * page.rect.width height = box["Width"] * page.rect.height elif page_rotation == 270: # 页面逆时针旋转90度(等同于顺时针270度) x0 = (1 - box["Top"] - box["Height"]) * page.rect.width y0 = box["Left"] * page.rect.height width = box["Height"] * page.rect.width height = box["Width"] * page.rect.height elif page_rotation == 180: # 页面旋转180度 x0 = (1 - box["Left"] - box["Width"]) * page.rect.width y0 = (1 - box["Top"] - box["Height"]) * page.rect.height width = box["Width"] * page.rect.width height = box["Height"] * page.rect.height else: # 无旋转,保持原逻辑 x0 = box["Left"] * page.rect.width y0 = box["Top"] * page.rect.height width = box["Width"] * page.rect.width height = box["Height"] * page.rect.height x1 = x0 + width y1 = y0 + height ocrRect = fitz.Rect(x0, y0, x1, y1) textLen = font.text_length(ocrText, fontsize=1) fontSize = ocrRect.width / textLen page.insert_text(ocrRect.bl, ocrText, fontsize = fontSize, fontname = "helv", render_mode = 3)
补充说明
- Textract的返回结果中,不会直接提供页面旋转信息,因为它只处理传入的图像内容。最可靠的旋转信息来自PDF本身的元数据(即
page.rotation)。 - 上述代码针对常见的90、180、270度旋转做了适配,可覆盖绝大多数场景。
内容的提问来源于stack exchange,提问作者REJ
相关产品推荐
相关产品推荐

