You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pdf2image与table-transformers时,如何实现图像坐标转PDF坐标?

图像坐标转PDF坐标实现方案

核心思路

pdf2image生成的图像像素尺寸与PDF页面的物理尺寸(以**点(pt)**为单位,1pt=1/72英寸)存在固定比例关系,同时要注意两者坐标原点的差异:

  • 图像坐标:左上角为原点(0,0),y轴向下递增
  • PDF坐标:左下角为原点(0,0),y轴向上递增

转换核心步骤:

  1. 获取PDF页面的原始宽高(pt单位)
  2. 获取对应生成图像的像素宽高
  3. 计算像素与pt的比例系数
  4. 对图像坐标进行比例换算+y轴反转,得到PDF坐标

代码实现

修改你现有的pdf2image调用逻辑,同时添加坐标转换函数:

from pdf2image import convert_from_path
from PIL import Image

def image_to_pdf_coords(image_x, image_y, pdf_width_pt, pdf_height_pt, image_width_px, image_height_px):
    # 计算像素到pt的比例系数
    scale_x = pdf_width_pt / image_width_px
    scale_y = pdf_height_pt / image_height_px
    # 转换x坐标
    pdf_x = image_x * scale_x
    # 反转y坐标(适配图像与PDF的原点差异)
    pdf_y = pdf_height_pt - (image_y * scale_y)
    return (pdf_x, pdf_y)

# 转换PDF为图像
images = convert_from_path(
    '/content/Sample Statement Format Bancslink.pdf',
    poppler_path=None  # 本地有poppler可填路径,如Windows下r'C:\poppler-xx\bin'
)

# 获取PDF页面原始尺寸(两种备选方法)
try:
    # 方法1:用pdf2image自带的PDFInfo获取
    from pdf2image.pdfinfo import PDFInfo
    pdf_info = PDFInfo('/content/Sample Statement Format Bancslink.pdf')
    page_sizes = pdf_info.get_page_sizes()  # 返回列表,每个元素为(width_pt, height_pt)
except:
    # 方法2:用PyPDF2获取(兼容性更强)
    from PyPDF2 import PdfReader
    reader = PdfReader('/content/Sample Statement Format Bancslink.pdf')
    page_sizes = []
    for page in reader.pages:
        page_sizes.append((page.mediabox.width, page.mediabox.height))

# 处理每个页面
for i in range(len(images)):
    img = images[i]
    img.save(f'/content/pages_sbi/page{i}.jpeg')
    
    # 获取当前页面的尺寸参数
    pdf_width, pdf_height = page_sizes[i]
    img_width, img_height = img.size
    
    # 示例:假设table-transformers识别到表格的图像坐标为(x1,y1,x2,y2)
    # 转换为PDF坐标
    # table_image_coords = (100, 200, 500, 600)
    # pdf_x1, pdf_y1 = image_to_pdf_coords(table_image_coords[0], table_image_coords[1], pdf_width, pdf_height, img_width, img_height)
    # pdf_x2, pdf_y2 = image_to_pdf_coords(table_image_coords[2], table_image_coords[3], pdf_width, pdf_height, img_width, img_height)
    # print(f"页面{i+1}表格PDF坐标:({pdf_x1:.2f}, {pdf_y1:.2f}) 至 ({pdf_x2:.2f}, {pdf_y2:.2f})")

关键注意事项

  • 页面旋转处理:如果PDF页面存在旋转(如90度),需先通过PyPDF2获取页面rotate属性,对图像坐标做旋转修正后再进行比例转换。
  • DPI一致性:若修改了convert_from_path的dpi参数,需确保用对应生成的图像尺寸计算比例。
  • 边界校验:转换后的PDF坐标需确认在页面mediabox范围内,避免图像裁剪导致的偏差。

内容的提问来源于stack exchange,提问作者siddharth patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 06:59:55