PaddleOCR PP-Structure 结构化文档分析快速上手:环境搭建、命令行与 Python 调用全指南

PaddleOCR PP-Structure 结构化文档分析快速上手:环境搭建、命令行与 Python 调用全指南 PaddleOCR PP-Structure 结构化文档分析快速上手环境搭建、命令行与 Python 调用全指南【免费下载链接】PaddleOCR飞桨多语言OCR工具包实用超轻量OCR系统支持80种语言识别提供数据标注与合成工具支持服务器、移动端、嵌入式及IoT设备端的训练与部署 Awesome multilingual OCR toolkits based on PaddlePaddle (practical ultra lightweight OCR system, support 80 languages recognition, provide data annotation and synthesis tools, support training and deployment among server, mobile, embedded and IoT devices)项目地址: https://gitcode.com/paddlepaddle/PaddleOCRPP-Structure 是 PaddleOCR 生态中面向文档结构化分析的解决方案能够在版面分析、表格识别、图像方向矫正、公式识别与版面复原PDF/OCR 转 Word、Markdown等多个任务上开箱即用。本文以docs/version2.x/ppstructure/quick_start.en.md为核心骨架结合仓库源码如 ppstructure/predict_system.py、ppstructure/utility.py补充实现细节与默认参数依据帮助读者在 10 分钟内完成环境准备并通过命令行或 Python 脚本跑通从图片/PDF 输入到结构化 JSON、Excel、docx、Markdown 输出的完整链路。1. 环境准备1.1 安装 PaddlePaddle若尚未准备 Python 环境请先参考 环境准备文档对应中文版为 environment.md。PP-Structure 基于 PaddlePaddle 深度学习框架运行请按机器是否具备 GPU 选择安装方式CUDA 11.8 GPU 版本python3 -m pip install paddlepaddle-gpu2.6 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/CUDA 12.3 GPU 版本python3 -m pip install paddlepaddle-gpu2.6 -i https://www.paddlepaddle.org.cn/packages/stable/cu123/CPU 版本无可用 GPU 的机器python3 -m pip install paddlepaddle2.6 -i https://www.paddlepaddle.org.cn/packages/stable/cpu/说明命令中的2.6表示安装 2.6 及以下版本。本文档面向 PaddleOCR 2.x 分支对应 PaddlePaddle 2.6 系列更详细的软件版本兼容要求请以 PaddlePaddle 官方安装指引为准。注意上述命令中的-i指定了 PaddlePaddle 官方的国内镜像源若网络环境可直连官方源也可去掉该参数。1.2 安装 PaddleOCR whl 包python3 -m pip install paddleocr3.0 # 安装图像方向分类依赖包 paddleclas不使用图像方向分类时可跳过 python3 -m pip install paddleclas安装paddleocr3.0即获取 2.x 版本的 PP-Structure 功能PPStructure类、draw_structure_result、save_structure_res等。其中paddleclas是可选依赖仅在开启--image_orientationtrue图像方向矫正时被加载——从源码可见ppstructure/predict_system.py 中StructureSystem.__init__只有在args.image_orientation为真时才import paddleclas并实例化PaddleClas(model_nametext_image_orientation)。安装完成后whl 包内自带示例图片与 PDF如命令中使用的ppstructure/docs/table/1.png、ppstructure/docs/recovery/UnrealText.pdf可直接用于本文所有示例命令。2. 命令行快速使用命令行统一入口为paddleocr使用--typestructure进入结构化分析模式。不同任务通过组合--image_orientation、--layout、--table、--ocr、--formula、--recovery等开关进行编排。2.1 图像方向矫正 版面分析 表格识别# 临时禁用新 IR 特性 export FLAGS_enable_pir_api0 paddleocr --image_dirppstructure/docs/table/1.png --typestructure --image_orientationtrue这是最完整的组合链路先由图像方向分类模型矫正旋转90°/180°/270°再做版面分析最后对版面内的文本区域执行 OCR、对表格区域执行表格结构识别。FLAGS_enable_pir_api0用于在 PaddlePaddle 2.6 环境下临时关闭新式 IRPIR接口避免旧版模型推理时的兼容性问题。2.2 版面分析 表格识别paddleocr --image_dirppstructure/docs/table/1.png --typestructure默认配置即执行版面分析layoutTrue、表格识别tableTrue与文本区域 OCRocrTrue适用于大多数扫描文档、论文截图等场景。2.3 仅版面分析paddleocr --image_dirppstructure/docs/table/1.png --typestructure --tablefalse --ocrfalse关闭表格识别与 OCR 后仅输出版面区域划分结果区域类型、bbox、置信度可用于版面预分析或后续自定义处理。2.4 仅表格识别paddleocr --image_dirppstructure/docs/table/table.jpg --typestructure --layoutfalse关闭版面分析后整张图片被当作一个表格区域直接送入表格结构模型。从 ppstructure/predict_system.py 可见当layout_predictor为None时代码会构造一个dict(bboxNone, labeltable, score0.0)的默认版面结果将整图视为表格处理。2.5 关键信息抽取关键信息抽取KIE目前不支持通过 whl 包直接使用详细使用教程请参考 关键信息抽取文档对应中文版 kie.md。在仓库源码中KIE 模式对应--modekie会加载 ppstructure/kie/predict_kie_token_ser_re.py 中的SerRePredictor通过命令行脚本 ppstructure/predict_system.py 或独立预测脚本使用。2.6 版面复原Layout Recovery版面复原提供两种方式详细教程请参考 版面复原文档对应中文版 recovery_to_doc.mdPDF parse 方式直接解析 PDF 内嵌文本仅支持 PDF 输入paddleocr --image_dirppstructure/docs/recovery/UnrealText.pdf --typestructure --recoverytrue --use_pdf2docx_apitrue该方式通过pdf2docx库的Converter将 PDF 直接转换为 docx见 ppstructure/predict_system.py不经过 OCR 模型速度更快适合电子版 PDF。OCR 方式对扫描件/图片执行版面分析 OCR 表格识别再将结果按阅读顺序重排并输出 docxpaddleocr --image_dirppstructure/docs/table/1.png --typestructure --recoverytrue --langenOCR 方式内部会调用 ppstructure/recovery/recovery_to_doc.py 的sorted_layout_boxes与convert_info_docx完成区域排序与 Word 文档生成。2.7 版面复原PDF 转 Markdown不使用 LaTeXOCR 模型做公式识别默认paddleocr --image_dirppstructure/docs/recovery/UnrealText.pdf --typestructure --recoverytrue --recovery_to_markdowntrue --langen使用 LaTeXOCR 模型做公式识别此时必须使用中文版面模型paddleocr --image_dirppstructure/docs/recovery/UnrealText.pdf --typestructure --recoverytrue --formulatrue --recovery_to_markdowntrue --langch--recovery_to_markdowntrue会在 docx 生成之后额外调用 ppstructure/recovery/recovery_to_markdown.py 的convert_info_markdown将复原结果输出为 Markdown 文件便于直接进入 RAG、知识库等下游流程。3. Python 脚本使用Python 脚本方式通过PPStructure类完成同样的编排且能拿到结构化返回结果做二次处理。核心 API 位于paddleocr包可视化与保存工具为draw_structure_result与save_structure_res实现位于 ppstructure/utility.py 与 ppstructure/predict_system.py。3.1 图像方向矫正 版面分析 表格识别import os import cv2 from paddleocr import PPStructure,draw_structure_result,save_structure_res table_engine PPStructure(show_logTrue, image_orientationTrue) save_folder ./output img_path ppstructure/docs/table/1.png img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder,os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line) from PIL import Image font_path doc/fonts/simfang.ttf # PaddleOCR下提供字体包 image Image.open(img_path).convert(RGB) im_show draw_structure_result(image, result,font_pathfont_path) im_show Image.fromarray(im_show) im_show.save(result.jpg)draw_structure_result会根据每个区域的type用不同颜色绘制 bbox 并标注区域类型同时对非表格/公式区域叠加 OCR 文本框save_structure_res则将结果写入res.txt、表格导出为.xlsx、图片区域裁剪保存为.jpg。font_path指向doc/fonts/simfang.ttf该字体文件在仓库 doc/fonts/ 目录下提供用于在可视化结果中正确渲染中文。3.2 版面分析 表格识别import os import cv2 from paddleocr import PPStructure,draw_structure_result,save_structure_res table_engine PPStructure(show_logTrue) save_folder ./output img_path ppstructure/docs/table/1.png img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder,os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line) from PIL import Image font_path doc/fonts/simfang.ttf # font provided in PaddleOCR image Image.open(img_path).convert(RGB) im_show draw_structure_result(image, result,font_pathfont_path) im_show Image.fromarray(im_show) im_show.save(result.jpg)3.3 仅版面分析import os import cv2 from paddleocr import PPStructure,save_structure_res table_engine PPStructure(tableFalse, ocrFalse, show_logTrue) save_folder ./output img_path ppstructure/docs/table/1.png img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line)若需对版面区域执行 OCR 但跳过表格识别可令tableFalse, ocrTrue此时非表格区域的文本会被识别PDF 输入则返回逐页结果列表import os import cv2 from paddleocr import PPStructure,save_structure_res ocr_engine PPStructure(tableFalse, ocrTrue, show_logTrue) save_folder ./output img_path ppstructure/docs/recovery/UnrealText.pdf result ocr_engine(img_path) for index, res in enumerate(result): save_structure_res(res, save_folder, os.path.basename(img_path).split(.)[0], index) for res in result: for line in res: line.pop(img) print(line)PDF 输入时也可自行控制渲染分辨率——例如用fitzPyMuPDF以 2 倍矩阵渲染页面若页宽或页高超过 2000 像素则降为 1 倍避免超大页面内存压力import os import cv2 import numpy as np from paddleocr import PPStructure,save_structure_res from paddle.utils import try_import from PIL import Image ocr_engine PPStructure(tableFalse, ocrTrue, show_logTrue) save_folder ./output img_path ppstructure/docs/recovery/UnrealText.pdf fitz try_import(fitz) imgs [] with fitz.open(img_path) as pdf: for pg in range(0, pdf.page_count): page pdf[pg] mat fitz.Matrix(2, 2) pm page.get_pixmap(matrixmat, alphaFalse) # if width or height 2000 pixels, dont enlarge the image if pm.width 2000 or pm.height 2000: pm page.get_pixmap(matrixfitz.Matrix(1, 1), alphaFalse) img Image.frombytes(RGB, [pm.width, pm.height], pm.samples) img cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) imgs.append(img) for index, img in enumerate(imgs): result ocr_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split(.)[0], index) for line in result: line.pop(img) print(line)3.4 仅表格识别import os import cv2 from paddleocr import PPStructure,save_structure_res table_engine PPStructure(layoutFalse, show_logTrue) save_folder ./output img_path ppstructure/docs/table/table.jpg img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line)3.5 关键信息抽取关键信息抽取暂不支持通过 whl 包使用请参考 推理文档对应中文版 python_infer.md以及上文提到的 KIE 教程。3.6 版面复原输出 docximport os import cv2 from paddleocr import PPStructure,save_structure_res from paddleocr.ppstructure.recovery.recovery_to_doc import sorted_layout_boxes, convert_info_docx # Chinese image table_engine PPStructure(recoveryTrue) # English image # table_engine PPStructure(recoveryTrue, langen) save_folder ./output img_path ppstructure/docs/table/1.png img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line) h, w, _ img.shape res sorted_layout_boxes(result, w) convert_info_docx(img, res, save_folder, os.path.basename(img_path).split(.)[0])sorted_layout_boxes按图像宽度对版面区域做阅读顺序排序源码位于 ppstructure/recovery/recovery_to_doc.py随后convert_info_docx依据区域坐标将文本、表格、图片还原为带布局的 Word 文档。默认面向中文langch英文图片请取消注释langen一行。3.7 版面复原输出 Markdownimport os import cv2 from paddleocr import PPStructure,save_structure_res from paddleocr.ppstructure.recovery.recovery_to_doc import sorted_layout_boxes from paddleocr.ppstructure.recovery.recovery_to_markdown import convert_info_markdown # Chinese image table_engine PPStructure(recoveryTrue) # English image # table_engine PPStructure(recoveryTrue, langen) save_folder ./output img_path ppstructure/docs/table/1.png img cv2.imread(img_path) result table_engine(img) save_structure_res(result, save_folder, os.path.basename(img_path).split(.)[0]) for line in result: line.pop(img) print(line) h, w, _ img.shape res sorted_layout_boxes(result, w) convert_info_markdown(res, save_folder, os.path.basename(img_path).split(.)[0])与 3.6 的区别仅在于最后调用convert_info_markdown源码位于 ppstructure/recovery/recovery_to_markdown.py输出为 Markdown 文件而非 docx。3.8 源码视角一次调用内部发生了什么从 ppstructure/predict_system.py 可以还原PPStructure一次前向的完整链路若启用image_orientation先用 PaddleClas 的text_image_orientation模型预测旋转角90°/180°/270°并按 [90/180/270 → ROTATE_90_COUNTERCLOCKWISE/ROTATE_180/ROTATE_90_CLOCKWISE] 映射旋转图像structure模式下先执行版面分析ppstructure/layout/predict_layout.py其预处理为Resize [800, 608] ImageNet 归一化后处理为PicoDetPostProcess受layout_score_threshold与layout_nms_threshold控制对整图先做一次全图文本检测与识别_predict_text再按版面 bbox 过滤出属于各区域的文本_filter_text_res做 bbox 交集判断从而提升 OCR 准确率对table区域调用TableSystem对equation区域且启用formula调用基于 LaTeXOCR 的TextRecognizer输出 LaTeX每个版面区域最终封装为包含type/bbox/img/res/score的 dict 列表返回。4. 输出结果说明4.1 返回结果格式PPStructure返回一个 dict 列表示例版面分析 表格识别[ { type: Text, bbox: [34, 432, 345, 462], res: ([[36.0, 437.0, 341.0, 437.0, 341.0, 446.0, 36.0, 447.0], [41.0, 454.0, 125.0, 453.0, 125.0, 459.0, 41.0, 460.0]], [(Tigure-6. The performance of CNN and IPT models using difforen, 0.90060663), (Tent , 0.465441)]) } ]各字段含义如下字段描述type图像区域类型如 Text、Table、Figure、Equation 等。bbox区域在原始图像中的坐标依次为 [左上角 x, 左上角 y, 右下角 x, 右下角 y]。res该区域的 OCR 或表格识别结果。table包含以下字段的 dicthtml表格的 HTML 字符串。在代码模式下调用时设置return_ocr_result_in_tableTrue可额外获得表格区域内每个文本的检测与识别结果对应字段boxes文本检测框。rec_res文本识别结果。OCR由每个独立文本的检测框与识别结果组成的元组。从 ppstructure/predict_system.py 可见每个区域的type取自版面模型 label 的小写形式bbox为整数坐标score为版面区域置信度res的具体结构取决于区域类型表格为含html的 dict公式为含latex的 dict其余为 OCR 文本列表。4.2 保存目录结构识别完成后output字段指定目录下会为每张图片生成同名子目录每个表格导出为 xlsx图片区域裁剪保存为 jpg文件名即为该区域在原图中的坐标/output/table/1/ └─ res.txt └─ [454, 360, 824, 658].xlsx table recognition result └─ [16, 2, 828, 305].jpg picture in Image └─ [17, 361, 404, 711].xlsx table recognition result该目录结构由save_structure_resppstructure/predict_system.py生成res_{img_idx}.txt记录全部区域的 JSON 序列化结果table类型区域通过to_excel将 HTML 表格转存为 xlsxfigure类型区域通过cv2.imwrite裁剪保存。5. 参数说明PPStructure与命令行paddleocr的主要参数如下表所示。多数参数与 PaddleOCR whl 包保持一致完整说明可参考 whl 包文档对应中文版 whl.md。字段描述默认值output结果保存路径./output/tabletable_max_len表格结构模型中图像缩放后的长边488table_model_dir表格结构模型推理模型路径Nonetable_char_dict_path表格结构模型字典路径../ppocr/utils/dict/table_structure_dict.txtmerge_no_span_structure表格识别模型中是否合并 与 Falseformula_model_dir公式识别模型推理模型路径Noneformula_char_dict_path公式识别模型字典路径../ppocr/utils/dict/latex_ocr_tokenizer.jsonlayout_model_dir版面分析模型推理模型路径Nonelayout_dict_path版面分析模型字典路径../ppocr/utils/dict/layout_publaynet_dict.txtlayout_score_threshold版面分析模型的框置信度阈值0.5layout_nms_threshold版面分析模型的 NMS 阈值0.5kie_algorithmKIE 模型算法LayoutXLMser_model_dirSER 模型推理模型路径Noneser_dict_pathSER 模型字典路径../train_data/XFUND/class_list_xfun.txtmodestructure 或 kiestructureimage_orientation前向时是否执行图像方向分类Falselayout前向时是否执行版面分析Truetable前向时表格区域是否使用表格识别Trueformula前向时是否执行公式识别Falseocr版面分析中非表格区域是否执行 OCRlayout 为 False 时自动置为 FalseTruerecovery前向时是否执行版面复原Falserecovery_to_markdown是否将版面复原结果转换为 Markdown 文件Falsesave_pdf版面复原时是否将 docx 转换为 pdfFalsestructure_version结构版本可选 PP-structure 与 PP-structurev2PP-structure对照当前仓库源码 ppstructure/utility.py 中的参数定义以下几点值得注意源码中--output的默认值为./output最终保存目录为os.path.join(args.output, mode)mode 为structure或kie因此实际输出目录形如./output/structure/图片名/--table_char_dict_path在当前源码中的默认值是../ppocr/utils/dict/table_structure_dict_ch.txt对应中文表格字典--layout_dict_path为../ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt与表格所列历史默认值略有差异请以所用版本实际为准--merge_no_span_structure在当前源码中默认值为True即默认合并td与/td标签简化后续 HTML 解析--layout_score_threshold与--layout_nms_threshold会直接传入PicoDetPostProcess见 ppstructure/layout/predict_layout.py分别控制版面框的置信度过滤与非极大值抑制强度--layoutfalse时若--ocrtrue源码会强制将ocr置为False并打印警告ppstructure/predict_system.py这与参数表中layout 为 False 时自动置为 False的说明一致。6. 总结通过本文读者可以掌握使用 PaddleOCR whl 包调用 PP-Structure 的完整方法从 PaddlePaddle 与paddleocr3.0的环境安装到命令行paddleocr --typestructure与 PythonPPStructure两类调用方式覆盖图像方向矫正、版面分析、表格识别、公式识别、关键信息抽取与版面复原docx/Markdown等场景并理解其返回的 dict 结构、输出目录组织与关键参数含义。更深入的模型训练、推理与部署教程可继续阅读仓库内 overview.en.md、models_list.en.md中文版见 overview.md、models_list.md等文档或直接阅读 ppstructure/ 目录下的源码实现。【免费下载链接】PaddleOCR飞桨多语言OCR工具包实用超轻量OCR系统支持80种语言识别提供数据标注与合成工具支持服务器、移动端、嵌入式及IoT设备端的训练与部署 Awesome multilingual OCR toolkits based on PaddlePaddle (practical ultra lightweight OCR system, support 80 languages recognition, provide data annotation and synthesis tools, support training and deployment among server, mobile, embedded and IoT devices)项目地址: https://gitcode.com/paddlepaddle/PaddleOCR创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考