Skip to content

Paddle OCR

This document describes the PaddleOCR wrapper included in ECOS Core. It covers installation, configuration, usage examples, predict and the module API.

Overview

  • This module provides a small wrapper to run PaddleOCR inference within the ECOS ecosystem, with utilities for configuration, visualization, and batch processing.

Installation

Please install ecos_core and lib bellow:

pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cu118
pip install paddlepaddle-gpu==3.2.2 -i https://www.paddlepaddle.org.cn/packages/stable/cu118/
pip install "paddleocr[all]"

Requirements

pip install -r requirements.txt

Usage

Configuration

Configuration is managed through a JSON file (opt.json). Here's the example structure:

{
    "type": "pytorch",
    "conf": null,
    "text_detection_model_dir": "PP-OCRv5_server_det",
    "text_recognition_model_dir": "PP-OCRv5_server_rec_infer_best",
    "use_doc_orientation_classify": false,
    "use_doc_unwarping": false,
    "use_textline_orientation": false,
    "text_det_thresh": null,
    "text_rec_score_thresh": null,
    "class_names": ["OK", "NG"],
    "visualization": true
}

With: - data: Path to data.yaml file containing dataset configuration - weight: Model weight filename - weights_url: URL to download pre-trained weights - batch_size: Number of samples per training batch - epochs: Number of training epochs - device: Device to use (0,1,2,3 for GPU or "cpu") - imgsz: Target image size for training. - task: Task type. Default: "detect" - type: Framework type - conf: Confidence threshold for predictions - iou: IoU threshold for NMS - font_scale: Font scale for visualization text - text_thichness: Text thickness for visualization - padding_rect: Padding for text background rectangles - visualization: Enable/disable result visualization

Inference

Basic inference example:

import sys
import os
import json
import argparse
from glob import glob
import numpy as np
import cv2
sys.path.insert(0, os.path.abspath(
    os.path.join(os.path.dirname(__file__), './../../')
))
from ecos_core.paddle_ocr.paddle_ocr import Model
from easydict import EasyDict

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--opt',
                        type=str, default="./opt.json", help='opt path')

    parser.add_argument('--input-path', required=True,
                        type=str, default="input.jpeg", help='input path')
    parser.add_argument('--output-path', required=True,
                        type=str, default="./output.jpeg", help='output path')
    args = parser.parse_args()
    opt = args.opt

    input_path = args.input_path
    output_path = args.output_path
    with open(opt, "r") as f:
        opts = EasyDict(json.load(f))
    model = Model(opts)
    model.build_model()

    for image_path in glob(os.path.join(input_path, "*")):
        model.process_predictions(
            net_output="",
            raw_image_path=image_path,
            raw_image_mat=None,
            image_transform=None,
            save_image_path=os.path.join(output_path, os.path.basename(image_path))
        )

APIs

Model

Bases: BaseModel

build_model(custom_weight=None)

Build model in PaddleOCR model

Parameters:

Name Type Description Default
custom_weight str

custom weight path. Defaults to None.

None

Returns:

Name Type Description
model Model

PaddleOCR model

fit()

Train the model

Returns:

Name Type Description
results

training results

get_transform()

Get image data transform function for preprocessing

Returns:

Name Type Description
transform func

transform function. This function will take input as image path and output - raw_image: image numpy mat - image_transform: image tensor (pytorch) Example: torchvision.transforms.transforms: data transforms function

predict(source=None)

Run inference on images or folders.

Parameters:

Name Type Description Default
source str

image path or folder path. Defaults to None.

None
classes list

list of class ids to filter. Defaults to None.

required

Returns:

Name Type Description
results

prediction results

process_predictions(net_output, raw_image_path, raw_image_mat, image_transform, save_image_path)

Process predictions and generate annotated images.

Parameters:

Name Type Description Default
net_output

output of detection net

required
raw_image_path str

raw image path

required
raw_image_mat Array

raw image numpy mat type

required
image_transform func

image_transform function

required
save_image_path str

save image path

required

Returns:

Name Type Description
save_image_path

inform that the annotation image has been written successfully.

reload_param(opt_path='./opt.json')

Reload parameters

Parameters:

Name Type Description Default
opt_path str

Opt path. Defaults to "./opt.json".

'./opt.json'

update_opt(option, output_path='./opt.json')

Update config

Parameters:

Name Type Description Default
option Namespace / Dict

option to update

required
output_path str

path to save opt json. Defaults to "./opt.json".

'./opt.json'