PaddleX 通用表格识别产线实战:从模型选型、CLI/Python 推理到服务化部署与二次开发

原创2026-10-11 10:55:401,853 阅读
文章标签:人工智能机器学习深度学习计算机视觉OCR多模态语音模型推理服务模型优化预训练微调

PaddleX 通用表格识别产线实战:从模型选型、CLI/Python 推理到服务化部署与二次开发

本篇技术指南围绕 PaddleX 的通用表格识别产线(table_recognition)展开,系统讲解其"表格结构识别 + 文本检测 + 文本识别"的产线架构、各模块模型选型与性能基准、命令行与 Python 脚本两种本地推理方式、预测结果的字段结构与保存方法,以及高性能推理、服务化部署、端侧部署和基于私有数据微调后再集成的完整落地路径。读完本文,你将能够在自己的项目中快速接入表格识别能力,将图片或 PDF 中的表格转换为可编辑的 HTML 与 Excel 格式,并能根据场景需求对产线做参数调优与模型二次开发。

1. 通用表格识别产线介绍

表格识别是一种自动从文档或图像中识别和提取表格内容及其结构的技术,广泛应用于数据录入、信息检索和文档分析等领域。通过计算机视觉和机器学习算法,表格识别能够将复杂的表格信息转换为可编辑的格式(如 HTML、Excel),方便用户进一步处理和分析数据。

PaddleX 的通用表格识别产线正是为这一任务而设计:它对图片中的表格进行识别,并以 HTML 格式输出。产线集成了业界知名的 SLANet 和 SLANet_plus 表格结构识别模型,使用场景覆盖通用、制造、金融、交通等各个领域。产线同时提供了灵活的服务化部署方式,支持在多种硬件上使用多种编程语言调用,也提供了二次开发能力——你可以基于本产线在自有数据集上训练调优,训练后的模型可无缝集成回产线。

1.1 产线的模块组成

从默认配置文件 paddlex/configs/pipelines/table_recognition.yaml 可以看出,产线的完整结构如下:

pipeline_name: table_recognition

use_doc_preprocessor: True
use_layout_detection: True
use_ocr_model: True

SubModules:
  LayoutDetection:
    module_name: layout_detection
    model_name: PP-DocLayout-L
    model_dir: null

  TableStructureRecognition:
    module_name: table_structure_recognition
    model_name: SLANet_plus
    model_dir: null

SubPipelines:
  DocPreprocessor:
    pipeline_name: doc_preprocessor
    use_doc_orientation_classify: True
    use_doc_unwarping: True
    SubModules:
      DocOrientationClassify:
        module_name: doc_text_orientation
        model_name: PP-LCNet_x1_0_doc_ori
        model_dir: null

      DocUnwarping:
        module_name: image_unwarping
        model_name: UVDoc
        model_dir: null

  GeneralOCR:
    pipeline_name: OCR
    text_type: general
    use_doc_preprocessor: False
    use_textline_orientation: False
    SubModules:
      TextDetection:
        module_name: text_detection
        model_name: PP-OCRv4_server_det
        model_dir: null
        limit_side_len: 960
        limit_type: max
        max_side_limit: 4000
        thresh: 0.3
        box_thresh: 0.6
        unclip_ratio: 1.5

      TextRecognition:
        module_name: text_recognition
        model_name: PP-OCRv4_server_rec_doc
        model_dir: null
        batch_size: 1
        score_thresh: 0

产线中包含必选的表格结构识别模块、文本检测模块和文本识别模块,以及可选的版面区域检测模块、文档图像方向分类模块和文本图像矫正模块:

  • 表格结构识别模块(必选):预测表格的行列结构、单元格位置与合并关系,输出 HTML 表格骨架。默认使用 SLANet_plus。
  • 文本检测模块 + 文本识别模块(必选):对表格内的文字进行定位与识别,将识别文本按单元格匹配回 HTML 结构中。默认使用 PP-OCRv4_server_det + PP-OCRv4_server_rec_doc。
  • 版面区域检测模块(可选):从整图中定位表格所在区域,默认使用 PP-DocLayout-L。关闭后产线将把整张图当作一个表格区域处理。
  • 文档图像方向分类模块(可选):判断文档是否旋转(0°/90°/180°/270°)并自动矫正,默认使用 PP-LCNet_x1_0_doc_ori。
  • 文本图像矫正模块(可选):对扭曲变形的文档图像做矫正,默认使用 UVDoc。

从源码层面看,产线初始化逻辑位于 paddlex/inference/pipelines/table_recognition/pipeline.py:构造函数按配置依次创建文档预处理子产线(DocPreprocessor)、版面检测模型(LayoutDetection)、表格结构识别模型(TableStructureRecognition)以及通用 OCR 子产线(GeneralOCR),并通过 get_model_settings() 统一汇总 use_doc_preprocessor、use_layout_detection、use_ocr_model 三个开关的最终取值。核心预测流程 predict() 大体为:

  1. 读取输入图像(ReadImage(format="BGR"),批大小固定为 1);
  2. 若启用文档预处理,则先做方向分类与扭曲矫正;
  3. 若启用通用 OCR 子产线,则对整图做文本检测与识别,得到全局 OCR 结果;
  4. 若启用版面检测,则从版面结果中筛出 label 为 table 的检测框,逐框裁剪出表格区域;
  5. 对每个表格区域调用表格结构识别模型,得到单元格框 bbox 与 HTML 结构序列 structure;
  6. 将全局 OCR 文本与单元格做匹配(match_table_and_ocr),把文本填入 HTML 的 <td> 中,最终生成 pred_html。

一个值得注意的细节是:产线支持 use_ocr_results_with_table_cells(单元格 OCR 模式),启用时会对每个单元格单独执行 OCR(见 split_ocr_bboxes_by_table_cells()),而不是使用全局 OCR 结果填充,精度更细但耗时增加。单元格与 OCR 框的匹配策略(L1 距离 + IoU 综合排序)实现在 table_recognition_post_processing.py 的 match_table_and_ocr() 中。

1.2 模型选型建议

如果您更注重模型的精度,请选择精度较高的模型;如果您更在意模型的推理速度,请选择推理速度较快的模型;如果您关注模型的存储大小,请选择存储体积较小的模型。以下各小节给出每个模块的完整模型清单与基准数据。

说明:下表中推理耗时仅包含模型推理耗时,不包含前后处理耗时。各模型推理/训练权重由 PaddleX 在首次使用时自动从官方模型库下载。

表格结构识别模块模型

模型 精度(%) GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
SLANet 59.52 23.96 / 21.75 - / 43.12 6.9 SLANet 是百度飞桨视觉团队自研的表格结构识别模型。该模型通过采用 CPU 友好型轻量级骨干网络 PP-LCNet、高低层特征融合模块 CSP-PAN、结构与位置信息对齐的特征解码模块 SLA Head,大幅提升了表格结构识别的精度和推理速度。
SLANet_plus 63.69 23.43 / 22.16 - / 41.80 6.9 在 SLANet 基础上进一步优化的表格结构识别模型(默认选用)。

从源码看,SLANet / SLANet_plus 的实现位于 paddlex/inference/models/table_structure_recognition/modeling/slanet.py,其网络结构完全对应上述描述:

  • 骨干网络:SLANetVisionBackbone 复用 PaddleX 图像分类模块的 PPLCNetEncoder(PP-LCNet),输出最后 4 个 stage 的多尺度特征图;
  • 特征融合:SLANetCSPPAN(CSP-PAN 路径聚合网络)通过 channel projector、top-down 与 bottom-up 的 CSP 层完成高低层特征融合;
  • 结构解码头:SLANetSLAHead 是一个自回归解码头,由 SLANeXtAttentionGRUCell(注意力 GRU 单元)+ SLANeXtMLP 组成,逐 token 预测表格 HTML 结构序列(<table>、<tr>、<td>、colspan/rowspan 等),直到生成结束符为止,最后通过 softmax 输出结构概率分布。

模型的预处理与解码在 predictor.py 中完成:图像先按长边 max_len=488 缩放(ResizeTableImage),再归一化(mean/std 为 ImageNet 标准值)并 padding 到 [488, 448](PaddingTableImage);后处理 TableLabelDecode 负责把结构 token 序列还原为 HTML 标签串 structure 和单元格坐标 bbox。

文本检测模块模型

模型 检测Hmean(%) GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
PP-OCRv5_server_det 83.8 89.55 / 70.19 383.15 / 383.15 84.3 PP-OCRv5 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署
PP-OCRv5_mobile_det 79.0 10.67 / 6.36 57.77 / 28.15 4.7 PP-OCRv5 的移动端文本检测模型,效率更高,适合在端侧设备部署
PP-OCRv4_server_det 69.2 127.82 / 98.87 585.95 / 489.77 109 PP-OCRv4 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署
PP-OCRv4_mobile_det 63.8 9.87 / 4.17 56.60 / 20.79 4.7 PP-OCRv4 的移动端文本检测模型,效率更高,适合在端侧设备部署

文本识别模块模型(重点核心模型)

文本识别模块共支持 18 个全量模型(含多语言模型),以下为重点支持的 4 个核心模型:

模型 识别 Avg Accuracy(%) GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
PP-OCRv4_server_rec_doc 86.58 8.69 / 2.78 37.93 / 37.93 182 在 PP-OCRv4_server_rec 的基础上,在更多中文文档数据和 PP-OCR 训练数据的混合数据训练而成,增加了部分繁体字、日文、特殊字符的识别能力,可支持识别的字符为 1.5 万+,除文档相关的文字识别能力提升外,也同时提升了通用文字的识别能力
PP-OCRv4_mobile_rec 78.74 5.26 / 1.12 17.48 / 3.61 10.5 PP-OCRv4 的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中
PP-OCRv4_server_rec 85.19 8.75 / 2.49 36.93 / 36.93 173 PP-OCRv4 的服务器端模型,推理精度高,可以部署在多种不同的服务器上
en_PP-OCRv4_mobile_rec 70.39 4.81 / 1.23 17.20 / 4.18 7.5 基于 PP-OCRv4 识别模型训练得到的超轻量英文识别模型,支持英文、数字识别

中文识别模型全量列表(除上述 4 个中的中文模型外,还包括):

  • PP-OCRv3_mobile_rec:72.96%,GPU 3.89 / 1.16 ms,CPU 8.72 / 3.56 ms,10.3 MB,PP-OCRv3 的轻量级识别模型;
  • ch_SVTRv2_rec:68.81%,GPU 10.38 / 8.31 ms,CPU 66.52 / 30.83 ms,80.5 MB,SVTRv2 是复旦大学视觉与学习实验室(FVL)OpenOCR 团队研发的服务端文本识别模型,在 PaddleOCR 算法模型挑战赛赛题一(OCR 端到端识别任务)中荣获一等奖,A 榜端到端识别精度相比 PP-OCRv4 提升 6%;
  • ch_RepSVTR_rec:65.07%,GPU 6.29 / 1.57 ms,CPU 20.64 / 5.40 ms,48.8 MB,基于 SVTRv2 的移动端文本识别模型,同赛事一等奖,B 榜端到端识别精度相比 PP-OCRv4 提升 2.5%,推理速度持平。

英文识别模型:

  • en_PP-OCRv4_mobile_rec:70.39%(已列于核心模型);
  • en_PP-OCRv3_mobile_rec:70.69%,GPU 3.56 / 0.78 ms,CPU 8.44 / 5.78 ms,17.3 MB。

多语言识别模型(均为基于 PP-OCRv3 训练的超轻量移动端模型,支持对应语种与数字识别):

模型 识别 Avg Accuracy(%) 模型存储大小(MB)
korean_PP-OCRv3_mobile_rec(韩文) 60.21 9.6
japan_PP-OCRv3_mobile_rec(日文) 45.69 9.8
chinese_cht_PP-OCRv3_mobile_rec(繁体中文) 82.06 10.8
te_PP-OCRv3_mobile_rec(泰卢固文) 95.88 8.7
ka_PP-OCRv3_mobile_rec(卡纳达文) 96.96 17.4
ta_PP-OCRv3_mobile_rec(泰米尔文) 76.83 8.7
latin_PP-OCRv3_mobile_rec(拉丁文) 76.93 8.7
arabic_PP-OCRv3_mobile_rec(阿拉伯字母) 73.55 17.3
cyrillic_PP-OCRv3_mobile_rec(斯拉夫字母) 94.28 8.7
devanagari_PP-OCRv3_mobile_rec(梵文字母) 96.44 8.7

版面区域检测模块模型(可选)

模型 mAP(0.5)(%) GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
PP-DocLayout-L 90.4 33.59 / 33.59 503.01 / 251.08 123.76 基于 RT-DETR-L 在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的高精度版面区域定位模型
PP-DocLayout-M 75.2 13.03 / 4.72 43.39 / 24.44 22.578 基于 PicoDet-L 在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的精度效率平衡的版面区域定位模型
PP-DocLayout-S 70.9 11.54 / 3.86 18.53 / 6.29 4.834 基于 PicoDet-S 在中英文论文、杂志、合同、书本、试卷和研报等场景上自建数据集训练的高效率版面区域定位模型

另有基于 PicoDet/RT-DETR 的轻量版面检测模型可选:PicoDet_layout_1x(97.8%,可定位文字、标题、表格、图片、列表 5 类区域)、PicoDet_layout_1x_table(97.5%,仅表格 1 类)、PicoDet-S_layout_3cls(88.2%,表格/图像/印章 3 类)、PicoDet-S_layout_17cls(87.4%,17 个版面常见类别:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章)、PicoDet-L_layout_3cls(89.0%)、PicoDet-L_layout_17cls(89.0%)、RT-DETR-H_layout_3cls(95.8%)、RT-DETR-H_layout_17cls(98.3%)。

文本图像矫正模块模型(可选)

模型 CER GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
UVDoc 0.179 19.05 / 19.05 - / 869.82 30.3 高精度文本图像矫正模型

文档图像方向分类模块模型(可选)

模型 Top-1 Acc(%) GPU推理耗时(ms)[常规模式 / 高性能模式] CPU推理耗时(ms)[常规模式 / 高性能模式] 模型存储大小(MB) 介绍
PP-LCNet_x1_0_doc_ori 99.06 2.62 / 0.59 3.24 / 1.19 7 基于 PP-LCNet_x1_0 的文档图像分类模型,含有四个类别,即 0 度,90 度,180 度,270 度

1.3 测试环境与推理模式说明

性能测试环境:

  • 测试数据集:文档图像方向分类模型使用 PaddleX 自建数据集(覆盖证件和文档等多个场景,1000 张图片);文本图像矫正模型使用 DocUNet;版面区域检测模型使用 PaddleOCR 自建的版面区域分析数据集(中英文论文、杂志和研报等常见 1 万张文档类型图片);表格结构识别模型使用 PaddleX 内部自建英文表格识别数据集;文本检测模型使用 PaddleOCR 自建中文数据集(街景、网图、文档、手写多场景,500 张图片);中文识别模型使用 PaddleOCR 自建中文数据集(文本识别 1.1 万张图片);ch_SVTRv2_rec 与 ch_RepSVTR_rec 分别使用 PaddleOCR 算法模型挑战赛赛题一 A/B 榜评估集;英文与多语言识别模型使用 PaddleX 自建数据集。
  • 硬件配置:GPU 为 NVIDIA Tesla T4,CPU 为 Intel Xeon Gold 6271C @ 2.60GHz;其他环境为 Ubuntu 20.04 / cuDNN 8.6 / TensorRT 8.5.2.2。

推理模式说明:

模式 GPU配置 CPU配置 加速技术组合
常规模式 FP32精度 / 无TRT加速 FP32精度 / 8线程 PaddleInference
高性能模式 选择先验精度类型和加速策略的最优组合 FP32精度 / 8线程 选择先验最优后端(Paddle/OpenVINO/TRT等)

2. 快速开始

PaddleX 所提供的预训练模型产线均可以快速体验效果,你既可以在星河社区在线体验通用表格识别产线的效果,也可以在本地使用命令行或 Python 体验。

2.1 在线体验

你可以使用官方提供的 demo 图片在线体验通用表格识别产线的效果。如果对产线运行效果满意,可以直接进行集成部署——从云端下载部署包,或参考 2.2 节的方法进行本地部署。如果对效果不满意,可以利用私有数据对产线中的模型进行微调训练:具备本地训练硬件资源可直接在本地开展训练;否则可使用星河零代码平台的一键式训练服务,无需编写代码,上传数据后即可一键启动训练任务。

2.2 本地安装

在本地使用通用表格识别产线前,请确保已按照 PaddleX 本地安装教程 完成 PaddleX wheel 包安装。如果你希望选择性安装依赖,请参考安装教程中的相关说明。该产线对应的依赖分组为 ocr(从源码看,产线类上标注了 @pipeline_requires_extra("ocr"),即需要安装 ocr 依赖分组才能运行)。

2.3 命令行方式体验

一行命令即可快速体验表格识别产线效果,使用官方测试图片,并将 --input 替换为本地路径进行预测:

paddlex --pipeline table_recognition \
        --use_doc_orientation_classify=False \
        --use_doc_unwarping=False \
        --input table_recognition.jpg \
        --save_path ./output \
        --device gpu:0

注:PaddleX 支持多个模型托管平台,官方模型默认优先从 HuggingFace 下载。PaddleX 也支持通过环境变量 PADDLE_PDX_MODEL_SOURCE 设置优先使用的托管平台,目前支持 huggingface、aistudio、bos、modelscope,如优先使用 bos:PADDLE_PDX_MODEL_SOURCE="bos"。

相关参数说明可参考 2.4 Python 脚本方式中的参数说明。产线支持同时指定多个设备以进行并行推理,详情请参考 产线并行推理。

运行后,结果会打印到终端。以官方 demo 图为例,输出大致如下(节选):

{'res': {'input_path': 'table_recognition.jpg', 'page_index': None, 'model_settings': {'use_doc_preprocessor': False, 'use_layout_detection': True, 'use_ocr_model': True}, 'layout_det_res': {'input_path': None, 'page_index': None, 'boxes': [{'cls_id': 0, 'label': 'Table', 'score': 0.9922188520431519, 'coordinate': [3.0127392, 0.14648987, 547.5102, 127.72023]}]}, 'overall_ocr_res': {...}, 'table_res_list': [{'cell_box_list': array([...]), 'pred_html': '<html><body><table><tbody><tr><td colspan="4">CRuncover</td></tr><tr><td>Dres</td><td>连续工作3</td><td>取出来放在网上 没想</td><td>江、整江等八大</td></tr>...</tbody></table></body></html>', 'table_ocr_pred': {...}}]}}

其中 pred_html 即为最终生成的表格 HTML。可视化结果保存在 save_path 下,包含版面检测结果、OCR 结果与表格单元格框的可视化图像。仓库配套的完整调用示例见 api_examples/pipelines/test_table_recognition.py,该示例演示了关闭/开启文档预处理、关闭版面检测、直接输入 PDF 等多种 predict 调用方式。

2.4 Python 脚本方式集成

命令行方式适合快速体验效果,而在实际项目中,通常需要通过代码集成。通过几行代码即可完成产线的快速推理:

from paddlex import create_pipeline

pipeline = create_pipeline(pipeline="table_recognition")

output = pipeline.predict(
    input="table_recognition.jpg",
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
)

for res in output:
    res.print()
    res.save_to_img("./output/")
    res.save_to_xlsx("./output/")
    res.save_to_html("./output/")
    res.save_to_json("./output/")

上述脚本执行了如下几个步骤:

(1)通过 create_pipeline() 实例化通用表格识别产线对象,参数说明如下:

参数 参数说明 参数类型 默认值
pipeline 产线名称或是产线配置文件路径。如为产线名称,则必须为 PaddleX 所支持的产线。 str None
config 产线具体的配置信息(如果和 pipeline 同时设置,优先级高于 pipeline,且要求产线名和 pipeline 一致)。 dict[str, Any] None
device 产线推理设备。支持指定 GPU 具体卡号,如 gpu:0,其他硬件具体卡号,如 npu:0,CPU 如 cpu。支持同时指定多个设备以进行并行推理。 str gpu:0
use_hpip 是否启用高性能推理插件。如果为 None,则使用配置文件或 config 中的配置。 bool / None None
hpi_config 高性能推理配置。 dict / None None
engine 推理引擎,可选 paddle、paddle_static、paddle_dynamic、hpi、flexible、transformers、genai_client。 str / None None
engine_config 推理引擎配置,不同引擎支持不同字段,请参考 推理引擎与配置。 dict / None None
pp_option 用于改变运行模式等配置项,关于推理配置的详细说明,请参考 兼容配置(PaddlePredictorOption)。 PaddlePredictorOption None

(2)调用产线对象的 predict() 方法进行推理预测,该方法返回一个 generator。以下是 predict() 方法的参数及其说明:

参数 参数说明 参数类型 可选项 默认值
input 待预测数据,支持多种输入类型,必填 Python Var / str / list Python Var:如 numpy.ndarray 表示的图像数据;str:图像文件或 PDF 文件的本地路径(如 /root/data/img.jpg)、网络 URL,或本地目录(该目录下需包含待预测图像,当前不支持目录中包含 PDF 文件的预测,PDF 文件需指定到具体文件路径);List:列表元素需为上述类型数据,如 [numpy.ndarray, numpy.ndarray]、["/root/data/img1.jpg", "/root/data/img2.jpg"]、["/root/data1", "/root/data2"] None
use_doc_orientation_classify 是否使用文档方向分类模块 bool / None True/False;None 时使用产线初始化值(True) None
use_doc_unwarping 是否使用文档扭曲矫正模块 bool / None True/False;None 时使用产线初始化值(True) None
use_layout_detection 是否使用版面检测模块 bool / None True/False;None 时使用产线初始化值(True) None
text_det_limit_side_len 文本检测的图像边长限制 int / None 大于 0 的任意整数;None 时使用产线初始化值(960) None
text_det_limit_type 文本检测的图像边长限制类型 str / None min 表示保证图像最短边不小于 det_limit_side_len,max 表示保证图像最长边不大于 limit_side_len;None 时使用产线初始化值(max) None
text_det_thresh 检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点 float / None 大于 0 的任意浮点数;None 时使用产线初始化值(0.3) None
text_det_box_thresh 检测框阈值,检测结果边框内所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域 float / None 大于 0 的任意浮点数;None 时使用产线初始化值(0.6) None
text_det_unclip_ratio 文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大扩张面积越大 float / None 大于 0 的任意浮点数;None 时使用产线初始化值(2.0) None
text_rec_score_thresh 文本识别阈值,得分大于该阈值的文本结果会被保留 float / None 大于 0 的任意浮点数;None 时使用产线初始化值(0.0,即不设阈值) None
use_table_cells_ocr_results 是否启用单元格 OCR 模式。不启用时采用全局 OCR 结果填充至 HTML 表格,启用时逐个单元格做 OCR 并填充(会增加耗时),二者在不同场景下性能不同,请根据实际情况选择 bool True / False False

(3)对预测结果进行处理,每个样本的预测结果均为对应的 Result 对象,支持打印、保存为图片、保存为 xlsx 文件、保存为 HTML 文件、保存为 json 文件:

方法 方法说明 参数 参数类型 参数说明 默认值
print() 打印结果到终端 format_json bool 是否对输出内容使用 JSON 缩进格式化 True
indent int 指定缩进级别,仅当 format_json 为 True 时有效 4
ensure_ascii bool 控制是否将非 ASCII 字符转义为 Unicode,仅当 format_json 为 True 时有效 False
save_to_json() 将结果保存为 json 格式的文件 save_path str 保存的文件路径,当为目录时,保存文件命名与输入文件类型命名一致 无
indent int 指定缩进级别,仅当 format_json 为 True 时有效 4
ensure_ascii bool 控制是否将非 ASCII 字符转义为 Unicode,仅当 format_json 为 True 时有效 False
save_to_img() 将结果保存为图像格式的文件 save_path str 保存的文件路径,支持目录或文件路径 无
save_to_xlsx() 将结果保存为 xlsx 格式的文件 save_path str 保存的文件路径,支持目录或文件路径 无
save_to_html() 将结果保存为 html 格式的文件 save_path str 保存的文件路径,支持目录或文件路径 无

各保存方法的输出约定:

  • save_to_json():若 save_path 为目录,保存路径为 save_path/{your_img_basename}_res.json;若为文件则直接保存到该文件。由于 json 文件不支持保存 numpy 数组,其中的 numpy.array 类型会被转换为列表形式。
  • save_to_img():若 save_path 为目录,保存路径为 save_path/{your_img_basename}_ocr_res_img.{your_img_extension}。产线通常包含较多结果图片,不建议直接指定为具体的文件路径,否则多张图会被覆盖,仅保留最后一张图。
  • save_to_html():若 save_path 为目录,保存路径为 save_path/{your_img_basename}_table_1.html。将图像中表格的 HTML 形式写入指定的 html 文件。
  • save_to_xlsx():若 save_path 为目录,保存路径为 save_path/{your_img_basename}_res.xlsx。将图像中表格的 Excel 表格形式写入指定的 xlsx 文件。

此外,也支持通过属性获取带结果的可视化图像和预测结果:

属性 属性说明
json 获取预测的 json 格式的结果
img 获取格式为 dict 的可视化图像
  • json 属性获取的预测结果为 dict 类型,内容与调用 save_to_json() 方法保存的内容一致。
  • img 属性返回的预测结果是字典类型,键分别为 table_res_img、ocr_res_img、layout_res_img 和 preprocessed_img,对应的值是四个 Image.Image 对象,按顺序分别为:表格识别结果的可视化图像、OCR 结果的可视化图像、版面区域检测结果的可视化图像、图像预处理的可视化图像。如果没有使用某个子模块,则字典中不包含对应的结果图像。

从源码 result.py 可以看出,TableRecognitionResult 组合了 HtmlMixin 与 XlsxMixin:_to_html() 按 table_region_id 生成 table_{id} 键并自动为 <table> 添加 border="1" 属性;_to_xlsx() 则把每个表格的 HTML 直接转换为 xlsx 文件;_to_img() 会用红色矩形在原图上绘制所有预测单元格框生成 table_cell_img,同时汇总版面检测图、OCR 图与预处理图。

2.5 通过配置文件自定义产线

此外,你可以获取通用表格识别产线配置文件,并加载配置文件进行预测。可执行如下命令将结果保存在 my_path 中:

paddlex --get_pipeline_config table_recognition --save_path ./my_path

获取配置文件后,即可对通用表格识别产线各项配置进行自定义,只需修改 create_pipeline 方法中的 pipeline 参数值为产线配置文件路径即可:

from paddlex import create_pipeline

pipeline = create_pipeline(pipeline="./my_path/table_recognition.yaml")

output = pipeline.predict(
    input="table_recognition.jpg",
    use_doc_orientation_classify=False,
    use_doc_unwarping=False,
)

for res in output:
    res.print()
    res.save_to_img("./output/")
    res.save_to_xlsx("./output/")
    res.save_to_html("./output/")
    res.save_to_json("./output/")

注:配置文件中的参数为产线初始化参数,如果希望更改产线初始化参数,可以直接修改配置文件中的参数并加载配置文件进行预测。同时,CLI 预测也支持传入配置文件,--pipeline 指定配置文件的路径即可。

3. 预测结果字段解析

调用 print() 方法会将结果打印到终端,各字段含义如下:

  • input_path:(str) 待预测图像的输入路径。
  • page_index:(Union[int, None]) 如果输入是 PDF 文件,则表示当前是 PDF 的第几页,否则为 None。
  • model_settings:(Dict[str, bool]) 配置产线所需的模型参数。
    • use_doc_preprocessor:(bool) 控制是否启用文档预处理子产线。
  • doc_preprocessor_res:(Dict[str, Union[str, Dict[str, bool], int]]) 文档预处理子产线的输出结果,仅当 use_doc_preprocessor=True 时存在。
    • input_path:(Union[str, None]) 图像预处理子产线接受的图像路径,当输入为 numpy.ndarray 时保存为 None。
    • model_settings:(Dict) 预处理子产线的模型配置参数。
      • use_doc_orientation_classify:(bool) 控制是否启用文档方向分类。
      • use_doc_unwarping:(bool) 控制是否启用文档扭曲矫正。
    • angle:(int) 文档方向分类的预测结果。启用时取值为 [0,1,2,3],分别对应 [0°,90°,180°,270°];未启用时为 -1。
  • dt_polys:(List[numpy.ndarray]) 文本检测的多边形框列表。每个检测框由 4 个顶点坐标构成的 numpy 数组表示,数组 shape 为 (4, 2),数据类型为 int16。
  • dt_scores:(List[float]) 文本检测框的置信度列表。
  • text_det_params:(Dict[str, Dict[str, int, float]]) 文本检测模块的配置参数。
    • limit_side_len:(int) 图像预处理时的边长限制值。
    • limit_type:(str) 边长限制的处理方式。
    • thresh:(float) 文本像素分类的置信度阈值。
    • box_thresh:(float) 文本检测框的置信度阈值。
    • unclip_ratio:(float) 文本检测框的膨胀系数。
    • text_type:(str) 文本检测的类型,当前固定为 "general"。
  • text_rec_score_thresh:(float) 文本识别结果的过滤阈值。
  • rec_texts:(List[str]) 文本识别结果列表,仅包含置信度超过 text_rec_score_thresh 的文本。
  • rec_scores:(List[float]) 文本识别的置信度列表,已按 text_rec_score_thresh 过滤。
  • rec_polys:(List[numpy.ndarray]) 经过置信度过滤的文本检测框列表,格式同 dt_polys。
  • rec_boxes:(numpy.ndarray) 检测框的矩形边界框数组,shape 为 (n, 4),dtype 为 int16。每一行表示一个矩形框的 [x_min, y_min, x_max, y_max] 坐标,其中 (x_min, y_min) 为左上角坐标,(x_max, y_max) 为右下角坐标。

table_res_list 中每个单表结果(SingleTableRecognitionResult)包含:

  • cell_box_list:(numpy.ndarray) 预测得到的单元格矩形框数组。
  • pred_html:(str) 由结构预测序列与匹配到的 OCR 文本共同生成的完整 HTML 表格字符串。
  • table_ocr_pred:(Dict) 该表格区域内的 OCR 预测结果,包含 rec_polys、rec_texts、rec_scores、rec_boxes 等字段。
  • table_region_id:当前表格在图像中的区域序号(从 1 开始,多表图像中依次递增)。

关于 HTML 的生成细节,可在 table_recognition_post_processing.py 的 get_html_result() 中看到:产线先把预测结构序列切分为表头(前 3 个 token)、表体(中间部分)与表尾(后 3 个 token),再遍历表体 token,遇到 </td> 时按 td_index 从匹配字典中取出对应 OCR 文本填入,并处理多文本合并(用空格分隔、自动包裹 <b> 加粗等),最终拼接出完整 HTML。

4. 开发集成与部署

如果产线可以达到你对推理速度和精度的要求,可以直接进行开发集成/部署。若需要将产线直接应用在 Python 项目中,参考 2.4 节中的示例代码即可。此外,PaddleX 还提供了以下三种部署方式。

4.1 高性能推理

在实际生产环境中,许多应用对部署策略的性能指标(尤其是响应速度)有着较严苛的标准,以确保系统的高效运行与用户体验的流畅性。为此,PaddleX 提供高性能推理插件,旨在对模型推理及前后处理进行深度性能优化,实现端到端流程的显著提速,详细流程请参考 PaddleX 高性能推理指南。上文的模型基准表中"高性能模式"一栏即对应启用该能力后的耗时。

4.2 服务化部署

服务化部署是实际生产环境中常见的一种部署形式:通过将推理功能封装为服务,客户端可以通过网络请求访问这些服务以获取推理结果。PaddleX 支持多种产线服务化部署方案,详细的产线服务化部署流程请参考 PaddleX 服务化部署指南。

4.2.1 API 参考

服务提供的主要操作 infer 用于定位并识别图中的表格,HTTP 接口为 POST /table-recognition:

  • HTTP 请求方法为 POST,请求体和响应体均为 JSON 数据(JSON 对象)。
  • 当请求处理成功时,响应状态码为 200,响应体属性如下:
名称 类型 含义
logId string 请求的 UUID。
errorCode integer 错误码。固定为 0。
errorMsg string 错误说明。固定为 "Success"。
result object 操作结果。
  • 当请求处理未成功时,响应体属性如下:
名称 类型 含义
logId string 请求的 UUID。
errorCode integer 错误码。与响应状态码相同。
errorMsg string 错误说明。

请求体属性如下:

名称 类型 含义 是否必填
file string 服务器可访问的图像文件(含 TIFF,多页时按页处理)或 PDF 文件的 URL,或上述类型文件内容的 Base64 编码结果。默认对于超过 10 页的 PDF 或多页 TIFF,仅处理前 10 页。要解除页数限制,请在产线配置文件中添加:Serving: extra: max_num_input_imgs: null 是
fileType integer / null 文件类型。0 表示 PDF 文件,1 表示图像文件(含 TIFF)。若请求体无此属性,则将根据 URL 推断文件类型。 否
useDocOrientationClassify boolean / null 同 predict 方法的 use_doc_orientation_classify 参数。 否
useDocUnwarping boolean / null 同 predict 方法的 use_doc_unwarping 参数。 否
useLayoutDetection boolean / null 同 predict 方法的 use_layout_detection 参数。 否
useOcrModel boolean / null 同 predict 方法的 use_ocr_model 参数。 否
textDetLimitSideLen integer / null 同 predict 方法的 text_det_limit_side_len 参数。 否
textDetLimitType string / null 同 predict 方法的 text_det_limit_type 参数。 否
textDetThresh number / null 同 predict 方法的 text_det_thresh 参数。 否
textDetBoxThresh number / null 同 predict 方法的 text_det_box_thresh 参数。 否
textDetUnclipRatio number / null 同 predict 方法的 text_det_unclip_ratio 参数。 否
textRecScoreThresh number / null 同 predict 方法的 text_rec_score_thresh 参数。 否
useOcrResultsWithTableCells boolean 同 predict 方法的 use_ocr_results_with_table_cells 参数。 否
visualize boolean / null 是否返回可视化结果图以及处理过程中的中间图像。传入 true 返回图像,false 不返回;若未提供或为 null,遵循产线配置文件 Serving.visualize 的设置(例如在配置文件中添加 Serving: visualize: False 将默认不返回图像,请求体参数可覆盖默认行为;若请求体和配置均未设置则默认返回图像)。 否

请求处理成功时,响应体的 result 具有如下属性:

名称 类型 含义
tableRecResults object 表格识别结果。数组长度为 1(对于图像输入)或实际处理的文档页数(对于 PDF 输入)。对于 PDF 输入,数组中的每个元素依次表示 PDF 文件中实际处理的每一页的结果。
dataInfo object 输入数据信息。

下表中涉及图像的字段(如 outputImages、inputImage)默认以 Base64 字符串内联返回;当服务端开启 URL 返回模式时,相应字段的值变为预签名 URL,字段类型保持不变。配置方式参见 服务化部署 中「以 URL 形式返回二进制内容」一节。

tableRecResults 中的每个元素为一个 object,具有如下属性:

名称 类型 含义
prunedResult object 产线对象 predict 方法生成结果的 JSON 表示中 res 字段的简化版本,其中去除了 input_path 和 page_index 字段。
outputImages object / null 参见产线预测结果的 img 属性说明。图像为 JPEG 格式,使用 Base64 编码;启用 URL 返回模式时为预签名 URL。
inputImage string / null 输入图像。图像为 JPEG 格式,使用 Base64 编码;启用 URL 返回模式时为预签名 URL。

4.2.2 多语言调用服务示例

Python:

import base64
import requests

API_URL = "http://localhost:8080/table-recognition"
file_path = "./demo.jpg"

with open(file_path, "rb") as file:
    file_bytes = file.read()
    file_data = base64.b64encode(file_bytes).decode("ascii")

payload = {"file": file_data, "fileType": 1}

response = requests.post(API_URL, json=payload)

assert response.status_code == 200
result = response.json()["result"]
for i, res in enumerate(result["tableRecResults"]):
    print(res["prunedResult"])
    for img_name, img in res["outputImages"].items():
        img_path = f"{img_name}_{i}.jpg"
        with open(img_path, "wb") as f:
            f.write(base64.b64decode(img))
        print(f"Output image saved at {img_path}")

C++(使用 cpp-httplib、nlohmann/json、base64 等库):

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "cpp-httplib/httplib.h"
#include "nlohmann/json.hpp"
#include "base64.hpp"

int main() {
    httplib::Client client("localhost", 8080);
    const std::string filePath = "./demo.jpg";
    std::ifstream file(filePath, std::ios::binary | std::ios::ate);
    if (!file) { std::cerr << "Error opening file." << std::endl; return 1; }

    std::streamsize size = file.tellg();
    file.seekg(0, std::ios::beg);
    std::vector<char> buffer(size);
    if (!file.read(buffer.data(), size)) { std::cerr << "Error reading file." << std::endl; return 1; }

    std::string bufferStr(buffer.data(), static_cast<size_t>(size));
    std::string encodedFile = base64::to_base64(bufferStr);

    nlohmann::json jsonObj;
    jsonObj["file"] = encodedFile;
    jsonObj["fileType"] = 1;

    auto response = client.Post("/table-recognition", jsonObj.dump(), "application/json");

    if (response && response->status == 200) {
        nlohmann::json jsonResponse = nlohmann::json::parse(response->body);
        auto result = jsonResponse["result"];
        for (size_t i = 0; i < result["tableRecResults"].size(); ++i) {
            auto tableRecResult = result["tableRecResults"][i];
            std::cout << tableRecResult["prunedResult"] << std::endl;
            if (tableRecResult["outputImages"].is_object()) {
                for (auto& img : tableRecResult["outputImages"].items()) {
                    std::string imgName = img.key();
                    std::string encodedImage = img.value();
                    std::string decodedImage = base64::from_base64(encodedImage);
                    std::string imgPath = imgName + "_" + std::to_string(i) + ".jpg";
                    std::ofstream outputImage(imgPath, std::ios::binary);
                    if (outputImage.is_open()) {
                        outputImage.write(decodedImage.c_str(), static_cast<std::streamsize>(decodedImage.size()));
                        std::cout << "Output image saved at " << imgPath << std::endl;
                    }
                }
            }
        }
    } else {
        std::cerr << "Failed to send HTTP request." << std::endl;
        if (response) { std::cerr << "HTTP status code: " << response->status << std::endl; }
        return 1;
    }
    return 0;
}

Java(使用 OkHttp 与 Jackson):

import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws IOException {
        String API_URL = "http://localhost:8080/table-recognition";
        String imagePath = "./demo.jpg";

        File file = new File(imagePath);
        byte[] fileContent = java.nio.file.Files.readAllBytes(file.toPath());
        String base64Image = Base64.getEncoder().encodeToString(fileContent);

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode payload = objectMapper.createObjectNode();
        payload.put("file", base64Image);
        payload.put("fileType", 1);

        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, payload.toString());
        Request request = new Request.Builder().url(API_URL).post(body).build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JsonNode root = objectMapper.readTree(responseBody);
                JsonNode result = root.get("result");
                JsonNode tableRecResults = result.get("tableRecResults");
                for (int i = 0; i < tableRecResults.size(); i++) {
                    JsonNode item = tableRecResults.get(i);
                    System.out.println("Pruned Result [" + i + "]: " + item.get("prunedResult").toString());
                    JsonNode outputImages = item.get("outputImages");
                    outputImages.fieldNames().forEachRemaining(imgName -> {
                        String imgBase64 = outputImages.get(imgName).asText();
                        byte[] imgBytes = Base64.getDecoder().decode(imgBase64);
                        String imgPath = "output_" + imgName + ".jpg";
                        try (FileOutputStream fos = new FileOutputStream(imgPath)) {
                            fos.write(imgBytes);
                            System.out.println("Saved image to: " + imgPath);
                        } catch (IOException e) { e.printStackTrace(); }
                    });
                }
            } else {
                System.err.println("Request failed with HTTP code: " + response.code());
            }
        }
    }
}

Go:

package main

import (
    "bytes"
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    API_URL := "http://localhost:8080/table-recognition"
    filePath := "./demo.jpg"

    fileBytes, _ := ioutil.ReadFile(filePath)
    fileData := base64.StdEncoding.EncodeToString(fileBytes)

    payload := map[string]interface{}{"file": fileData, "fileType": 1}
    payloadBytes, _ := json.Marshal(payload)

    client := &http.Client{}
    req, _ := http.NewRequest("POST", API_URL, bytes.NewBuffer(payloadBytes))
    req.Header.Set("Content-Type", "application/json")

    res, err := client.Do(req)
    if err != nil { fmt.Printf("Error sending request: %v\n", err); return }
    defer res.Body.Close()

    if res.StatusCode != http.StatusOK { fmt.Printf("Unexpected status code: %d\n", res.StatusCode); return }

    body, _ := ioutil.ReadAll(res.Body)

    type TableRecResult struct {
        PrunedResult map[string]interface{} `json:"prunedResult"`
        OutputImages map[string]string      `json:"outputImages"`
        InputImage   *string                `json:"inputImage"`
    }
    type Response struct {
        Result struct {
            TableRecResults []TableRecResult `json:"tableRecResults"`
            DataInfo        interface{}      `json:"dataInfo"`
        } `json:"result"`
    }

    var respData Response
    if err := json.Unmarshal(body, &respData); err != nil { fmt.Printf("Error unmarshaling response: %v\n", err); return }

    for i, res := range respData.Result.TableRecResults {
        fmt.Printf("Result %d - prunedResult: %+v\n", i, res.PrunedResult)
        for imgName, imgData := range res.OutputImages {
            imgBytes, _ := base64.StdEncoding.DecodeString(imgData)
            filename := fmt.Sprintf("%s_%d.jpg", imgName, i)
            ioutil.WriteFile(filename, imgBytes, 0644)
            fmt.Printf("Saved image to %s\n", filename)
        }
    }
}

C#(使用 HttpClient 与 Newtonsoft.Json):

using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

class Program
{
    static readonly string API_URL = "http://localhost:8080/table-recognition";
    static readonly string inputFilePath = "./demo.jpg";

    static async Task Main(string[] args)
    {
        var httpClient = new HttpClient();

        byte[] fileBytes = File.ReadAllBytes(inputFilePath);
        string fileData = Convert.ToBase64String(fileBytes);

        var payload = new JObject { { "file", fileData }, { "fileType", 1 } };
        var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");

        HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
        response.EnsureSuccessStatusCode();

        string responseBody = await response.Content.ReadAsStringAsync();
        JObject jsonResponse = JObject.Parse(responseBody);

        JArray tableRecResults = (JArray)jsonResponse["result"]["tableRecResults"];
        for (int i = 0; i < tableRecResults.Count; i++)
        {
            var res = tableRecResults[i];
            Console.WriteLine($"[{i}] prunedResult:\n{res["prunedResult"]}");

            JObject outputImages = res["outputImages"] as JObject;
            if (outputImages != null)
            {
                foreach (var img in outputImages)
                {
                    string imgName = img.Key;
                    string base64Img = img.Value?.ToString();
                    if (!string.IsNullOrEmpty(base64Img))
                    {
                        string imgPath = $"{imgName}_{i}.jpg";
                        byte[] imageBytes = Convert.FromBase64String(base64Img);
                        File.WriteAllBytes(imgPath, imageBytes);
                        Console.WriteLine($"Output image saved at {imgPath}");
                    }
                }
            }
        }
    }
}

Node.js(使用 axios):

const axios = require('axios');
const fs = require('fs');

const API_URL = 'http://localhost:8080/table-recognition';
const inputImagePath = './demo.jpg';

function encodeImageToBase64(filePath) {
  const bitmap = fs.readFileSync(filePath);
  return Buffer.from(bitmap).toString('base64');
}

async function callTableRecognitionAPI() {
  const payload = {
    file: encodeImageToBase64(inputImagePath),
    fileType: 1
  };

  try {
    const response = await axios.post(API_URL, payload, {
      headers: { 'Content-Type': 'application/json' },
      maxBodyLength: Infinity
    });

    const results = response.data.result.tableRecResults;
    results.forEach((res, index) => {
      console.log(`Result [${index}] prunedResult:\n`, res.prunedResult);

      const outputImages = res.outputImages || {};
      Object.entries(outputImages).forEach(([imgName, base64Img]) => {
        const outputPath = `${imgName}_${index}.jpg`;
        fs.writeFileSync(outputPath, Buffer.from(base64Img, 'base64'));
        console.log(`Saved image: ${outputPath}`);
      });
    });
  } catch (error) {
    console.error('API request failed:', error.message);
  }
}

callTableRecognitionAPI();

PHP(使用 cURL):

<?php
$API_URL = "http://localhost:8080/table-recognition";
$image_path = "./demo.jpg";

$image_data = base64_encode(file_get_contents($image_path));
$payload = array("file" => $image_data, "fileType" => 1);

$ch = curl_init($API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$result_array = json_decode($response, true);
$results = $result_array["result"]["tableRecResults"];

foreach ($results as $i => $item) {
    echo "[$i] prunedResult:\n";
    print_r($item["prunedResult"]);

    if (!empty($item["outputImages"])) {
        foreach ($item["outputImages"] as $img_name => $base64_img) {
            $img_path = $img_name . "_" . $i . ".jpg";
            file_put_contents($img_path, base64_decode($base64_img));
            echo "Output image saved at $img_path\n";
        }
    }
}
?>

4.3 端侧部署

端侧部署是一种将计算和数据处理功能放在用户设备本身上的方式,设备可以直接处理数据,而不需要依赖远程的服务器。PaddleX 支持将模型部署在 Android 等端侧设备上,详细的端侧部署流程请参考 PaddleX 端侧部署指南。

你可以根据业务需要选择合适的方式部署模型产线,进而进行后续的 AI 应用集成。

5. 二次开发

如果通用表格识别产线提供的默认模型权重在你的场景中精度或速度不满意,可以尝试利用你自己拥有的特定领域或应用场景的数据对现有模型进行进一步的微调,以提升产线在你场景中的识别效果。

5.1 模型微调

由于通用表格识别产线包含若干模块,产线效果如果不及预期,可能来自于其中任何一个模块。你可以对识别效果差的图片进行分析,确定是哪个模块存在问题,并参考下表对应的微调教程进行模型微调:

情形 微调模块 微调参考
表格结构识别错误或单元格定位错误 表格结构识别模块 表格结构识别模块微调教程
未能成功检测到表格所在区域 版面区域检测模块 版面区域检测模块微调教程
文本存在漏检 文本检测模块 文本检测模块微调教程
文本内容都不准 文本识别模块 文本识别模块微调教程
整图旋转矫正不准 文档图像方向分类模块 文档图像方向分类模块微调教程
图像扭曲矫正不准 文本图像矫正模块 暂不支持微调

以表格结构识别模块为例,其单模块训练配置可参考 paddlex/configs/modules/table_structure_recognition/SLANet_plus.yaml,包含数据集目录(dataset_dir)、训练轮数(epochs_iters: 10)、批大小(batch_size: 48)、学习率(learning_rate: 0.001)、预训练权重(pretrain_weight_path,默认指向 SLANet_plus 官方预训练权重)等训练超参,以及评估、导出、预测等阶段的配置。

5.2 模型应用

当使用私有数据集完成微调训练后,可获得本地模型权重文件。若需要使用微调后的模型权重,只需对产线配置文件做修改,将微调后模型权重的本地路径替换至产线配置文件中的对应位置即可:

SubModules:
  LayoutDetection:
    module_name: layout_detection
    model_name: PicoDet_layout_1x_table
    model_dir: null # 替换为微调后的版面区域检测模型权重路径

  TableStructureRecognition:
    module_name: table_structure_recognition
    model_name: SLANet_plus
    model_dir: null # 替换为微调后的表格结构识别模型权重路径

SubPipelines:
  DocPreprocessor:
    pipeline_name: doc_preprocessor
    use_doc_orientation_classify: True
    use_doc_unwarping: True
    SubModules:
      DocOrientationClassify:
        module_name: doc_text_orientation
        model_name: PP-LCNet_x1_0_doc_ori
        model_dir: null # 替换为微调后的文档图像方向分类模型权重路径

      DocUnwarping:
        module_name: image_unwarping
        model_name: UVDoc
        model_dir: null

  GeneralOCR:
    pipeline_name: OCR
    text_type: general
    use_doc_preprocessor: False
    use_textline_orientation: False
    SubModules:
      TextDetection:
        module_name: text_detection
        model_name: PP-OCRv5_server_det
        model_dir: null # 替换为微调后的文本检测模型权重路径
        limit_side_len: 960
        limit_type: max
        max_side_limit: 4000
        thresh: 0.3
        box_thresh: 0.4
        unclip_ratio: 1.5
      TextRecognition:
        module_name: text_recognition
        model_name: PP-OCRv5_server_rec
        model_dir: null # 替换为微调后文本识别的模型权重路径
        batch_size: 1
        score_thresh: 0

随后,参考 2.3/2.4 节中的命令行方式或 Python 脚本方式,加载修改后的产线配置文件即可完成推理(CLI 中 --pipeline 指定配置文件路径,Python 中 create_pipeline(pipeline="./my_path/table_recognition.yaml"))。

6. 多硬件支持

PaddleX 支持英伟达 GPU、昆仑芯 XPU、昇腾 NPU 和寒武纪 MLU 等多种主流硬件设备,仅需修改 --device 参数即可完成不同硬件之间的无缝切换。

例如,使用昇腾 NPU 进行产线推理的 CLI 命令为:

paddlex --pipeline table_recognition \
        --use_doc_orientation_classify=False \
        --use_doc_unwarping=False \
        --input table_recognition.jpg \
        --save_path ./output \
        --device npu:0

当然,也可以在 Python 脚本中 create_pipeline() 时或 predict() 时指定硬件设备(device 参数同样支持 gpu:0、npu:0、cpu 等写法)。若想在更多种类的硬件上使用通用表格识别产线,请参考 PaddleX 多硬件使用指南。

总结

PaddleX 通用表格识别产线以 SLANet_plus 表格结构识别模型为核心,配合文本检测/识别、版面检测、文档预处理等模块,形成了一套"定位表格 → 解析结构 → 填充文字 → 输出 HTML/Excel"的完整链路。通过本文介绍的 CLI 与 Python 两种接入方式、predict() 的参数调优、结果对象的多种保存方法、服务化部署的多语言调用示例,以及基于私有数据微调后替换 model_dir 的二次开发路径,你可以快速将表格识别能力集成到自己的业务系统中,并根据精度、速度、存储与硬件环境灵活选型。

登录后查看全文
PaddleX