Skip to content

Document Image Orientation Classification Module Tutorial

1. Overview

The Document Image Orientation Classification Module is primarily designed to distinguish the orientation of document images and correct them through post-processing. During processes such as document scanning or ID photo capturing, the device might be rotated to achieve clearer images, resulting in images with various orientations. Standard OCR pipelines may not handle these images effectively. By leveraging image classification techniques, the orientation of documents or IDs containing text regions can be pre-determined and adjusted, thereby improving the accuracy of OCR 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 "Normal Mode" values correspond to the local paddle_static inference engine.

ModelModel Download Links Top-1 Acc (%) GPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
CPU Inference Time (ms)
[Normal Mode / High-Performance Mode]
Model Size (MB) Description
PP-LCNet_x1_0_doc_ori Inference Model/Pretrained Model 99.06 2.62 / 0.59 3.24 / 1.19 7 A document image classification model based on PP-LCNet_x1_0, with four categories: 0°, 90°, 180°, and 270°.

Test Environment Description:

  • Performance Test Environment
    • Test Dataset: Self-built multi-scenario dataset (1000 images, including ID/document scenarios)
    • 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 Technology Combination
Normal Mode FP32 Precision / No TRT Acceleration FP32 Precision / 8 Threads PaddleInference
High-Performance Mode Optimal combination of precision type and acceleration strategy FP32 Precision / 8 Threads Optimal backend selected (Paddle/OpenVINO/TRT, etc.)

3. Quick Start

❗ Before starting, please install the PaddleOCR wheel package. For details, refer to the Installation Guide.

You can quickly experience it with one command:

paddleocr doc_img_orientation_classification -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/img_rot180_demo.jpg

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 doc_img_orientation_classification -i https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/img_rot180_demo.jpg \
    --engine transformers

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 of the Document Image Orientation Classification Module into your project. Before running the following code, please download the sample image to your local machine.

from paddleocr import DocImgOrientationClassification

model = DocImgOrientationClassification(model_name="PP-LCNet_x1_0_doc_ori")
output = model.predict("img_rot180_demo.jpg", batch_size=1)
for res in output:
    res.print(json_format=False)
    res.save_to_img("./output/demo.png")
    res.save_to_json("./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 DocImgOrientationClassification

model = DocImgOrientationClassification(
    model_name="PP-LCNet_x1_0_doc_ori",
    engine="transformers",
)
output = model.predict("img_rot180_demo.jpg", batch_size=1)
for res in output:
    res.print(json_format=False)
    res.save_to_img("./output/demo.png")
    res.save_to_json("./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.

After running, the result will be:

{'res': {'input_path': 'img_rot180_demo.jpg', 'page_index': None, 'class_ids': array([2], dtype=int32), 'scores': array([0.88164], dtype=float32), 'label_names': ['180']}}

The meaning of the output parameters is as follows:

  • input_path:Represents the path of the input image.
  • class_ids:Represents the predicted class ID, with four categories: 0°, 90°, 180°, and 270°.
  • scores:Represents the confidence level of the prediction result.
  • label_names:Represents the category names of the prediction results.

Here is the visualization of the image:

The explanations of relevant methods and parameters are as follows:

  • Instantiate the document image orientation classification model with DocImgOrientationClassification (taking PP-LCNet_x1_0_doc_ori as an example here). The specific explanations are as follows:
Parameter Description Type Default
model_name Meaning:Model name.
Description: If set to None, PP-LCNet_x1_0_doc_ori will be used.
str|None None
model_dir Meaning:Model storage path. str|None None
device Meaning: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|None None
engine Meaning: Inference engine.
Description: Supports None (the default), paddle, paddle_static, paddle_dynamic, and transformers. When left as None, local inference uses the paddle_static engine by default. For detailed descriptions, supported values, compatibility rules, and examples, see Inference Engine and Configuration.
str|None None
engine_config Meaning: Inference-engine configuration.
Description: Recommended together with engine. For supported fields, compatibility rules, and examples, see Inference Engine and Configuration.
dict|None None
enable_hpi Meaning:Whether to enable high-performance inference. bool False
use_tensorrt Meaning: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.
bool False
precision Meaning:Computation precision when using the TensorRT subgraph engine in Paddle Inference.
Description: Options:"fp32", "fp16".
str "fp32"
enable_mkldnn Meaning: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.
bool True
mkldnn_cache_capacity Meaning:MKL-DNN cache capacity. int 10
cpu_threads Meaning:Number of threads to use for inference on CPUs. int 10
  • Call the predict() method of the document image orientation classification model for inference prediction. This method will return a list of results. In addition, this module also provides the predict_iter() method. The two methods are completely consistent in terms of parameter acceptance and result return. The difference is that predict_iter() returns a generator, which can process and obtain prediction results step by step, suitable for scenarios where large datasets need to be processed or memory needs to be saved. You can choose either of these two methods according to your actual needs. The parameters of the predict() method are input and batch_size, and the specific explanations are as follows:
Parameter Description Type Default
input Meaning:Input data to be predicted. Required.
Description: Supports multiple input types:
  • Python Var: e.g., numpy.ndarray representing image data
  • str:Local image or PDF file path: /root/data/img.jpgURL of image or PDF file: e.g., example; Local directory: directory containing images for prediction, e.g., /root/data/ (Note: directories containing PDF files are not supported; PDFs must be specified by exact file path)
  • list: Elements must 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|list
batch_size Meaning:Batch size.
Description: Positive integer.
int 1
  • Process the prediction results. The prediction result for each sample is the corresponding Result object, and it supports operations such as printing, saving as an image, and saving as a json file:
Method Description Parameter Parameter Type Description Default Value
print() Print the result to the terminal format_json bool Whether to format the output content using JSON indentation True
indent int Specify the indentation level to beautify the output JSON data and make it more readable. It is only valid when format_json is True. 4
ensure_ascii bool Control whether to escape non-ASCII characters as Unicode. When set to True, all non-ASCII characters will be escaped; when set to False, the original characters will be retained. It is only valid when format_json is True. False
save_to_json() Save the result as a file in json format save_path str The file path to save. When it is a directory, the saved file name is consistent with the naming of the input file type. None
indent int Specify the indentation level to beautify the output JSON data and make it more readable. It is only valid when format_json is True. 4
ensure_ascii bool Control whether to escape non-ASCII characters as Unicode. When set to True, all non-ASCII characters will be escaped; when set to False, the original characters will be retained. It is only valid when format_json is True. False
save_to_img() Save the result as a file in image format save_path str The file path to save. When it is a directory, the saved file name is consistent with the naming of the input file type. None
  • In addition, it also supports obtaining the visualization image with results and the prediction results through attributes. The specifics are as follows:
Attribute Description
json Get the prediction result in json format
img Get the visualization image in dict format

4. Secondary Development

Since PaddleOCR does not directly provide training functionality for document image orientation classification, if you need to train a document image orientation classification model, you can refer to the PaddleX Secondary Development for Document Image Orientation Classification section for training guidance. The trained model can be seamlessly integrated into PaddleOCR's API for inference purposes.

If you want to use the paddle_dynamic or transformers engine with the trained model, please refer to the Weight Conversion section in Inference Engine later in this document to convert the model from the pdparams format to the safetensors format 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-LCNet_x1_0_doc_ori paddle_static 2.21 3.36 0.06 5.74
paddle_dynamic 2.15 7.54 0.07 9.87
transformers 4.46 3.44 0.14 8.36

Test Environment Description:

  • Test Data: [Sample Image](https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/img_rot180_demo.jpg)
  • 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

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_dynamic or transformers engine, please refer to the PaddleX Text Image Orientation Classification Module Weight Conversion section to convert the model from the pdparams format to the safetensors format using PaddleX. This allows seamless integration into the PaddleOCR API for inference.

6. FAQ

Comments