Skip to content

📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.

Update rapidocr_openvino api and update to v1.2.0

SWHL0a603b4e8919
diff --git a/docs/doc_whl_rapidocr_vino.md b/docs/doc_whl_rapidocr_vino.md
index a717c8a..9f09b9b 100644
--- a/docs/doc_whl_rapidocr_vino.md
+++ b/docs/doc_whl_rapidocr_vino.md
@@ -2,6 +2,7 @@
<p>
<a href=""><img src="https://img.shields.io/badge/Python->=3.7,<=3.10-aff.svg"></a>
<a href=""><img src="https://img.shields.io/badge/OS-Linux%2C%20Win%2C%20Mac-pink.svg"></a>
+ <a href="https://pepy.tech/project/rapidocr_openvino"><img src="https://static.pepy.tech/personalized-badge/rapidocr_openvino?period=total&units=abbreviation&left_color=grey&right_color=blue&left_text=Downloads%20Vino"></a>
</p>
### 1. Install package by pypi.
@@ -45,14 +46,65 @@ $ pip install rapidocr-openvino
```
- Run by command line.
- ```bash
- $ rapidocr_openvino -h
- usage: rapidocr_openvino [-h] [-img IMG_PATH] [-p]
+ ```bash
+ $ rapidocr_openvino -h
+ usage: rapidocr_openvino [-h] -img IMG_PATH [-p] [--text_score TEXT_SCORE]
+ [--use_angle_cls USE_ANGLE_CLS]
+ [--use_text_det USE_TEXT_DET]
+ [--print_verbose PRINT_VERBOSE]
+ [--min_height MIN_HEIGHT]
+ [--width_height_ratio WIDTH_HEIGHT_RATIO]
+ [--det_model_path DET_MODEL_PATH]
+ [--det_limit_side_len DET_LIMIT_SIDE_LEN]
+ [--det_limit_type {max,min}]
+ [--det_thresh DET_THRESH]
+ [--det_box_thresh DET_BOX_THRESH]
+ [--det_unclip_ratio DET_UNCLIP_RATIO]
+ [--det_use_dilation DET_USE_DILATION]
+ [--det_score_mode {slow,fast}]
+ [--cls_model_path CLS_MODEL_PATH]
+ [--cls_image_shape CLS_IMAGE_SHAPE]
+ [--cls_label_list CLS_LABEL_LIST]
+ [--cls_batch_num CLS_BATCH_NUM]
+ [--cls_thresh CLS_THRESH]
+ [--rec_model_path REC_MODEL_PATH]
+ [--rec_image_shape REC_IMAGE_SHAPE]
+ [--rec_batch_num REC_BATCH_NUM]
optional arguments:
-h, --help show this help message and exit
-img IMG_PATH, --img_path IMG_PATH
-p, --print_cost
- $ rapidocr_openvino -img tests/test_files/ch_en_num.jpg
- ```
\ No newline at end of file
+ Global:
+ --text_score TEXT_SCORE
+ --use_angle_cls USE_ANGLE_CLS
+ --use_text_det USE_TEXT_DET
+ --print_verbose PRINT_VERBOSE
+ --min_height MIN_HEIGHT
+ --width_height_ratio WIDTH_HEIGHT_RATIO
+
+ Det:
+ --det_model_path DET_MODEL_PATH
+ --det_limit_side_len DET_LIMIT_SIDE_LEN
+ --det_limit_type {max,min}
+ --det_thresh DET_THRESH
+ --det_box_thresh DET_BOX_THRESH
+ --det_unclip_ratio DET_UNCLIP_RATIO
+ --det_use_dilation DET_USE_DILATION
+ --det_score_mode {slow,fast}
+
+ Cls:
+ --cls_model_path CLS_MODEL_PATH
+ --cls_image_shape CLS_IMAGE_SHAPE
+ --cls_label_list CLS_LABEL_LIST
+ --cls_batch_num CLS_BATCH_NUM
+ --cls_thresh CLS_THRESH
+
+ Rec:
+ --rec_model_path REC_MODEL_PATH
+ --rec_image_shape REC_IMAGE_SHAPE
+ --rec_batch_num REC_BATCH_NUM
+
+ $ rapidocr_openvino -img tests/test_files/ch_en_num.jpg
+ ```
\ No newline at end of file
diff --git a/python/README.md b/python/README.md
index 865da00..6c13213 100755
--- a/python/README.md
+++ b/python/README.md
@@ -12,6 +12,7 @@
- [RapidOCR Python](#rapidocr-python)
- [简介和说明](#简介和说明)
- [(推荐)pip安装快速使用](#推荐pip安装快速使用)
+ - [源码使用步骤](#源码使用步骤)
- [`config.yaml`中常用参数介绍](#configyaml中常用参数介绍)
- [onnxruntime-gpu版相关说明](#onnxruntime-gpu版相关说明)
- [onnxruntime-gpu版推理配置](#onnxruntime-gpu版推理配置)
@@ -52,6 +53,7 @@
1. 安装`rapidocr`包
- <a href="https://pypi.org/project/rapidocr-onnxruntime/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapidocr-onnxruntime?style=flat-square"></a> `rapidocr_onnxruntime` → `pip install rapidocr-onnxruntime`
- <a href="https://pypi.org/project/rapidocr-openvino/"><img alt="PyPI" src="https://img.shields.io/pypi/v/rapidocr-openvino?style=flat-square"></a> `rapidocr_openvino` → `pip install rapidocr-openvino`
+ - 注意:两个包接口一致,只是推理引擎不同而已
2. 推理使用
- 📌初始化RapidOCR可不提供`config.yaml`,默认使用**rapidocr_onnxruntime**目录下的。如有特殊需求,可以自行更改目录下的`config.yaml`。
@@ -87,7 +89,7 @@
# 如果没有有效文本,则result: (None, None)
```
- 命令行使用:
- ```bash
+ ```bash
$ rapidocr_onnxruntime -h
usage: rapidocr_onnxruntime [-h] -img IMG_PATH [-p] [--text_score TEXT_SCORE]
[--use_angle_cls USE_ANGLE_CLS]
diff --git a/python/rapidocr_openvino/rapid_ocr_api.py b/python/rapidocr_openvino/rapid_ocr_api.py
index 733a039..6ab02ab 100644
--- a/python/rapidocr_openvino/rapid_ocr_api.py
+++ b/python/rapidocr_openvino/rapid_ocr_api.py
@@ -1,7 +1,6 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-import argparse
import copy
import importlib
import sys
@@ -11,19 +10,23 @@ from typing import Union
import cv2
import numpy as np
-from .utils import LoadImage, read_yaml
+from .utils import LoadImage, ParseArgs, concat_model_path, read_yaml
root_dir = Path(__file__).resolve().parent
sys.path.append(str(root_dir))
class RapidOCR():
- def __init__(self, config_path=str(root_dir / 'config.yaml')):
- super(RapidOCR).__init__()
+ def __init__(self, **kwargs):
+ config_path = str(root_dir / 'config.yaml')
if not Path(config_path).exists():
raise FileExistsError(f'{config_path} does not exist!')
-
config = read_yaml(config_path)
+ config = concat_model_path(config)
+
+ if kwargs:
+ parser = ParseArgs()
+ config = parser.update_config(config, **kwargs)
global_config = config['Global']
self.print_verbose = global_config['print_verbose']
@@ -177,13 +180,8 @@ class RapidOCR():
def main():
- parser = argparse.ArgumentParser()
- parser.add_argument('-img', '--img_path', type=str, default=None)
- parser.add_argument('-p', '--print_cost',
- action='store_true', default=False)
- args = parser.parse_args()
-
- ocr_engine = RapidOCR()
+ args = ParseArgs().args
+ ocr_engine = RapidOCR(**vars(args))
result, elapse_list = ocr_engine(args.img_path)
print(result)
diff --git a/python/rapidocr_openvino/utils.py b/python/rapidocr_openvino/utils.py
index f4caf4e..d4c5163 100644
--- a/python/rapidocr_openvino/utils.py
+++ b/python/rapidocr_openvino/utils.py
@@ -1,8 +1,10 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
+import argparse
import imghdr
import tempfile
+import warnings
from contextlib import contextmanager
from pathlib import Path
from typing import Optional, Union
@@ -39,12 +41,6 @@ class OpenVINOInferSession():
raise FileExistsError(f'{model_path} is not a file.')
-def read_yaml(yaml_path):
- with open(yaml_path, 'rb') as f:
- data = yaml.load(f, Loader=yaml.Loader)
- return data
-
-
class LoadImage():
def __init__(self, ):
self.valid_format = ['jpg', 'jpeg', 'png', 'tiff', 'tif', 'bmp']
@@ -175,3 +171,129 @@ class LoadImage():
class LoadImageError(Exception):
pass
+
+
+def read_yaml(yaml_path):
+ with open(yaml_path, 'rb') as f:
+ data = yaml.load(f, Loader=yaml.Loader)
+ return data
+
+
+def concat_model_path(config):
+ key = 'model_path'
+ config['Det'][key] = str(root_dir / config['Det'][key])
+ config['Rec'][key] = str(root_dir / config['Rec'][key])
+ config['Cls'][key] = str(root_dir / config['Cls'][key])
+ return config
+
+
+class ParseArgs():
+ def __init__(self, ):
+ self.args = self.init_args()
+ self.args_dict = vars(self.args)
+
+ def init_args(self):
+ parser = argparse.ArgumentParser()
+ parser.add_argument('-img', '--img_path', type=str, default=None,
+ required=True)
+ parser.add_argument('-p', '--print_cost',
+ action='store_true', default=False)
+
+ global_group = parser.add_argument_group(title='Global')
+ global_group.add_argument('--text_score', type=float, default=0.5)
+ global_group.add_argument('--use_angle_cls', type=bool, default=True)
+ global_group.add_argument('--use_text_det', type=bool, default=True)
+ global_group.add_argument('--print_verbose', type=bool, default=False)
+ global_group.add_argument('--min_height', type=int, default=30)
+ global_group.add_argument('--width_height_ratio', type=int, default=8)
+
+ det_group = parser.add_argument_group(title='Det')
+ det_group.add_argument('--det_model_path', type=str, default=None)
+ det_group.add_argument('--det_limit_side_len', type=float, default=736)
+ det_group.add_argument('--det_limit_type', type=str, default='min',
+ choices=['max', 'min'])
+ det_group.add_argument('--det_thresh', type=float, default=0.3)
+ det_group.add_argument('--det_box_thresh', type=float, default=0.5)
+ det_group.add_argument('--det_unclip_ratio', type=float, default=1.6)
+ det_group.add_argument('--det_use_dilation', type=bool, default=True)
+ det_group.add_argument('--det_score_mode', type=str, default='fast',
+ choices=['slow', 'fast'])
+
+ cls_group = parser.add_argument_group(title='Cls')
+ cls_group.add_argument('--cls_model_path', type=str, default=None)
+ cls_group.add_argument('--cls_image_shape', type=list,
+ default=[3, 48, 192])
+ cls_group.add_argument('--cls_label_list', type=list,
+ default=['0', '180'])
+ cls_group.add_argument('--cls_batch_num', type=int, default=6)
+ cls_group.add_argument('--cls_thresh', type=float, default=0.9)
+
+ rec_group = parser.add_argument_group(title='Rec')
+ rec_group.add_argument('--rec_model_path', type=str, default=None)
+ rec_group.add_argument('--rec_image_shape', type=list,
+ default=[3, 48, 320])
+ rec_group.add_argument('--rec_batch_num', type=int, default=6)
+
+ args = parser.parse_args()
+ return args
+
+ def parse_kwargs(self, **kwargs):
+ global_dict, det_dict, cls_dict, rec_dict = {}, {}, {}, {}
+ for k, v in kwargs.items():
+ if k.startswith('det'):
+ det_dict[k] = v
+ elif k.startswith('cls'):
+ cls_dict[k] = v
+ elif k.startswith('rec'):
+ rec_dict[k] = v
+ else:
+ global_dict[k] = v
+ return global_dict, det_dict, cls_dict, rec_dict
+
+ def update_config(self, config, **kwargs):
+ global_dict, det_dict, cls_dict, rec_dict = self.parse_kwargs(**kwargs)
+ new_config = {
+ 'Global': self.update_global_params(config['Global'],
+ global_dict),
+ 'Det': self.update_det_params(config['Det'], det_dict),
+ 'Cls': self.update_cls_params(config['Cls'], cls_dict),
+ 'Rec': self.update_rec_params(config['Rec'], rec_dict)
+ }
+ return new_config
+
+ def update_global_params(self, config, global_dict):
+ config.update(global_dict)
+ return config
+
+ def update_det_params(self, config, det_dict):
+ det_dict = {k.split('det_')[1]: v for k, v in det_dict.items()}
+ if not det_dict['model_path']:
+ det_dict['model_path'] = str(root_dir / config['model_path'])
+ config.update(det_dict)
+ return config
+
+ def update_cls_params(self, config, cls_dict):
+ need_remove_prefix = ['cls_label_list', 'cls_model_path']
+ new_cls_dict = {}
+ for k, v in cls_dict.items():
+ if k in need_remove_prefix:
+ k = k.split('cls_')[1]
+ new_cls_dict[k] = v
+
+ if not new_cls_dict['model_path']:
+ new_cls_dict['model_path'] = str(root_dir / config['model_path'])
+ config.update(new_cls_dict)
+ return config
+
+ def update_rec_params(self, config, rec_dict):
+ need_remove_prefix = ['rec_model_path']
+ new_rec_dict = {}
+ for k, v in rec_dict.items():
+ if k in need_remove_prefix:
+ k = k.split('rec_')[1]
+ new_rec_dict[k] = v
+
+ if not new_rec_dict['model_path']:
+ new_rec_dict['model_path'] = str(root_dir / config['model_path'])
+ config.update(new_rec_dict)
+ return config