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

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_oriInference Model/Pretrained Model 99.06 2.31 / 0.43 3.37 / 1.27 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
      • Other Environment: Ubuntu 20.04 / cuDNN 8.6 / TensorRT 8.5.2.2
  • 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

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")

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 Model name str PP-LCNet_x1_0_doc_ori
model_dir Model storage path str None
device Device(s) to use for inference.
Examples: cpu, gpu, npu, gpu:0, gpu:0,1.
If multiple devices are specified, inference will be performed in parallel. Note that parallel inference is not always supported.
By default, GPU 0 will be used if available; otherwise, the CPU will be used.
str None
enable_hpi Whether to use the high performance inference. bool False
use_tensorrt Whether to use the Paddle Inference TensorRT subgraph engine. bool False
min_subgraph_size Minimum subgraph size for TensorRT when using the Paddle Inference TensorRT subgraph engine. int 3
precision Precision for TensorRT when using the Paddle Inference TensorRT subgraph engine.
Options: fp32, fp16, etc.
str fp32
enable_mkldnn Whether to use MKL-DNN acceleration for inference. bool True
cpu_threads Number of threads to use for inference on CPUs. int 10
top_k The top-k value for prediction results. If not specified, the default value in the official PaddleOCR model configuration is used. If the value is 5, the top 5 categories and their corresponding classification probabilities will be returned. int None
  • Among them, model_name must be specified. After specifying model_name, the model parameters built into PaddleX are used by default. On this basis, when model_dir is specified, the user-defined model is used.

  • 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 Input data to be predicted. Required. Supports multiple input types:
  • Python Var: e.g., numpy.ndarray representing image data
  • str: - Local image or PDF file path: /root/data/img.jpg; - URL 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 Batch size, positive integer. int 1
top_k The top-k value for prediction results. If not specified, the value provided when the model was instantiated will be used; if it was not specified at instantiation either, the default value in the official PaddleOCR model configuration is used. int None
  • 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

IV. 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.

V. FAQ

Comments