版面解析是一种从文档图像中提取结构化信息的技术,主要用于将复杂的文档版面转换为机器可读的数据格式。这项技术在文档管理、信息提取和数据数字化等领域具有广泛的应用。版面解析通过结合光学字符识别(OCR)、图像处理和机器学习算法,能够识别和提取文档中的文本块、标题、段落、图片、表格以及其他版面元素。此过程通常包括版面分析、元素分析和数据格式化三个主要步骤,最终生成结构化的文档数据,提升数据处理的效率和准确性。本产线同时提供了灵活的服务化部署方式,支持在多种硬件上使用多种编程语言调用。不仅如此,本产线也提供了二次开发的能力,您可以基于本产线在您自己的数据集上训练调优,训练后的模型也可以无缝集成。
通用版面解析产线中包含必选的版面区域分析模块、通用OCR子产线,以及可选的文档图像预处理子产线、表格识别子产线、印章识别子产线和公式识别子产线。
如您更考虑模型精度,请选择精度较高的模型,如您更考虑模型推理速度,请选择推理速度较快的模型,如您更考虑模型存储大小,请选择存储大小较小的模型。
文档图像方向分类模块(可选):
| 模型 | 模型下载链接 | Top-1 Acc(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-LCNet_x1_0_doc_ori | 推理模型/训练模型 | 99.06 | 2.31 / 0.43 | 3.37 / 1.27 | 7 | 基于PP-LCNet_x1_0的文档图像分类模型,含有四个类别,即0度,90度,180度,270度 |
文本图像矫正模块(可选):
| 模型 | 模型下载链接 | CER | 模型存储大小(M) | 介绍 |
|---|---|---|---|---|
| UVDoc | 推理模型/训练模型 | 0.179 | 30.3 M | 高精度文本图像矫正模型 |
版面区域检测模块模型(必选):
| 模型 | 模型下载链接 | mAP(0.5)(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-DocLayout-L | 推理模型/训练模型 | 90.4 | 34.6244 / 10.3945 | 510.57 / - | 123.76 M | 基于RT-DETR-L在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的高精度版面区域定位模型 |
| PP-DocLayout-M | 推理模型/训练模型 | 75.2 | 13.3259 / 4.8685 | 44.0680 / 44.0680 | 22.578 | 基于PicoDet-L在包含中英文论文、杂志、合同、书本、试卷和研报等场景的自建数据集训练的精度效率平衡的版面区域定位模型 |
| PP-DocLayout-S | 推理模型/训练模型 | 70.9 | 8.3008 / 2.3794 | 10.0623 / 9.9296 | 4.834 | 基于PicoDet-S在中英文论文、杂志、合同、书本、试卷和研报等场景上自建数据集训练的高效率版面区域定位模型 |
| PicoDet_layout_1x | 推理模型/训练模型 | 86.8 | 9.03 / 3.10 | 25.82 / 20.70 | 7.4 | 基于PicoDet-1x在PubLayNet数据集训练的高效率版面区域定位模型,可定位包含文字、标题、表格、图片以及列表这5类区域 |
| PicoDet_layout_1x_table | 推理模型/训练模型 | 95.7 | 8.02 / 3.09 | 23.70 / 20.41 | 7.4 M | 基于PicoDet-1x在自建数据集训练的高效率版面区域定位模型,可定位包含表格这1类区域 |
| PicoDet-S_layout_3cls | 推理模型/训练模型 | 87.1 | 8.99 / 2.22 | 16.11 / 8.73 | 4.8 | 基于PicoDet-S轻量模型在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含3个类别:表格,图像和印章 |
| PicoDet-S_layout_17cls | 推理模型/训练模型 | 70.3 | 9.11 / 2.12 | 15.42 / 9.12 | 4.8 | 基于PicoDet-S轻量模型在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
| PicoDet-L_layout_3cls | 推理模型/训练模型 | 89.3 | 13.05 / 4.50 | 41.30 / 41.30 | 22.6 | 基于PicoDet-L在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含3个类别:表格,图像和印章 |
| PicoDet-L_layout_17cls | 推理模型/训练模型 | 79.9 | 13.50 / 4.69 | 43.32 / 43.32 | 22.6 | 基于PicoDet-L在中英文论文、杂志和研报等场景上自建数据集训练的高效率版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
| RT-DETR-H_layout_3cls | 推理模型/训练模型 | 95.9 | 114.93 / 27.71 | 947.56 / 947.56 | 470.1 | 基于RT-DETR-H在中英文论文、杂志和研报等场景上自建数据集训练的高精度版面区域定位模型,包含3个类别:表格,图像和印章 |
| RT-DETR-H_layout_17cls | 推理模型/训练模型 | 92.6 | 115.29 / 104.09 | 995.27 / 995.27 | 470.2 | 基于RT-DETR-H在中英文论文、杂志和研报等场景上自建数据集训练的高精度版面区域定位模型,包含17个版面常见类别,分别是:段落标题、图片、文本、数字、摘要、内容、图表标题、公式、表格、表格标题、参考文献、文档标题、脚注、页眉、算法、页脚、印章 |
表格结构识别模块(可选):
| 模型 | 模型下载链接 | 精度(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小 (M) | 介绍 |
|---|---|---|---|---|---|---|
| SLANet | 推理模型/训练模型 | 59.52 | 103.08 / 103.08 | 197.99 / 197.99 | 6.9 M | SLANet 是百度飞桨视觉团队自研的表格结构识别模型。该模型通过采用CPU 友好型轻量级骨干网络PP-LCNet、高低层特征融合模块CSP-PAN、结构与位置信息对齐的特征解码模块SLA Head,大幅提升了表格结构识别的精度和推理速度。 |
| SLANet_plus | 推理模型/训练模型 | 63.69 | 140.29 / 140.29 | 195.39 / 195.39 | 6.9 M | SLANet_plus 是百度飞桨视觉团队自研的表格结构识别模型SLANet的增强版。相较于SLANet,SLANet_plus 对无线表、复杂表格的识别能力得到了大幅提升,并降低了模型对表格定位准确性的敏感度,即使表格定位出现偏移,也能够较准确地进行识别。 |
文本检测模块(必选):
| 模型 | 模型下载链接 | 检测Hmean(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-OCRv4_server_det | 推理模型/训练模型 | 82.56 | 83.34 / 80.91 | 442.58 / 442.58 | 109 | PP-OCRv4 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署 |
| PP-OCRv4_mobile_det | 推理模型/训练模型 | 77.35 | 8.79 / 3.13 | 51.00 / 28.58 | 4.7 | PP-OCRv4 的移动端文本检测模型,效率更高,适合在端侧设备部署 |
| PP-OCRv3_mobile_det | 推理模型/训练模型 | 78.68 | 8.44 / 2.91 | 27.87 / 27.87 | 2.1 | PP-OCRv3 的移动端文本检测模型,效率更高,适合在端侧设备部署 |
| PP-OCRv3_server_det | 推理模型/训练模型 | 80.11 | 65.41 / 13.67 | 305.07 / 305.07 | 102.1 | PP-OCRv3 的服务端文本检测模型,精度更高,适合在性能较好的服务器上部署 |
| 模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-OCRv4_server_rec_doc | 推理模型/训练模型 | 81.53 | 6.65 / 6.65 | 32.92 / 32.92 | 74.7 M | PP-OCRv4_server_rec_doc是在PP-OCRv4_server_rec的基础上,在更多中文文档数据和PP-OCR训练数据的混合数据训练而成,增加了部分繁体字、日文、特殊字符的识别能力,可支持识别的字符为1.5万+,除文档相关的文字识别能力提升外,也同时提升了通用文字的识别能力 |
| PP-OCRv4_mobile_rec | 推理模型/训练模型 | 78.74 | 4.82 / 4.82 | 16.74 / 4.64 | 10.6 M | PP-OCRv4的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中 |
| PP-OCRv4_server_rec | 推理模型/训练模型 | 80.61 | 6.58 / 6.58 | 33.17 / 33.17 | 71.2 M | PP-OCRv4的服务器端模型,推理精度高,可以部署在多种不同的服务器上 |
| PP-OCRv3_mobile_rec | 推理模型/训练模型 | 72.96 | 5.87 / 5.87 | 9.07 / 4.28 | 9.2 M | PP-OCRv3的轻量级识别模型,推理效率高,可以部署在包含端侧设备的多种硬件设备中 |
| 模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| ch_SVTRv2_rec | 推理模型/训练模型 | 68.81 | 8.08 / 8.08 | 50.17 / 42.50 | 73.9 M | SVTRv2 是一种由复旦大学视觉与学习实验室(FVL)的OpenOCR团队研发的服务端文本识别模型,其在PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务中荣获一等奖,A榜端到端识别精度相比PP-OCRv4提升6%。 |
| 模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| ch_RepSVTR_rec | 推理模型/训练模型 | 65.07 | 5.93 / 5.93 | 20.73 / 7.32 | 22.1 M | RepSVTR 文本识别模型是一种基于SVTRv2 的移动端文本识别模型,其在PaddleOCR算法模型挑战赛 - 赛题一:OCR端到端识别任务中荣获一等奖,B榜端到端识别精度相比PP-OCRv4提升2.5%,推理速度持平。 |
| 模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| en_PP-OCRv4_mobile_rec | 推理模型/训练模型 | 70.39 | 4.81 / 4.81 | 16.10 / 5.31 | 6.8 M | 基于PP-OCRv4识别模型训练得到的超轻量英文识别模型,支持英文、数字识别 |
| en_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 70.69 | 5.44 / 5.44 | 8.65 / 5.57 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量英文识别模型,支持英文、数字识别 |
| 模型 | 模型下载链接 | 识别 Avg Accuracy(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| korean_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 60.21 | 5.40 / 5.40 | 9.11 / 4.05 | 8.6 M | 基于PP-OCRv3识别模型训练得到的超轻量韩文识别模型,支持韩文、数字识别 |
| japan_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 45.69 | 5.70 / 5.70 | 8.48 / 4.07 | 8.8 M | 基于PP-OCRv3识别模型训练得到的超轻量日文识别模型,支持日文、数字识别 |
| chinese_cht_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 82.06 | 5.90 / 5.90 | 9.28 / 4.34 | 9.7 M | 基于PP-OCRv3识别模型训练得到的超轻量繁体中文识别模型,支持繁体中文、数字识别 |
| te_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 95.88 | 5.42 / 5.42 | 8.10 / 6.91 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量泰卢固文识别模型,支持泰卢固文、数字识别 |
| ka_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 96.96 | 5.25 / 5.25 | 9.09 / 3.86 | 8.0 M | 基于PP-OCRv3识别模型训练得到的超轻量卡纳达文识别模型,支持卡纳达文、数字识别 |
| ta_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 76.83 | 5.23 / 5.23 | 10.13 / 4.30 | 8.0 M | 基于PP-OCRv3识别模型训练得到的超轻量泰米尔文识别模型,支持泰米尔文、数字识别 |
| latin_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 76.93 | 5.20 / 5.20 | 8.83 / 7.15 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量拉丁文识别模型,支持拉丁文、数字识别 |
| arabic_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 73.55 | 5.35 / 5.35 | 8.80 / 4.56 | 7.8 M | 基于PP-OCRv3识别模型训练得到的超轻量阿拉伯字母识别模型,支持阿拉伯字母、数字识别 |
| cyrillic_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 94.28 | 5.23 / 5.23 | 8.89 / 3.88 | 7.9 M | 基于PP-OCRv3识别模型训练得到的超轻量斯拉夫字母识别模型,支持斯拉夫字母、数字识别 |
| devanagari_PP-OCRv3_mobile_rec | 推理模型/训练模型 | 96.44 | 5.22 / 5.22 | 8.56 / 4.06 | 7.9 M | 基于PP-OCRv3识别模型训练得到的超轻量梵文字母识别模型,支持梵文字母、数字识别 |
文本行方向分类模块(可选):
| 模型 | 模型下载链接 | Top-1 Acc(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-LCNet_x0_25_textline_ori | 推理模型/训练模型 | 95.54 | - | - | 0.32 | 基于PP-LCNet_x0_25的文本行分类模型,含有两个类别,即0度,180度 |
公式识别模块(可选):
| 模型 | 模型下载链接 | BLEU score | normed edit distance | ExpRate (%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小 |
|---|---|---|---|---|---|---|---|
| LaTeX_OCR_rec | 推理模型/训练模型 | 0.8821 | 0.0823 | 40.01 | 2047.13 / 2047.13 | 10582.73 / 10582.73 | 89.7 M |
印章文本检测模块(可选):
| 模型 | 模型下载链接 | 检测Hmean(%) | GPU推理耗时(ms) [常规模式 / 高性能模式] |
CPU推理耗时(ms) [常规模式 / 高性能模式] |
模型存储大小(M) | 介绍 |
|---|---|---|---|---|---|---|
| PP-OCRv4_server_seal_det | 推理模型/训练模型 | 98.21 | 74.75 / 67.72 | 382.55 / 382.55 | 109 | PP-OCRv4的服务端印章文本检测模型,精度更高,适合在较好的服务器上部署 |
| PP-OCRv4_mobile_seal_det | 推理模型/训练模型 | 96.47 | 7.82 / 3.09 | 48.28 / 23.97 | 4.6 | PP-OCRv4的移动端印章文本检测模型,效率更高,适合在端侧部署 |
PaddleX 所提供的模型产线均可以快速体验效果,你可以在本地使用命令行或 Python 体验通用通用版面解析产线的效果。
在本地使用通用版面解析产线前,请确保您已经按照PaddleX本地安装教程完成了PaddleX的wheel包安装。
一行命令即可快速体验版面解析产线效果,使用 测试文件,并将 --input 替换为本地路径,进行预测
paddlex --pipeline layout_parsing \
--input demo_paper.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
--use_textline_orientation False \
--save_path ./output \
--device gpu:0
相关的参数说明可以参考2.2.2 Python脚本方式集成中的参数说明。
运行后,会将结果打印到终端上,结果如下:
{'res': {'input_path': 'demo_paper.png', 'model_settings': {'use_doc_preprocessor': True, 'use_general_ocr': True, 'use_seal_recognition': True, 'use_table_recognition': True, 'use_formula_recognition': True}, 'parsing_res_list': [{'layout_bbox': [46.905365, 44.05746, 565.6911, 217.74211], 'image': array([[[255, ..., 255],
...,
[188, ..., 175]],
...,
[[255, ..., 255],
...,
[255, ..., 255]]], dtype=uint8), 'image_text': 'Efficient Hybrid Encoder\nCaevIst s1\nCaaveJs2\nCCFF\n\nFusion\n00□0□000000', 'layout': 'single'}, {'layout_bbox': [42.178703, 227.34215, 570.1248, 284.377], 'text': 'Figure 4, Overview of RT-DETR. We feed the features from the last three stages of the backbone into the encoder. The eficient hybrid\nencoder transforms multi-scale features into a sequence of image features through the Attention-based Intra-scale Feature Interaction (AIFI)\nfeatures to serve as initial object queries for the decoder, Finaly, the decoder with auxiliary prediction heads iteratively optimizes object\nand the CNN-based Cross-scale Feature Fusion (CCFF), Then, the uncertainty-minimal query selection selects a fixed number of encoder\nqueries to generate categories and boxes.', 'layout': 'single'}, {'layout_bbox': [53.227856, 294.16644, 283.854, 396.24164], 'image': array([[[255, ..., 255],
...,
[255, ..., 255]],
...,
[[255, ..., 255],
...,
[255, ..., 255]]], dtype=uint8), 'image_text': '1x1Conv\nFusion\nC\nNX\n1x1Conv\nRepBlock\nCConcatenate\nElement-wise add\nFlatten', 'layout': 'double'}, {'layout_bbox': [99.52045, 401.63477, 240.27536, 411.01334], 'text': 'Figure 5. The fusion block in CCFF', 'layout': 'double'}, {'layout_bbox': [41.776196, 418.61166, 296.82672, 554.4149], 'text': 'D, Ds, not only significantly reduces latency (35% faster),\nbut also improves accuracy (0.4% AP higher). CCFF is opti-\nmized based on the cross-scale fusion module, which inserts\nseveral fusion blocks consisting of convolutional layers into\nthe fusion path. The role of the fusion block is to fuse two\nadjacent scale features into a new feature, and its structure is\nillustrated in Figure 5. The fusion block contains two 1 × 1\nconvolutions to adjust the number of channels, N RepBlocks\ncomposed of RepConv [8] are used for feature fusion, and\nthe two-path outputs are fused by element-wise add. We\nformulate the calculation of the hybrid encoder as:', 'layout': 'double'}, {'layout_bbox': [92.092064, 563.1221, 297.57217, 607.2598], 'formula': '\\begin{array}{r l}{\\mathcal{Q}}&{=\\mathcal{K}=\\mathcal{V}=\\mathtt{F l a t t e r n}(\\mathcal{S}_{5}),}\\\\ {\\mathcal{F}_{5}}&{=\\mathtt{R e s h a p e}(\\mathtt{A I F I}(\\mathcal{Q},\\mathcal{K},\\mathcal{V})),\\qquad\\quad(1)}\\\\ {\\mathcal{O}}&{=\\mathtt{C C F F}(\\{\\mathcal{S}_{3},\\mathcal{S}_{4},\\mathcal{F}_{5}\\}),}\\end{array}', 'layout': 'double'}, {'layout_bbox': [41.275124, 613.64154, 298.0696, 636.9947], 'text': 'where Reshape represents restoring the shape of the flat-\ntened feature to the same shape as S5', 'layout': 'double'}, {'layout_bbox': [41.01993, 645.3085, 253.87302, 656.61505], 'text': '4.3.Uncertainty-minimal Ouery Selection', 'layout': 'double'}, {'layout_bbox': [39.780045, 664.1547, 296.5302, 724.974], 'text': 'To reduce the difficulty of optimizing object queries in\nDETR, several subsequent works [42, 44, 45] propose query\nselection schemes, which have in common that they use the\nconfidence score to select the top K features from the en-\ncoder to initialize object queries (or just position queries).', 'layout': 'double'}, {'layout_bbox': [316.3008, 289.54156, 573.4635, 415.4659], 'text': 'The confidence score represents the likelihood that the fea-\nture includes foreground objects. Nevertheless, the detector\nare required to simultaneously model the category and loca-\ntion of objects, both of which determine the quality of the\nfeatures. Hence, the performance score of the feature is a la-\ntent variable that is jointly correlated with both classification\nand localization. Based on the analysis, the current query\nselection lead to a considerable level of uncertainty in the\nselected features, resulting in sub-optimal initialization for\nthe decoder and hindering the performance of the detector.', 'layout': 'double'}, {'layout_bbox': [316.1587, 417.67807, 575.0031, 541.93054], 'text': 'To address this problem, we propose the uncertainty mini-\nmal query selection scheme, which explicitly constructs and\noptimizes the epistemic uncertainty to model the joint latent\nvariable of encoder features, thereby providing high-quality\nqueries for the decoder. Specifically, the feature uncertainty\nL/ is defined as the discrepancy between the predicted dis-\ntributions of localization P and classification C in Eq. (2).\nTo minimize the uncertainty of the queries, we integrate\nthe uncertainty into the loss function for the gradient-based\noptimization in Eq. (3).', 'layout': 'double'}, {'layout_bbox': [343.82712, 551.06995, 573.45465, 589.9438], 'formula': '\\begin{array}{r l r}{\\mathcal{U}(\\hat{\\mathcal{X}})=\\|\\mathcal{P}(\\hat{\\mathcal{X}})-\\mathcal{C}(\\hat{\\mathcal{X}})\\|,\\hat{\\mathcal{X}}\\in\\mathbb{R}^{D}}&{{}(2)}&{}\\\\ {\\mathcal{L}(\\hat{\\mathcal{X}},\\hat{\\mathcal{Y}},\\mathcal{Y})=\\mathcal{L}_{t o x}(\\hat{\\mathbf{b}},\\mathbf{b})+\\mathcal{L}_{c l s}(\\mathcal{U}(\\hat{\\mathcal{X}}),\\hat{\\mathbf{c}},\\mathbf{c})}&{{}(3)}\\end{array}', 'layout': 'double'}, {'layout_bbox': [316.74704, 598.45776, 573.39526, 636.35236], 'text': 'where and y denote the prediction and ground truth.\n= (e, b), C and b represent the category and bounding\nbox respectively, X represent the encoder feature.', 'layout': 'double'}, {'layout_bbox': [315.35437, 638.09393, 572.0008, 724.53687], 'text': 'Effectiveness analysis. To analyze the effectiveness of thc\nuncertainty-minimal query selection, we visualize the clas-\nsification scores and IoU scores of the selected features on\nCOCO va1.2017, Figure 6. We draw the scatterplot with\nclassification scores greater than 0.5. The purple and green\nwith uncertainty-minimal query selection and vanilla query\ndots represent the selected features from the model trained', 'layout': 'double'}], 'doc_preprocessor_res': {'input_path': None, 'model_settings': {'use_doc_orientation_classify': True, 'use_doc_unwarping': True}, 'angle': 0}, 'layout_det_res': {'input_path': None, 'page_index': None, 'boxes': [{'cls_id': 1, 'label': 'image', 'score': 0.9874590635299683, 'coordinate': [46.905365, 44.05746, 565.6911, 217.74211]}, {'cls_id': 2, 'label': 'text', 'score': 0.9869957566261292, 'coordinate': [41.776196, 418.61166, 296.82672, 554.4149]}, {'cls_id': 2, 'label': 'text', 'score': 0.9792540073394775, 'coordinate': [39.780045, 664.1547, 296.5302, 724.974]}, {'cls_id': 2, 'label': 'text', 'score': 0.9792136549949646, 'coordinate': [316.3008, 289.54156, 573.4635, 415.4659]}, {'cls_id': 2, 'label': 'text', 'score': 0.9789648652076721, 'coordinate': [316.1587, 417.67807, 575.0031, 541.93054]}, {'cls_id': 1, 'label': 'image', 'score': 0.9786934852600098, 'coordinate': [53.227856, 294.16644, 283.854, 396.24164]}, {'cls_id': 2, 'label': 'text', 'score': 0.9765349626541138, 'coordinate': [315.35437, 638.09393, 572.0008, 724.53687]}, {'cls_id': 6, 'label': 'figure_title', 'score': 0.9575827717781067, 'coordinate': [42.178703, 227.34215, 570.1248, 284.377]}, {'cls_id': 2, 'label': 'text', 'score': 0.9554654359817505, 'coordinate': [41.275124, 613.64154, 298.0696, 636.9947]}, {'cls_id': 7, 'label': 'formula', 'score': 0.951255738735199, 'coordinate': [92.092064, 563.1221, 297.57217, 607.2598]}, {'cls_id': 7, 'label': 'formula', 'score': 0.9501133561134338, 'coordinate': [343.82712, 551.06995, 573.45465, 589.9438]}, {'cls_id': 6, 'label': 'figure_title', 'score': 0.9381633400917053, 'coordinate': [99.52045, 401.63477, 240.27536, 411.01334]}, {'cls_id': 2, 'label': 'text', 'score': 0.9283379316329956, 'coordinate': [316.74704, 598.45776, 573.39526, 636.35236]}, {'cls_id': 0, 'label': 'paragraph_title', 'score': 0.9257320761680603, 'coordinate': [41.01993, 645.3085, 253.87302, 656.61505]}]}, 'overall_ocr_res': {'input_path': None, 'page_index': None, 'model_settings': {'use_doc_preprocessor': False, 'use_textline_orientation': False}, 'dt_polys': array([[[169, 50],
...,
[169, 62]],
...,
[[ 39, 711],
...,
[ 39, 726]]], dtype=int16), 'text_det_params': {'limit_side_len': 960, 'limit_type': 'max', 'thresh': 0.3, 'box_thresh': 0.6, 'unclip_ratio': 2.0}, 'text_type': 'general', 'textline_orientation_angles': array([-1, ..., -1]), 'text_rec_score_thresh': 0, 'rec_texts': ['Efficient Hybrid Encoder', 'CaevIst s1', 'CaaveJs2', 'CCFF', '', 'Fusion', '00□0□000000', 'Figure 4, Overview of RT-DETR. We feed the features from the last three stages of the backbone into the encoder. The eficient hybrid', 'encoder transforms multi-scale features into a sequence of image features through the Attention-based Intra-scale Feature Interaction (AIFI)', 'features to serve as initial object queries for the decoder, Finaly, the decoder with auxiliary prediction heads iteratively optimizes object', 'and the CNN-based Cross-scale Feature Fusion (CCFF), Then, the uncertainty-minimal query selection selects a fixed number of encoder', 'queries to generate categories and boxes.', '1x1Conv', 'Fusion', 'The confidence score represents the likelihood that the fea-', 'C', 'ture includes foreground objects. Nevertheless, the detector', 'are required to simultaneously model the category and loca-', 'NX', 'tion of objects, both of which determine the quality of the', '1x1Conv', 'features. Hence, the performance score of the feature is a la-', 'RepBlock', 'tent variable that is jointly correlated with both classification', 'and localization. Based on the analysis, the current query', 'CConcatenate', 'Element-wise add', 'Flatten', 'selection lead to a considerable level of uncertainty in the', 'selected features, resulting in sub-optimal initialization for', 'Figure 5. The fusion block in CCFF', 'the decoder and hindering the performance of the detector.', 'D, Ds, not only significantly reduces latency (35% faster),', 'To address this problem, we propose the uncertainty mini-', 'but also improves accuracy (0.4% AP higher). CCFF is opti-', 'mal query selection scheme, which explicitly constructs and', 'mized based on the cross-scale fusion module, which inserts', 'optimizes the epistemic uncertainty to model the joint latent', 'several fusion blocks consisting of convolutional layers into', 'variable of encoder features, thereby providing high-quality', 'the fusion path. The role of the fusion block is to fuse two', 'queries for the decoder. Specifically, the feature uncertainty', 'adjacent scale features into a new feature, and its structure is', 'L/ is defined as the discrepancy between the predicted dis-', 'illustrated in Figure 5. The fusion block contains two 1 × 1', 'tributions of localization P and classification C in Eq. (2).', 'convolutions to adjust the number of channels, N RepBlocks', 'To minimize the uncertainty of the queries, we integrate', 'composed of RepConv [8] are used for feature fusion, and', 'the uncertainty into the loss function for the gradient-based', 'the two-path outputs are fused by element-wise add. We', 'optimization in Eq. (3).', 'formulate the calculation of the hybrid encoder as:', 'u(x)=P(x)-C(x),x∈RD', '(2)', '=K =V =F1atten(Ss),', 'F = Reshape(AIFI(Q,K,V)),', '(1)', 'C(x.y)= Lo(b,b)+Cc(u(x),e,c)(3)', 'O=CCFF({S,S,F})', 'where and y denote the prediction and ground truth.', 'where Reshape represents restoring the shape of the flat-', '= (e, b), C and b represent the category and bounding', 'tened feature to the same shape as S5', 'box respectively, X represent the encoder feature.', '4.3.Uncertainty-minimal Ouery Selection', 'Effectiveness analysis. To analyze the effectiveness of thc', 'uncertainty-minimal query selection, we visualize the clas-', 'To reduce the difficulty of optimizing object queries in', 'sification scores and IoU scores of the selected features on', 'DETR, several subsequent works [42, 44, 45] propose query', 'COCO va1.2017, Figure 6. We draw the scatterplot with', 'selection schemes, which have in common that they use the', 'classification scores greater than 0.5. The purple and green', 'confidence score to select the top K features from the en-', 'with uncertainty-minimal query selection and vanilla query', 'dots represent the selected features from the model trained', 'coder to initialize object queries (or just position queries).'], 'rec_scores': array([0.95921248, ..., 0.99757016]), 'rec_polys': array([[[169, 50],
...,
[169, 62]],
...,
[[ 39, 711],
...,
[ 39, 726]]], dtype=int16), 'rec_boxes': array([[169, ..., 62],
...,
[ 39, ..., 726]], dtype=int16)}, 'text_paragraphs_ocr_res': {'rec_polys': array([[[169, 50],
...,
[169, 62]],
...,
[[ 39, 711],
...,
[ 39, 726]]], dtype=int16), 'rec_texts': ['Efficient Hybrid Encoder', 'CaevIst s1', 'CaaveJs2', 'CCFF', '', 'Fusion', '00□0□000000', 'Figure 4, Overview of RT-DETR. We feed the features from the last three stages of the backbone into the encoder. The eficient hybrid', 'encoder transforms multi-scale features into a sequence of image features through the Attention-based Intra-scale Feature Interaction (AIFI)', 'features to serve as initial object queries for the decoder, Finaly, the decoder with auxiliary prediction heads iteratively optimizes object', 'and the CNN-based Cross-scale Feature Fusion (CCFF), Then, the uncertainty-minimal query selection selects a fixed number of encoder', 'queries to generate categories and boxes.', '1x1Conv', 'Fusion', 'The confidence score represents the likelihood that the fea-', 'C', 'ture includes foreground objects. Nevertheless, the detector', 'are required to simultaneously model the category and loca-', 'NX', 'tion of objects, both of which determine the quality of the', '1x1Conv', 'features. Hence, the performance score of the feature is a la-', 'RepBlock', 'tent variable that is jointly correlated with both classification', 'and localization. Based on the analysis, the current query', 'CConcatenate', 'Element-wise add', 'Flatten', 'selection lead to a considerable level of uncertainty in the', 'selected features, resulting in sub-optimal initialization for', 'Figure 5. The fusion block in CCFF', 'the decoder and hindering the performance of the detector.', 'D, Ds, not only significantly reduces latency (35% faster),', 'To address this problem, we propose the uncertainty mini-', 'but also improves accuracy (0.4% AP higher). CCFF is opti-', 'mal query selection scheme, which explicitly constructs and', 'mized based on the cross-scale fusion module, which inserts', 'optimizes the epistemic uncertainty to model the joint latent', 'several fusion blocks consisting of convolutional layers into', 'variable of encoder features, thereby providing high-quality', 'the fusion path. The role of the fusion block is to fuse two', 'queries for the decoder. Specifically, the feature uncertainty', 'adjacent scale features into a new feature, and its structure is', 'L/ is defined as the discrepancy between the predicted dis-', 'illustrated in Figure 5. The fusion block contains two 1 × 1', 'tributions of localization P and classification C in Eq. (2).', 'convolutions to adjust the number of channels, N RepBlocks', 'To minimize the uncertainty of the queries, we integrate', 'composed of RepConv [8] are used for feature fusion, and', 'the uncertainty into the loss function for the gradient-based', 'the two-path outputs are fused by element-wise add. We', 'optimization in Eq. (3).', 'formulate the calculation of the hybrid encoder as:', 'where and y denote the prediction and ground truth.', 'where Reshape represents restoring the shape of the flat-', '= (e, b), C and b represent the category and bounding', 'tened feature to the same shape as S5', 'box respectively, X represent the encoder feature.', '4.3.Uncertainty-minimal Ouery Selection', 'Effectiveness analysis. To analyze the effectiveness of thc', 'uncertainty-minimal query selection, we visualize the clas-', 'To reduce the difficulty of optimizing object queries in', 'sification scores and IoU scores of the selected features on', 'DETR, several subsequent works [42, 44, 45] propose query', 'COCO va1.2017, Figure 6. We draw the scatterplot with', 'selection schemes, which have in common that they use the', 'classification scores greater than 0.5. The purple and green', 'confidence score to select the top K features from the en-', 'with uncertainty-minimal query selection and vanilla query', 'dots represent the selected features from the model trained', 'coder to initialize object queries (or just position queries).'], 'rec_scores': array([0.95921248, ..., 0.99757016]), 'rec_boxes': array([[169, ..., 62],
...,
[ 39, ..., 726]], dtype=int16)}, 'formula_res_list': [{'input_path': None, 'page_index': None, 'rec_formula': '\\begin{array}{r l}{\\mathcal{Q}}&{=\\mathcal{K}=\\mathcal{V}=\\mathtt{F l a t t e r n}(\\mathcal{S}_{5}),}\\\\ {\\mathcal{F}_{5}}&{=\\mathtt{R e s h a p e}(\\mathtt{A I F I}(\\mathcal{Q},\\mathcal{K},\\mathcal{V})),\\qquad\\quad(1)}\\\\ {\\mathcal{O}}&{=\\mathtt{C C F F}(\\{\\mathcal{S}_{3},\\mathcal{S}_{4},\\mathcal{F}_{5}\\}),}\\end{array}', 'formula_region_id': 1, 'dt_polys': [92.092064, 563.1221, 297.57217, 607.2598]}, {'input_path': None, 'page_index': None, 'rec_formula': '\\begin{array}{r l r}{\\mathcal{U}(\\hat{\\mathcal{X}})=\\|\\mathcal{P}(\\hat{\\mathcal{X}})-\\mathcal{C}(\\hat{\\mathcal{X}})\\|,\\hat{\\mathcal{X}}\\in\\mathbb{R}^{D}}&{{}(2)}&{}\\\\ {\\mathcal{L}(\\hat{\\mathcal{X}},\\hat{\\mathcal{Y}},\\mathcal{Y})=\\mathcal{L}_{t o x}(\\hat{\\mathbf{b}},\\mathbf{b})+\\mathcal{L}_{c l s}(\\mathcal{U}(\\hat{\\mathcal{X}}),\\hat{\\mathbf{c}},\\mathbf{c})}&{{}(3)}\\end{array}', 'formula_region_id': 2, 'dt_polys': [343.82712, 551.06995, 573.45465, 589.9438]}]}}
运行结果参数说明可以参考2.2.2 Python脚本方式集成中的结果解释。
您可以通过 --save_path 自定义保存路径,随后结构化的json结果将被保存在指定路径下。
几行代码即可完成产线的快速推理,以通用版面解析产线为例:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="layout_parsing")
output = pipeline.predict(
input="./demo_paper.png",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
for res in output:
res.print() ## 打印预测的结构化输出
res.save_to_img(save_path="./output/") ## 保存当前图像的所有子模块预测的可视化图像结果
res.save_to_json(save_path="./output/") ## 保存当前图像的结构化json结果
res.save_to_xlsx(save_path="./output/") ## 保存当前图像的子表格xlsx格式的结果
res.save_to_html(save_path="./output/") ## 保存当前图像的子表格html格式的结果
在上述 Python 脚本中,执行了如下几个步骤:
(1)实例化 create_pipeline 实例化产线对象:具体参数说明如下:
| 参数 | 参数说明 | 参数类型 | 默认值 |
|---|---|---|---|
pipeline |
产线名称或是产线配置文件路径。如为产线名称,则必须为 PaddleX 所支持的产线。 | str |
None |
config |
产线配置文件路径。 | str |
None |
device |
产线推理设备。支持指定GPU具体卡号,如“gpu:0”,其他硬件具体卡号,如“npu:0”,CPU如“cpu”。 | str |
gpu:0 |
use_hpip |
是否启用高性能推理,仅当该产线支持高性能推理时可用。 | bool |
False |
(2)调用版面解析产线对象的 predict() 方法进行推理预测。该方法将返回一个 generator。以下是 predict() 方法的参数及其说明:
| 参数 | 参数说明 | 参数类型 | 可选项 | 默认值 |
|---|---|---|---|---|
input |
待预测数据,支持多种输入类型,必填 | Python Var|str|list |
|
None |
device |
产线推理设备 | str|None |
|
None |
use_doc_orientation_classify |
是否使用文档方向分类模块 | bool|None |
|
None |
use_doc_unwarping |
是否使用文档扭曲矫正模块 | bool|None |
|
None |
use_textline_orientation |
是否使用文本行方向分类模块 | bool|None |
|
None |
use_general_ocr |
是否使用 OCR 子产线 | bool|None |
|
None |
use_seal_recognition |
是否使用印章识别子产线 | bool|None |
|
None |
use_table_recognition |
是否使用表格识别子产线 | bool|None |
|
None |
use_formula_recognition |
是否使用公式识别子产线 | bool|None |
|
None |
layout_threshold |
版面模型得分阈值 | float|dict|None |
|
None |
layout_nms |
版面区域检测模型是否使用NMS后处理 | bool|None |
|
None |
layout_unclip_ratio |
版面区域检测模型检测框的扩张系数 | float|Tuple[float,float]|None |
|
None |
layout_merge_bboxes_mode |
版面区域检测的重叠框过滤方式 | str|None |
|
None |
text_det_limit_side_len |
文本检测的图像边长限制 | int|None |
|
None |
text_det_limit_type |
文本检测的图像边长限制类型 | str|None |
|
None |
text_det_thresh |
检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是文字像素点 | float|None |
|
None |
text_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是文字区域 | float|None |
|
None |
text_det_unclip_ratio |
文本检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大 | float|None |
|
None |
text_rec_score_thresh |
文本识别阈值,得分大于该阈值的文本结果会被保留 | float|None |
|
None |
seal_det_limit_side_len |
印章检测的图像边长限制 | int|None |
|
None |
seal_det_limit_type |
印章检测的图像边长限制类型 | str|None |
|
None |
seal_det_thresh |
检测像素阈值,输出的概率图中,得分大于该阈值的像素点才会被认为是印章像素点 | float|None |
|
None |
seal_det_box_thresh |
检测框阈值,检测结果边框内,所有像素点的平均得分大于该阈值时,该结果会被认为是印章区域 | float|None |
|
None |
seal_det_unclip_ratio |
印章检测扩张系数,使用该方法对文字区域进行扩张,该值越大,扩张的面积越大 | float|None |
|
None |
seal_rec_score_thresh |
印章识别阈值,得分大于该阈值的文本结果会被保留 | float|None |
|
None |
(3)对预测结果进行处理:每个样本的预测结果均为对应的Result对象,且支持打印、保存为图片、保存为json文件的操作:
| 方法 | 方法说明 | 参数 | 参数类型 | 参数说明 | 默认值 |
|---|---|---|---|---|---|
print() |
打印结果到终端 | format_json |
bool |
是否对输出内容进行使用 JSON 缩进格式化 |
True |
indent |
int |
指定缩进级别,以美化输出的 JSON 数据,使其更具可读性,仅当 format_json 为 True 时有效 |
4 | ||
ensure_ascii |
bool |
控制是否将非 ASCII 字符转义为 Unicode。设置为 True 时,所有非 ASCII 字符将被转义;False 则保留原始字符,仅当format_json为True时有效 |
False |
||
save_to_json() |
将结果保存为json格式的文件 | save_path |
str |
保存的文件路径,当为目录时,保存文件命名与输入文件类型命名一致 | 无 |
indent |
int |
指定缩进级别,以美化输出的 JSON 数据,使其更具可读性,仅当 format_json 为 True 时有效 |
4 | ||
ensure_ascii |
bool |
控制是否将非 ASCII 字符转义为 Unicode。设置为 True 时,所有非 ASCII 字符将被转义;False 则保留原始字符,仅当format_json为True时有效 |
False |
||
save_to_img() |
将中间各个模块的可视化图像保存在png格式的图像 | save_path |
str |
保存的文件路径,支持目录或文件路径 | 无 |
save_to_html() |
将文件中的表格保存为html格式的文件 | save_path |
str |
保存的文件路径,支持目录或文件路径 | 无 |
save_to_xlsx() |
将文件中的表格保存为xlsx格式的文件 | save_path |
str |
保存的文件路径,支持目录或文件路径 | 无 |
调用print() 方法会将结果打印到终端,打印到终端的内容解释如下:
input_path: (str) 待预测图像的输入路径
page_index: (Union[int, None]) 如果输入是PDF文件,则表示当前是PDF的第几页,否则为 None
model_settings: (Dict[str, bool]) 配置产线所需的模型参数
use_doc_preprocessor: (bool) 控制是否启用文档预处理子产线use_general_ocr: (bool) 控制是否启用 OCR 子产线use_seal_recognition: (bool) 控制是否启用印章识别子产线use_table_recognition: (bool) 控制是否启用表格识别子产线use_formula_recognition: (bool) 控制是否启用公式识别子产线parsing_res_list: (List[Dict]) 解析结果的列表,每个元素为一个字典,列表顺序为解析后的阅读顺序。
block_bbox: (np.ndarray) 版面区域的边界框。block_label: (str) 版面区域的标签,例如text, table等。block_content: (str) 内容为版面区域内的内容。overall_ocr_res: (Dict[str, Union[List[str], List[float], numpy.ndarray]]) 全局 OCR 结果的字典
input_path: (Union[str, None]) 图像OCR子产线接受的图像路径,当输入为numpy.ndarray时,保存为Nonemodel_settings: (Dict) OCR子产线的模型配置参数dt_polys: (List[numpy.ndarray]) 文本检测的多边形框列表。每个检测框由4个顶点坐标构成的numpy数组表示,数组shape为(4, 2),数据类型为int16dt_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_type: (str) 文本检测的类型,当前固定为"general"
textline_orientation_angles: (List[int]) 文本行方向分类的预测结果。启用时返回实际角度值(如[0,0,1]
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
formula_res_list: (List[Dict[str, Union[numpy.ndarray, List[float], str]]]) 公式识别结果列表,每个元素为一个字典
rec_formula: (str) 公式识别结果rec_polys: (numpy.ndarray) 公式检测框,shape为(4, 2),dtype为int16formula_region_id: (int) 公式所在的区域编号seal_res_list: (List[Dict[str, Union[numpy.ndarray, List[float], str]]]) 印章识别结果列表,每个元素为一个字典
input_path: (str) 印章图像的输入路径model_settings: (Dict) 印章识别子产线的模型配置参数dt_polys: (List[numpy.ndarray]) 印章检测框列表,格式同dt_polystext_det_params: (Dict[str, Dict[str, int, float]]) 印章检测模块的配置参数, 具体参数含义同上text_type: (str) 印章检测的类型,当前固定为"seal"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_polysrec_boxes: (numpy.ndarray) 检测框的矩形边界框数组,shape为(n, 4),dtype为int16。每一行表示一个矩形table_res_list: (List[Dict[str, Union[numpy.ndarray, List[float], str]]]) 表格识别结果列表,每个元素为一个字典
cell_box_list: (List[numpy.ndarray]) 表格单元格的边界框列表pred_html: (str) 表格的HTML格式字符串table_ocr_pred: (dict) 表格的OCR识别结果
rec_polys: (List[numpy.ndarray]) 单元格的检测框列表rec_texts: (List[str]) 单元格的识别结果rec_scores: (List[float]) 单元格的识别置信度rec_boxes: (numpy.ndarray) 检测框的矩形边界框数组,shape为(n, 4),dtype为int16。每一行表示一个矩形调用save_to_json() 方法会将上述内容保存到指定的save_path中,如果指定为目录,则保存的路径为save_path/{your_img_basename}.json,如果指定为文件,则直接保存到该文件中。由于json文件不支持保存numpy数组,因此会将其中的numpy.array类型转换为列表形式。
调用save_to_img() 方法会将可视化结果保存到指定的save_path中,如果指定为目录,则保存的路径为save_path/{your_img_basename}_ocr_res_img.{your_img_extension},如果指定为文件,则直接保存到该文件中。(产线通常包含较多结果图片,不建议直接指定为具体的文件路径,否则多张图会被覆盖,仅保留最后一张图)
此外,也支持通过属性获取带结果的可视化图像和预测结果,具体如下:
| 属性 | 属性说明 |
|---|---|
json |
获取预测的 json 格式的结果 |
img |
获取格式为 dict 的可视化图像 |
json 属性获取的预测结果为dict类型的数据,相关内容与调用 save_to_json() 方法保存的内容一致。img 属性返回的预测结果是一个字典类型的数据。其中,键分别为 layout_det_res、overall_ocr_res、text_paragraphs_ocr_res、formula_res_region1、table_cell_img 和 seal_res_region1,对应的值是 Image.Image 对象:分别用于显示版面区域检测、OCR、OCR文本段落、公式、表格和印章结果的可视化图像。如果没有使用可选模块,则字典中只包含 layout_det_res。此外,您可以获取版面解析产线配置文件,并加载配置文件进行预测。可执行如下命令将结果保存在 my_path 中:
paddlex --get_pipeline_config layout_parsing --save_path ./my_path
若您获取了配置文件,即可对版面解析产线各项配置进行自定义,只需要修改 create_pipeline 方法中的 pipeline 参数值为产线配置文件路径即可。示例如下:
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="./my_path/layout_parsing.yaml")
output = pipeline.predict(
input="./demo_paper.png",
use_doc_orientation_classify=False,
use_doc_unwarping=False,
use_textline_orientation=False,
)
for res in output:
res.print()
res.save_to_img("./output/")
res.save_to_json("./output/")
注: 配置文件中的参数为产线初始化参数,如果希望更改通用版面解析产线初始化参数,可以直接修改配置文件中的参数,并加载配置文件进行预测。同时,CLI 预测也支持传入配置文件,--pipeline 指定配置文件的路径即可。
如果产线可以达到您对产线推理速度和精度的要求,您可以直接进行开发集成/部署。
若您需要将产线直接应用在您的Python项目中,可以参考 2.2 Python脚本方式中的示例代码。
此外,PaddleX 也提供了其他三种部署方式,详细说明如下:
🚀 高性能推理:在实际生产环境中,许多应用对部署策略的性能指标(尤其是响应速度)有着较严苛的标准,以确保系统的高效运行与用户体验的流畅性。为此,PaddleX 提供高性能推理插件,旨在对模型推理及前后处理进行深度性能优化,实现端到端流程的显著提速,详细的高性能推理流程请参考PaddleX高性能推理指南。
☁️ 服务化部署:服务化部署是实际生产环境中常见的一种部署形式。通过将推理功能封装为服务,客户端可以通过网络请求来访问这些服务,以获取推理结果。PaddleX 支持多种产线服务化部署方案,详细的产线服务化部署流程请参考PaddleX服务化部署指南。
以下是基础服务化部署的API参考与多语言服务调用示例:
对于服务提供的主要操作: 服务提供的主要操作如下: 进行版面解析。API参考
200,响应体的属性如下:
名称
类型
含义
logIdstring请求的UUID。
errorCodeinteger错误码。固定为
0。
errorMsgstring错误说明。固定为
"Success"。
resultobject操作结果。
名称
类型
含义
logIdstring请求的UUID。
errorCodeinteger错误码。与响应状态码相同。
errorMsgstring错误说明。
inferPOST /layout-parsing
名称
类型
含义
是否必填
filestring服务器可访问的图像文件或PDF文件的URL,或上述类型文件内容的Base64编码结果。对于超过10页的PDF文件,只有前10页的内容会被使用。
是
fileTypeinteger|null文件类型。
0表示PDF文件,1表示图像文件。若请求体无此属性,则将根据URL推断文件类型。否
useDocOrientationClassifyboolean | null参见产线
predict 方法中的 use_doc_orientation_classify 参数说明。否
useDocUnwarpingboolean | null参见产线
predict 方法中的 use_doc_unwarping 参数说明。否
useTextlineOrientationboolean | null参见产线
predict 方法中的 use_textline_orientation 参数说明。否
useGeneralOcrboolean | null参见产线
predict 方法中的 use_general_ocr 参数说明。否
useSealRecognitionboolean | null参见产线
predict 方法中的 use_seal_recognition 参数说明。否
useTableRecognitionboolean | null参见产线
predict 方法中的 use_table_recognition 参数说明。否
useFormulaRecognitionboolean | null参见产线
predict 方法中的 use_formula_recognition 参数说明。否
textDetLimitSideLeninteger | null参见产线
predict 方法中的 text_det_limit_side_len 参数说明。否
textDetLimitTypestring | null参见产线
predict 方法中的 text_det_limit_type 参数说明。否
textDetThreshnumber | null参见产线
predict 方法中的 text_det_thresh 参数说明。否
textDetBoxThreshnumber | null参见产线
predict 方法中的 text_det_box_thresh 参数说明。否
textDetUnclipRationumber | null参见产线
predict 方法中的 text_det_unclip_ratio 参数说明。否
textRecScoreThreshnumber | null参见产线
predict 方法中的 text_rec_score_thresh 参数说明。否
sealDetLimitSideLeninteger | null参见产线
predict 方法中的 seal_det_limit_side_len 参数说明。否
sealDetLimitTypestring | null参见产线
predict 方法中的 seal_det_limit_type 参数说明。否
sealDetThreshnumber | null参见产线
predict 方法中的 seal_det_thresh 参数说明。否
sealDetBoxThreshnumber | null参见产线
predict 方法中的 seal_det_box_thresh 参数说明。否
sealDetUnclipRationumber | null参见产线
predict 方法中的 seal_det_unclip_ratio 参数说明。否
sealRecScoreThreshnumber | null参见产线
predict 方法中的 seal_rec_score_thresh 参数说明。否
layoutThresholdnumber | null参见产线
predict 方法中的 layout_threshold 参数说明。否
layoutNmsboolean | null参见产线
predict 方法中的 layout_nms 参数说明。否
layoutUnclipRationumber | array | null参见产线
predict 方法中的 layout_unclip_ratio 参数说明。否
layoutMergeBboxesModestring | null参见产线
predict 方法中的 layout_merge_bboxes_mode 参数说明。否
result具有如下属性:
名称
类型
含义
layoutParsingResultsarray版面解析结果。数组长度为1(对于图像输入)或文档页数与10中的较小者(对于PDF输入)。对于PDF输入,数组中的每个元素依次表示PDF文件中每一页的处理结果。
dataInfoobject输入数据信息。
layoutParsingResults中的每个元素为一个object,具有如下属性:
名称
类型
含义
prunedResultobject产线对象的
predict 方法生成结果的 JSON 表示中 res 字段的简化版本,其中去除了 input_path 字段
outputImagesobject | null参见产线预测结果中的
img 属性说明。图像为JPEG格式,使用Base64编码。
inputImagestring | null输入图像。图像为JPEG格式,使用Base64编码。
多语言调用服务示例
Python
import base64
import requests
API_URL = "http://localhost:8080/layout-parsing" # 服务URL 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, # Base64编码的文件内容或者文件URL
"fileType": 1,
}
response = requests.post(API_URL, json=payload)
assert response.status_code == 200 result = response.json()["result"] print("\nDetected layout elements:") for i, res in enumerate(result["layoutParsingResults"]):
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}")
📱 端侧部署:端侧部署是一种将计算和数据处理功能放在用户设备本身上的方式,设备可以直接处理数据,而不需要依赖远程的服务器。PaddleX 支持将模型部署在 Android 等端侧设备上,详细的端侧部署流程请参考PaddleX端侧部署指南。 您可以根据需要选择合适的方式部署模型产线,进而进行后续的 AI 应用集成。
如果通用版面解析产线提供的默认模型权重在您的场景中,精度或速度不满意,您可以尝试利用您自己拥有的特定领域或应用场景的数据对现有模型进行进一步的微调,以提升通用版面解析产线的在您的场景中的识别效果。
由于通用版面解析产线包含7个模块,模型产线的效果不及预期可能来自于其中任何一个模块。
由于通用版面解析产线包含若干模块,模型产线的效果不及预期可能来自于其中任何一个模块。。您可以对提取效果差的 case 进行分析,通过可视化图像,确定是哪个模块存在问题,并参考以下表格中对应的微调教程链接进行模型微调。
| 情形 | 微调模块 | 微调参考链接 |
|---|---|---|
| 版面区域检测不准,如印章、表格未检出等 | 版面区域检测模块 | 链接 |
| 表格结构识别不准 | 表格结构识别模块 | 链接 |
| 公式识别不准 | 公式识别模块 | 链接 |
| 印章文本存在漏检 | 印章文本检测模块 | 链接 |
| 文本存在漏检 | 文本检测模块 | 链接 |
| 文本内容都不准 | 文本识别模块 | 链接 |
| 垂直或者旋转文本行矫正不准 | 文本行方向分类模块 | 链接 |
| 整图旋转矫正不准 | 文档图像方向分类模块 | 链接 |
| 图像扭曲矫正不准 | 文本图像矫正模块 | 暂不支持微调 |
当您使用私有数据集完成微调训练后,可获得本地模型权重文件。
若您需要使用微调后的模型权重,只需对产线配置文件做修改,将微调后模型权重的本地路径替换至产线配置文件中的对应位置即可:
......
SubModules:
LayoutDetection:
module_name: layout_detection
model_name: RT-DETR-H_layout_17cls
model_dir: null # 替换为微调后的版面区域检测模型权重路径
......
SubPipelines:
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
thresh: 0.3
box_thresh: 0.6
unclip_ratio: 2.0
TextRecognition:
module_name: text_recognition
model_name: PP-OCRv4_server_rec
model_dir: null # 替换为微调后的文本识别模型权重路径
batch_size: 1
score_thresh: 0
......
随后, 参考本地体验中的命令行方式或 Python 脚本方式,加载修改后的产线配置文件即可。
PaddleX 支持英伟达 GPU、昆仑芯 XPU、昇腾 NPU和寒武纪 MLU 等多种主流硬件设备,仅需修改 --device参数即可完成不同硬件之间的无缝切换。
例如,您使用昇腾 NPU 进行版面解析产线的推理,使用的 CLI 命令为:
paddlex --pipeline layout_parsing \
--input demo_paper.png \
--use_doc_orientation_classify False \
--use_doc_unwarping False \
--use_textline_orientation False \
--save_path ./output \
--device npu:0
当然,您也可以在 Python 脚本中 create_pipeline() 时或者 predict() 时指定硬件设备。
若您想在更多种类的硬件上使用通用版面解析产线,请参考PaddleX多硬件使用指南。