本页目录
30 秒速览:先安装推理引擎和 PaddleOCR(安装教程),然后调用 PaddleOCR().predict("image.png")。每个结果都是类似字典的对象:读取 rec_texts、rec_scores 和 rec_boxes,或者调用 save_to_json() 和 save_to_img()。需要 Markdown、表格和公式时,请改用 PPStructureV3。
快速开始:第一次 OCR#
from paddleocr import PaddleOCR
ocr = PaddleOCR(
use_doc_orientation_classify=False, # 跳过整页方向分类模型(扫描件干净时)
use_doc_unwarping=False, # 跳过文档弯曲矫正模型(页面平整时)
use_textline_orientation=False, # 跳过文本行倒置检测
)
for res in ocr.predict("receipt.jpg"):
res.print() # 格式化打印所有字段
res.save_to_img("output") # 生成画好检测框的 output/receipt_ocr_res_img.jpg
res.save_to_json("output") # 生成 output/receipt_res.json第一次调用会把 PP-OCRv6 medium(检测 + 识别)下载到 ~/.paddlex/official_models,之后全部离线运行。在国内如果模型下载慢,先设置 PADDLE_PDX_MODEL_SOURCE=bos(见 安装教程)。在终端里做同样的事:
paddleocr ocr -i receipt.jpg --use_doc_orientation_classify False --use_doc_unwarping False --use_textline_orientation False --save_path ./output没有 GPU?没关系——在我们的 4 核测试机上,使用 PaddlePaddle 3.2.0 识别一张小票约 3.2 秒(ONNX Runtime 为 2.0 秒)。所有模型的数据见 基准测试(英文)。
三条产线一览#
| 产线 | Python 类 | 命令行 | 需要的 extra | 输出 |
|---|---|---|---|---|
| 文字识别(PP-OCRv6) | PaddleOCR | paddleocr ocr | 无 | 文本行、检测框、置信度 |
| PP-StructureV3 | PPStructureV3 | paddleocr pp_structurev3 | [doc-parser] | 包含版面、表格、公式的 Markdown/JSON |
| PaddleOCR-VL | PaddleOCRVL | paddleocr doc_parser | [doc-parser] | 由视觉语言模型生成的 Markdown/JSON |
此外还有更多产线(印章识别、表格识别、公式识别、PP-ChatOCRv4 关键信息抽取、PP-DocTranslation 文档翻译),以及 TextDetection、TextRecognition 等单模型类;命令行一节 列出了全部。1
PaddleOCR() 参数及其实际默认值#
PaddleOCR.__init__ 中所有 OCR 相关参数的默认值都是 None,意思是“使用 PaddleX 产线配置中的值”。所以真正的默认值写在 PaddleX 的 OCR.yaml 里,而不是 PaddleOCR 的函数签名里——其中有三处与官方文档不一致。12
| 参数 | 实际默认值 | 作用 |
|---|---|---|
lang | None → PP-OCRv6 medium | 语言代码,例如 "en"、"japan"、"korean",用于选择识别模型。全部 112 个代码。 |
ocr_version | None | "PP-OCRv6"、"PP-OCRv5"、"PP-OCRv4" 或 "PP-OCRv3"。其他值会抛出 ValueError。 |
text_detection_model_name / text_recognition_model_name | PP-OCRv6_medium_det / _rec | 直接指定模型——这是使用 small 或 tiny 档的唯一方式。会覆盖 lang/ocr_version。 |
text_detection_model_dir / text_recognition_model_dir | None | 从本地文件夹加载模型(离线或微调后的模型)。 |
use_doc_orientation_classify | True | 先把整页按 0/90/180/270° 旋转校正。 |
use_doc_unwarping | True | 先用 UVDoc 把弯曲或拍摄的页面展平。会改变坐标。 |
use_textline_orientation | True | 检测倒置的文本行(0°/180°)。 |
text_det_limit_side_len / text_det_limit_type | 64 / "min" | 检测前的缩放规则。设为 "max" 则改为限制最长边。 |
text_det_thresh | 0.3 | 文本概率图上的像素阈值。 |
text_det_box_thresh | 0.6 | 检测框平均得分高于此值才保留。调低可以捕获较淡的文字。 |
text_det_unclip_ratio | 1.5 文档写的是 2.0 | 检测框外扩的程度。字符被裁掉时调高。 |
text_rec_score_thresh | 0.0 | 丢弃置信度低于此值的识别结果(≥ 此值则保留)。 |
text_recognition_batch_size | 6 文档写的是 1 | 每批识别的文本行数。 |
textline_orientation_batch_size | 6 文档写的是 1 | 每批做方向分类的文本行数。 |
return_word_box | False | 同时返回单词级检测框(text_word、text_word_boxes)。 |
device | None(有 GPU 用 GPU 0,否则用 CPU) | "cpu"、"gpu"、"gpu:1"、"npu:0"… |
engine | None(大多数情况下为 PaddlePaddle) | "paddle"、"paddle_static"、"paddle_dynamic"、"onnxruntime"、"transformers"。 |
enable_mkldnn / cpu_threads | True / 10 | PaddlePaddle 的 CPU 加速(oneDNN)与线程数。 |
enable_hpi、use_tensorrt、precision | None、False、"fp32" | 高性能推理、TensorRT、"fp16"。 |
传入其他任何关键字参数都会抛出 ValueError: Unknown argument: …。有 11 个 2.x 参数名(use_angle_cls、det_db_thresh、rec_model_dir…)仍被 PaddleOCR 接受,但会给出弃用警告;use_gpu、show_log 等则不再接受。我们的 迁移指南 列出了全部参数。1
三个预处理模型要不要开?#
默认情况下,PaddleOCR() 在识别之前会先运行两个页面级模型(方向分类和 UVDoc 弯曲矫正)和一个文本行级模型。它们对拍摄、旋转或弯曲的页面有帮助,但在干净的扫描件和截图上只会白白耗时。如果你的输入是平整、方向正确的(本站所有示例都是),就把它们关掉;否则只打开你需要的那一个:
| 你的输入 | use_doc_orientation_classify | use_doc_unwarping | use_textline_orientation |
|---|---|---|---|
| 扫描件、PDF、截图 | False | False | False |
| 手机拍摄的平整页面 | False | False | True |
| 可能侧转或倒置的页面 | True | False | True |
| 卷曲的书页、皱巴巴的小票 | True | True | True |
每张图片的毫秒数,高性能模式,Intel Xeon Gold 6271C,数据来自 PaddleOCR 官方文档。模型分别为 PP-LCNet_x1_0_textline_ori、PP-LCNet_x1_0_doc_ori 和 UVDoc。越低开销越小。
| 模型 | CPU 毫秒 |
|---|---|
| 文本行方向分类 | 2.98 ms |
| 整页方向分类 | 1.19 ms |
| 文档弯曲矫正(UVDoc) | 869.82 ms |
docs/version3.x/pipeline_usage/OCR.en.md)及模块文档。厂商公布数据。两个方向分类模型几乎不花时间;UVDoc 弯曲矫正才是大头——按官方数据,在服务器 CPU 上每张图约 0.9 秒——而且它还会改变坐标(见下一节)。如果只关一个,就关 use_doc_unwarping。
注意:弯曲矫正会改变坐标#
当 use_doc_unwarping=True(默认值)时,检测是在展平后的图片上进行的,所有检测框的坐标也都基于这张图。我们用同一张小票分别跑了两次:开启矫正时,第一行返回 [[119, 11], [507, 8], [507, 46], [120, 49]];关闭时返回 [[128, 55], [489, 55], [489, 82], [128, 82]]。如果把第一组坐标画在原图上,框的位置就会偏掉。6
要么关闭弯曲矫正,要么画在结果自带的预处理图上:res.img["preprocessed_img"](文档预处理运行时才有——我们核实过:此时 res.img 包含 ocr_res_img 和 preprocessed_img 两个键)。46
predict():输入与单次调用覆盖参数#
predict(input) 返回结果列表;predict_iter(input) 则逐个产出结果,处理长 PDF 和大文件夹时内存占用保持平稳。input 可以是:3
- 图片(
.jpg、.png等)或 PDF 的路径或 URL——PDF 的每一页对应一个结果,并设置page_index; - 一个图片目录(不支持目录里的 PDF);
- 一个 numpy 数组(BGR 格式,与
cv2.imread的返回值相同); - 由以上任意类型组成的列表。
检测和识别阈值、三个预处理开关以及 return_word_box 都可以在单次调用时覆盖——重试难识别的图片时不必重建产线:
res = ocr.predict("faded_label.jpg", text_det_box_thresh=0.4, text_det_unclip_ratio=2.0)[0]构造时关闭的模型,不能在 predict() 时再打开。用 PaddleOCR(use_textline_orientation=False) 创建后,调用 predict(..., use_textline_orientation=True) 会记录一条错误日志,并返回 {"error": ...} 而不是识别结果。2
结果对象#
每个结果都是 dict 的子类(OCRResult),所以 res["rec_texts"] 可以直接用,另外还带有一些辅助方法。下面是 PaddleOCR 3.7.0 为我们的测试小票写出的真实 JSON(数组已截短):
{
"input_path": "samples/receipt.png",
"page_index": null,
"model_settings": {"use_doc_preprocessor": true, "use_textline_orientation": true},
"doc_preprocessor_res": {"model_settings": {"use_doc_orientation_classify": true, "use_doc_unwarping": true}, "angle": 0},
"dt_polys": [[[119, 11], [507, 8], [507, 46], [120, 49]], "…"],
"text_det_params": {"limit_side_len": 64, "limit_type": "min", "thresh": 0.3,
"max_side_limit": 4000, "box_thresh": 0.6, "unclip_ratio": 1.5},
"text_type": "general",
"textline_orientation_angles": [0, 0, "…"],
"text_rec_score_thresh": 0.0,
"return_word_box": false,
"rec_texts": ["HARBOR STREET COFFEE", "214 Harbor Street, Portland ME", "…"],
"rec_scores": [0.9999498128890991, 0.9985201954841614, "…"],
"rec_polys": [[[119, 11], [507, 8], [507, 46], [120, 49]], "…"],
"rec_boxes": [[119, 8, 507, 49], [120, 57, 506, 87], "…"]
}| 字段 | 含义 |
|---|---|
rec_texts | 识别出的文字,每行一个字符串(只包含得分 ≥ text_rec_score_thresh 的行)。 |
rec_scores | 每行的置信度,0–1。 |
rec_polys | 每个保留行的四点多边形(可处理旋转文字)。 |
rec_boxes | 每个保留行的水平外接框 [x_min, y_min, x_max, y_max];在 Python 中是形状为 (n, 4) 的 numpy 数组。 |
dt_polys | 得分过滤之前的全部检测多边形。 |
textline_orientation_angles | 每行为 0 或 1(180°);分类器关闭时为 −1。 |
doc_preprocessor_res | 应用的整页旋转(angle 为 0–3,对应 0/90/180/270°;关闭时为 −1)。 |
page_index | PDF 输入时为页码,否则为 null。 |
text_word、text_word_boxes | 仅在 return_word_box=True 时出现。 |
方法:print(json_format=False, indent=4, ensure_ascii=False)、save_to_json(path)(写出 {name}_res.json)、save_to_img(path)(写出 {name}_ocr_res_img.{ext})、save_all(path),以及属性 json、str 和 img。注意:官方文档把 print 的参数写成 format_json,代码里实际是 json_format。4
常用代码片段#
res = ocr.predict("invoice.png")[0]
for text, score, box in zip(res["rec_texts"], res["rec_scores"], res["rec_boxes"]):
if score >= 0.80:
x1, y1, x2, y2 = box.tolist()
print(f"{score:.2f} {text} @ ({x1},{y1})-({x2},{y2})")res = ocr.predict("page.png")[0]
lines = sorted(zip(res["rec_boxes"].tolist(), res["rec_texts"]), key=lambda t: (t[0][1], t[0][0]))
print("\n".join(text for _, text in lines))from paddleocr import PaddleOCR
ocr = PaddleOCR(use_doc_orientation_classify=False, use_doc_unwarping=False)
with open("report.txt", "w", encoding="utf-8") as f:
for res in ocr.predict_iter("report.pdf"): # 每页一个结果
f.write(f"--- page {res['page_index'] + 1} ---\n")
f.write("\n".join(res["rec_texts"]) + "\n")import cv2
img = cv2.imread("photo.jpg") # BGR 格式的 numpy 数组
res = ocr.predict(img)[0]“从上到下”排序只是针对单栏文本的简单启发式方法。多栏页面、表格或需要真正阅读顺序时,请使用 PP-StructureV3,它会根据版面分析计算阅读顺序。
批量、文件夹与速度#
- 复用同一个实例。创建
PaddleOCR()时会加载模型;只创建一次,然后多次调用predict。 - 直接传入文件夹或列表,不要在 Python 里自己循环;输入量大时使用
predict_iter。 - 按硬件选档位:在我们的 CPU 上,small 比 medium 快 3.3–3.7 倍,124 个文本项中只多错 2 个。模型指南。
- CPU 上试试 ONNX Runtime(
engine="onnxruntime"):在我们的测试中,PP-OCRv6 快了 1.4–1.5 倍。 - 关掉用不到的预处理(见上文)。
ocr = PaddleOCR(
text_detection_model_name="PP-OCRv6_small_det",
text_recognition_model_name="PP-OCRv6_small_rec",
use_doc_orientation_classify=False, use_doc_unwarping=False, use_textline_orientation=False,
engine="onnxruntime",
)
for res in ocr.predict_iter("scans/"):
res.save_to_json("output")单模型类与自定义模型#
3.x 把每个模型都暴露为独立的类——用来替代 2.x 的 ocr(img, det=False) 和 ocr(img, rec=False):
from paddleocr import TextDetection, TextRecognition
det = TextDetection(model_name="PP-OCRv6_medium_det")
for res in det.predict("receipt.jpg"):
print(res["dt_polys"], res["dt_scores"]) # 检测框及其得分
rec = TextRecognition(model_name="PP-OCRv6_medium_rec")
for res in rec.predict("cropped_line.png"):
print(res["rec_text"], res["rec_score"])微调或导出的模型通过 *_model_dir 参数加载,例如 PaddleOCR(text_recognition_model_dir="./my_rec_model")。
命令行参考#
3.x 的命令行使用子命令。2.x 的写法(paddleocr --image_dir x.jpg --use_angle_cls true)已经不能用了。1
| 类别 | 子命令 |
|---|---|
| 产线 | ocr、pp_structurev3、doc_parser(PaddleOCR-VL)、doc_preprocessor、table_recognition_v2、seal_recognition、formula_recognition_pipeline、doc_understanding、pp_chatocrv4_doc、pp_doctranslation |
| 单模型 | text_detection、text_recognition、textline_orientation_classification、doc_img_orientation_classification、text_image_unwarping、layout_detection、table_structure_recognition、table_cells_detection、table_classification、formula_recognition、seal_text_detection、chart_parsing、doc_vlm |
| 工具命令 | install_hpi_deps {cpu,gpu,npu}、install_genai_server_deps {vllm,sglang,fastdeploy}、genai_server、doc2md、api |
产线的命令行参数与 Python 参数同名,布尔值写作 True/False:
# 用 GPU 0 和 small 档识别整个扫描件文件夹,结果写到 ./out
paddleocr ocr -i ./scans --device gpu:0 \
--text_detection_model_name PP-OCRv6_small_det \
--text_recognition_model_name PP-OCRv6_small_rec \
--use_doc_orientation_classify False --use_doc_unwarping False \
--save_path ./out
# 韩文,CPU,ONNX Runtime 引擎
paddleocr ocr -i sign.jpg --lang korean --engine onnxruntime
# 用 PP-StructureV3 把 PDF 转成 Markdown
paddleocr pp_structurev3 -i report.pdf --save_path ./out
# 查看任意子命令的帮助
paddleocr ocr --help日志#
PaddleOCR 通过同一个 logger paddleocr.logger 输出日志,默认级别为 ERROR,所以除非出错,平时很安静。要调高日志级别或写入文件:5
import logging
from paddleocr import logger
logger.setLevel(logging.INFO)
logger.addHandler(logging.FileHandler("paddleocr.log"))如果想让 PaddleOCR 完全不配置自己的 logger,文档说设置 DISABLE_AUTO_LOGGING_CONFIG=1——但代码实际读取的是 PADDLEOCR_DISABLE_AUTO_LOGGING_CONFIG=1。请使用带前缀的名称。5 PaddleX 那些绿色的“Creating model”信息来自 PaddleX 自己的 logger,不受此影响。
接下来读什么#
PP-StructureV3#
把 PDF 和扫描件转成带表格、公式的 Markdown。
服务化部署与 API EN#
通过 HTTP 提供任意产线服务,或调用官方托管 API。
常见错误排查#
粘贴报错信息,获取经过验证的修复方法。
代码生成器 EN#
只用你需要的参数生成脚本。
常见问题#
ocr() 和 predict() 有什么区别?
ocr() 是 2.x 的方法名。在 3.x 中它仍然存在,作为已弃用的别名,返回与 predict() 相同的结果对象,但不再接受 cls=、det= 或 rec=:在我们的测试中,ocr(img, cls=True) 报错 TypeError: PaddleOCR.predict() got an unexpected keyword argument 'cls'。请使用 predict()(或 predict_iter()),并从结果对象中读取字段。
怎样只取出 PaddleOCR 结果中的文字?
"\n".join(res["rec_texts"])。每一项是一行检测到的文字,按检测顺序排列。
PaddleOCR 能直接识别 PDF 吗?
能。把 PDF 路径传给 predict() 或 predict_iter(),每一页对应一个结果,并设置 page_index。如果需要带版面和表格的 Markdown 输出,请使用 PP-StructureV3。
为什么把检测框画到图片上时位置不对?
最可能的原因是 use_doc_unwarping 处于开启状态(默认值),坐标对应的是展平后的图片。把它关掉,或者画在 res.img["preprocessed_img"] 上。
怎样使用 PP-OCRv6 的 small 或 tiny 模型?
同时传入两个模型名:text_detection_model_name="PP-OCRv6_small_det" 和 text_recognition_model_name="PP-OCRv6_small_rec"。lang 和 ocr_version 只会选中 medium 档。
有覆盖所有参数的 PaddleOCR API 文档吗?
本页讲的是通用 OCR 产线。paddleocr.ai 上的官方中文文档覆盖了所有产线和模块;其中默认值与实际发布配置不一致的地方,我们已在上文注明。
参考来源
- PaddleOCR 3.7.0 源码:
paddleocr/_pipelines/ocr.py(构造函数、旧参数名映射、ocr()弃用)、paddleocr/_common_args.py(engine、device、未知参数报错)、paddleocr/_cli.py(子命令)——github.com/PaddlePaddle/PaddleOCR。 - 实际默认值:PaddleX 3.7.2 的
paddlex/configs/pipelines/OCR.yaml与paddlex/inference/pipelines/ocr/pipeline.py,即pip install paddleocr==3.7.0所安装的版本。 - 官方通用 OCR 产线文档:docs/version3.x/pipeline_usage/OCR.en.md(参数说明、支持的输入、输出文件)。中文版:OCR.md。
- 结果对象方法:PaddleX
paddlex/inference/common/result/mixin.py与paddlex/inference/pipelines/ocr/result.py。 - 日志:logging.en.md 与
paddleocr/_env.py对照。 - 我们的测试(2026-10-27,PaddleOCR 3.7.0,Linux,4 vCPU):真实的
save_to_json输出、use_doc_unwarping=True时的坐标偏移、预处理开销。脚本见我们的 基准测试(英文)。 - 预处理模型耗时:官方 OCR 产线文档中的表格(Intel Xeon Gold 6271C CPU / NVIDIA T4)。