comments: true
Text Detection Module Usage Guide
1. Overview
The text detection module is a critical component of OCR (Optical Character Recognition) systems, responsible for locating and marking text-containing regions in images. The performance of this module directly impacts the accuracy and efficiency of the entire OCR system. The text detection module typically outputs bounding boxes for text regions, which are then passed to the text recognition module for further processing.
2. Supported Models List
The inference time only includes the model inference time and does not include the time for pre- or post-processing. The "Standard Mode" values correspond to the local
paddle_staticinference engine.
| Model | Model Download Link | Detection Hmean (%) | GPU Inference Time (ms) [Standard Mode / High-Performance Mode] |
CPU Inference Time (ms) [Standard Mode / High-Performance Mode] |
Model Size (MB) | Description |
|---|---|---|---|---|---|---|
| PP-OCRv6_medium_det | Inference Model/Training Model | 86.2* | - / - | - / - | 59.4 | PP-OCRv6 medium-scale text detection model based on PPLCNetV4 + RepLKFPN, highest accuracy, suitable for server deployment |
| PP-OCRv6_small_det | Inference Model/Training Model | 84.1* | - / - | - / - | 9.6 | PP-OCRv6 small text detection model, balancing accuracy and efficiency, suitable for mobile deployment |
| PP-OCRv6_tiny_det | Inference Model/Training Model | 80.6* | - / - | - / - | 1.9 | PP-OCRv6 ultra-lightweight text detection model (0.43M params), suitable for edge/IoT scenarios |
| PP-OCRv5_server_det | Inference Model/Training Model | 83.8 | 89.55 / 70.19 | 383.15 / 383.15 | 84.3 | PP-OCRv5 server-side text detection model with higher accuracy, suitable for deployment on high-performance servers |
| PP-OCRv5_mobile_det | Inference Model/Training Model | 79.0 | 10.67 / 6.36 | 57.77 / 28.15 | 4.7 | PP-OCRv5 mobile-side text detection model with higher efficiency, suitable for deployment on edge devices |
| PP-OCRv4_server_det | Inference Model/Training Model | 69.2 | 127.82 / 98.87 | 585.95 / 489.77 | 109 | PP-OCRv4 server-side text detection model with higher accuracy, suitable for deployment on high-performance servers |
| PP-OCRv4_mobile_det | Inference Model/Training Model | 63.8 | 9.87 / 4.17 | 56.60 / 20.79 | 4.7 | PP-OCRv4 mobile-side text detection model with higher efficiency, suitable for deployment on edge devices |
*Note: PP-OCRv6 metrics are evaluated on an internal multi-scenario evaluation set, while PP-OCRv5/v4 metrics are based on a general evaluation set. As the evaluation sets differ, the metrics are not directly comparable.
Testing Environment:
- Performance Testing Environment
- Test Dataset: PaddleOCR3.0 newly constructed multilingual dataset (including Chinese, Traditional Chinese, English, Japanese), covering street scenes, web images, documents, handwriting, blur, rotation, distortion, etc., totaling 2677 images.
- Hardware Configuration:
- GPU: NVIDIA Tesla T4
- CPU: Intel Xeon Gold 6271C @ 2.60GHz
- Software Environment:
- Ubuntu 20.04 / CUDA 11.8 / cuDNN 8.9 / TensorRT 8.6.1.6
- paddlepaddle-gpu 3.0.0 / paddleocr 3.0.3
- Inference Mode Description
| Mode | GPU Configuration | CPU Configuration | Acceleration Techniques |
|---|---|---|---|
| Standard Mode | FP32 precision / No TRT acceleration | FP32 precision / 8 threads | PaddleInference |
| High-Performance Mode | Optimal combination of precision types and acceleration strategies | FP32 precision / 8 threads | Optimal backend selection (Paddle/OpenVINO/TRT, etc.) |
3. Quick Start
❗ Before starting, please install the PaddleOCR wheel package. Refer to the Installation Guide for details.
Use the following command for a quick experience:
paddleocr text_detection -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png
The example above uses the paddle_static inference engine by default. To run it, first install PaddlePaddle by following PaddlePaddle Framework Installation.
If you choose transformers as the inference engine, make sure the Transformers environment is configured, and then run the following command:
# Use the transformers engine for inference
paddleocr text_detection -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png \
--engine transformers
If you choose onnxruntime as the inference engine, make sure the ONNX Runtime environment is configured, and then run the following command:
# Use the onnxruntime engine for inference
paddleocr text_detection -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/general_ocr_001.png \
--engine onnxruntime
In most scenarios, the default paddle_static inference engine delivers better inference performance and is the recommended first choice.
Note: The official models would be download from HuggingFace by default. If can't access to HuggingFace, please set the environment variable PADDLE_PDX_MODEL_SOURCE="BOS" to change the model source to BOS. In the future, more model sources will be supported.
You can also integrate the model inference into your project. Before running the following code, download the example image locally.
from paddleocr import TextDetection
model = TextDetection()
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
res.save_to_img(save_path="./output/")
res.save_to_json(save_path="./output/res.json")
The example above uses the paddle_static inference engine by default. To run it, first install PaddlePaddle by following PaddlePaddle Framework Installation.
If you choose transformers as the inference engine, make sure the Transformers environment is configured, and then run the following code:
from paddleocr import TextDetection
model = TextDetection(engine="transformers")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
res.save_to_img(save_path="./output/")
res.save_to_json(save_path="./output/res.json")
If you choose onnxruntime as the inference engine, make sure the ONNX Runtime environment is configured, and then run the following code:
from paddleocr import TextDetection
model = TextDetection(engine="onnxruntime")
output = model.predict("general_ocr_001.png", batch_size=1)
for res in output:
res.print()
res.save_to_img(save_path="./output/")
res.save_to_json(save_path="./output/res.json")
In most scenarios, the default paddle_static inference engine delivers better inference performance and is the recommended first choice.
If you want to use the trained model with the paddle_dynamic or transformers engine, refer to the Weight Conversion section in the Inference Engine section below to convert the model from the pdparams format to the safetensors format using PaddleX.
The output will be:
{'res': {'input_path': 'general_ocr_001.png', 'page_index': None, 'dt_polys': array([[[ 75, 549],
...,
[ 77, 586]],
...,
[[ 31, 406],
...,
[ 34, 455]]], dtype=int16), 'dt_scores': [0.873949039891189, 0.8948166013613552, 0.8842595305917041, 0.876953790920377]}}
Output parameter meanings:
input_path:Path of the input image.page_index:If the input is a PDF, this indicates the current page number; otherwise, it isNonedt_polys:Predicted text detection boxes, where each box contains four vertices (x, y coordinates).dt_scores:Confidence scores of the predicted text detection boxes.
Visualization example:
Method and parameter descriptions:
- Instantiate the text detection model with
TextDetection:Parameter Description Type Default model_nameMeaning:Model name.
Description: If set toNone,PP-OCRv6_medium_detwill be used.str|NoneNonemodel_dirMeaning:Model storage path. str|NoneNonedeviceMeaning:Device for inference.
Description: For example:"cpu","gpu","npu","gpu:0","gpu:0,1".
If multiple devices are specified, parallel inference will be performed.
By default, GPU 0 is used if available; otherwise, CPU is used.str|NoneNoneengineMeaning: Inference engine.
Description: SupportsNone(the default),paddle,paddle_static,paddle_dynamic,transformers, andonnxruntime. When left asNone, local inference uses thepaddle_staticengine by default. For detailed descriptions, supported values, compatibility rules, and examples, see Inference Engine and Configuration.str|NoneNoneengine_configMeaning: Inference-engine configuration.
Description: Recommended together withengine. For supported fields, compatibility rules, and examples, see Inference Engine and Configuration.dict|NoneNoneenable_hpiMeaning:Whether to enable high-performance inference. boolFalseuse_tensorrtMeaning:Whether to use the Paddle Inference TensorRT subgraph engine.
Description: If the model does not support acceleration through TensorRT, setting this flag will not enable acceleration.
For Paddle with CUDA version 11.8, the compatible TensorRT version is 8.x (x>=6), and it is recommended to install TensorRT 8.6.1.6.
boolFalseprecisionMeaning:Computation precision when using the Paddle Inference TensorRT subgraph engine.
Description: Options:"fp32","fp16".str"fp32"enable_mkldnnMeaning:Whether to enable MKL-DNN acceleration for inference.
Description: If MKL-DNN is unavailable or the model does not support it, acceleration will not be used even if this flag is set.boolTruemkldnn_cache_capacityMeaning:MKL-DNN cache capacity. int10cpu_threadsMeaning:Number of threads to use for inference on CPUs. int10limit_side_lenMeaning:Limit on the side length of the input image for detection. Description: intspecifies the value. If set toNone, the model's default configuration will be used.int|NoneNonelimit_typeMeaning:Type of image side length limitation.
Description:"min"ensures the shortest side of the image is no less thandet_limit_side_len;"max"ensures the longest side is no greater thanlimit_side_len. If set toNone, the model's default configuration will be used.str|NoneNonemax_side_limitMeaning:Limit on the max length of the input image for detection.
Description:intlimits the longest side of the image for input detection model. If set toNone, the model's default configuration will be used.int|NoneNonethreshMeaning:Pixel score threshold. Pixels in the output probability map with scores greater than this threshold are considered text pixels.
Description: If set toNone, the model's default configuration will be used.float|NoneNonebox_threshMeaning:If the average score of all pixels inside the bounding box is greater than this threshold, the result is considered a text region.
Description: If set toNone, the model's default configuration will be used.float|NoneNoneunclip_ratioMeaning:Expansion ratio for the Vatti clipping algorithm, used to expand the text region. Description: If set to None, the model's default configuration will be used.float|NoneNoneinput_shapeMeaning:Input image size for the model in the format (C, H, W).tuple|NoneNoneThe
predict()method parameters:Parameter Description Type Default inputMeaning:Input data to be predicted. Required.
Description: Supports multiple input types:- Python variable: e.g.,
numpy.ndarrayrepresenting image data - str: Local image file or PDF file path:
/root/data/img.jpg; URL: Image or PDF file network URL: Example; Directory: Should contain images for prediction, e.g.,/root/data/(currently, PDF files in directories are not supported, PDF files need to be specified by file path) - list: List elements should be of the above types, e.g.,
[numpy.ndarray, numpy.ndarray],["/root/data/img1.jpg", "/root/data/img2.jpg"],["/root/data1", "/root/data2"]
Python Var|str|listbatch_sizeMeaning:Batch size
Description:Positive integer.int1 limit_side_lenMeaning:Same meaning as the instantiation parameters.
Description: If set toNone, the instantiation value is used; otherwise, this parameter takes precedence.int|NoneNonelimit_typeMeaning:Same meaning as the instantiation parameters.
Description: If set toNone, the instantiation value is used; otherwise, this parameter takes precedence.str|NoneNonethreshMeaning:Same meaning as the instantiation parameters.
Description: If set toNone, the instantiation value is used; otherwise, this parameter takes precedence.float|NoneNonebox_threshMeaning:Same meaning as the instantiation parameters.
Description: If set toNone, the instantiation value is used; otherwise, this parameter takes precedence.float|NoneNoneunclip_ratioMeaning:Same meaning as the instantiation parameters.
Description: If set toNone, the instantiation value is used; otherwise, this parameter takes precedence.float|NoneNone- Python variable: e.g.,
Result processing methods:
Method Description Parameters Type Description Default print()Print results to terminal format_jsonboolFormat output as JSON TrueindentintJSON indentation level 4 ensure_asciiboolEscape non-ASCII characters Falsesave_to_json()Save results as JSON file save_pathstrOutput file path Required indentintJSON indentation level 4 ensure_asciiboolEscape non-ASCII characters Falsesave_to_img()Save results as image save_pathstrOutput file path Required Additional attributes:
Attribute Description jsonGet prediction results in JSON format imgGet visualization image as a dictionary
4. Custom Development
If the above models do not meet your requirements, follow these steps for custom development (using
PP-OCRv5_server_detas an example). First, prepare a text detection dataset (refer to the Demo Dataset format). After preparation, proceed with model training and export. The exported model can be integrated into the API. Ensure PaddleOCR dependencies are installed as per the Installation Guide.4.1 Dataset and Pretrained Model Preparation
4.1.1 Prepare Dataset
# Download example dataset wget https://paddle-model-ecology.bj.bcebos.com/paddlex/data/ocr_det_dataset_examples.tar tar -xf ocr_det_dataset_examples.tar4.1.2 Download Pretrained Model
# Download PP-OCRv5_server_det pretrained model wget https://paddle-model-ecology.bj.bcebos.com/paddlex/official_pretrained_model/PP-OCRv5_server_det_pretrained.pdparams4.2 Model Training
PaddleOCR modularizes the code. To train the
PP-OCRv5_server_detmodel, use its configuration file.Training command:
# Single-GPU training (default) python3 tools/train.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml \ -o Global.pretrained_model=./PP-OCRv5_server_det_pretrained.pdparams \ Train.dataset.data_dir=./ocr_det_dataset_examples \ Train.dataset.label_file_list='[./ocr_det_dataset_examples/train.txt]' \ Eval.dataset.data_dir=./ocr_det_dataset_examples \ Eval.dataset.label_file_list='[./ocr_det_dataset_examples/val.txt]' # Multi-GPU training (specify GPUs with --gpus) python3 -m paddle.distributed.launch --gpus '0,1,2,3' tools/train.py \ -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml \ -o Global.pretrained_model=./PP-OCRv5_server_det_pretrained.pdparams \ Train.dataset.data_dir=./ocr_det_dataset_examples \ Train.dataset.label_file_list='[./ocr_det_dataset_examples/train.txt]' \ Eval.dataset.data_dir=./ocr_det_dataset_examples \ Eval.dataset.label_file_list='[./ocr_det_dataset_examples/val.txt]'4.3 Model Evaluation
You can evaluate trained weights (e.g.,
output/PP-OCRv5_server_det/best_accuracy.pdparams) using the following command:# Note: Set pretrained_model to local path. For custom-trained models, modify the path and filename as {path/to/weights}/{model_name}. # Demo dataset evaluation python3 tools/eval.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml \ -o Global.pretrained_model=output/PP-OCRv5_server_det/best_accuracy.pdparams \ Eval.dataset.data_dir=./ocr_det_dataset_examples \ Eval.dataset.label_file_list='[./ocr_det_dataset_examples/val.txt]'4.4 Model Export
python3 tools/export_model.py -c configs/det/PP-OCRv5/PP-OCRv5_server_det.yml -o \ Global.pretrained_model=output/PP-OCRv5_server_det/best_accuracy.pdparams \ Global.save_inference_dir="./PP-OCRv5_server_det_infer/"After export, the static graph model will be saved in
./PP-OCRv5_server_det_infer/with the following files:./PP-OCRv5_server_det_infer/ ├── inference.json ├── inference.pdiparams ├── inference.ymlThe custom development is now complete. This static graph model can be directly integrated into PaddleOCR's API.
If you want to use the
paddle_dynamicortransformersengine with the trained model, please refer to the Weight Conversion section in Inference Engine later in this document to convert the model from thepdparamsformat to thesafetensorsformat using PaddleX.5. Inference Engine
For detailed descriptions, values, compatibility rules, and examples of the inference engine, please refer to Inference Engine and Configuration Description.
5.1 Speed Data
model engine Preprocessing (ms) Inference (ms) PostProcessing (ms) End-to-End (ms) PP-OCRv5_mobile_det paddle_static 11.43 13.80 2.15 27.58 paddle_dynamic 11.70 48.36 2.47 62.71 transformers 14.05 18.45 3.98 37.54 onnxruntime 9.98 5.70 2.04 17.90 PP-OCRv5_server_det paddle_static 13.24 26.91 2.63 43.05 paddle_dynamic 11.82 45.56 2.52 60.10 transformers 14.56 13.76 7.44 36.76 onnxruntime 10.01 13.76 1.92 25.86 PP-OCRv6_medium_det paddle_static 13.89 16.02 2.49 33.14 paddle_dynamic 11.42 26.23 2.30 40.10 transformers 11.40 8.57 8.35 29.57 onnxruntime 10.80 13.06 2.19 26.18 PP-OCRv6_small_det paddle_static 10.91 10.97 2.41 24.45 paddle_dynamic 11.56 22.17 2.66 36.55 transformers 11.70 7.34 3.87 23.89 onnxruntime 11.32 7.46 2.54 21.49 PP-OCRv6_tiny_det paddle_static 11.14 10.71 2.84 24.85 paddle_dynamic 11.52 21.70 2.94 36.31 transformers 10.90 6.99 4.13 23.00 onnxruntime 11.19 6.35 2.79 20.49 Test Environment Description:
- Test Data: Sample Image
- Hardware Configuration:
- GPU: NVIDIA A100 40G
- CPU: Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz
- Software Environment:
- Ubuntu 22.04 / CUDA 12.6 / cuDNN 9.5
- paddlepaddle-gpu 3.2.1 / paddleocr 3.5 / transformers 5.4.0 / torch 2.10 / onnxruntime-gpu 1.23.2
5.2 Weight Conversion
When using the inference engine, the system will automatically download the official pre-trained model. If you need to use a self-trained model with the
paddle_dynamicortransformersengine, please refer to the PaddleX Text Detection Module Weight Conversion section to convert the model from thepdparamsformat to thesafetensorsformat using PaddleX. This allows seamless integration into the PaddleOCR API for inference. If you need to use a self-trained model with theonnxruntimeengine, refer to PaddleX Obtain ONNX Models to obtain the ONNX model, so it can be seamlessly integrated into the PaddleOCR API for inference.6. FAQ
- Use parameters
limit_typeandlimit_side_lento constrain image dimensions.limit_typeoptions: [max,min]limit_side_len: Positive integer (typically multiples of 32, e.g., 960).- For lower-resolution images, use
limit_type=minandlimit_side_len=960to balance computational efficiency and detection quality. - For higher-resolution images requiring larger detection scales, set
limit_side_lento desired values (e.g., 1216).