📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
Add pytest
SWHL334f0f13e6d7
diff --git a/python/README.md b/python/README.mdindex 6e224a4..13026e8 100755--- a/python/README.md+++ b/python/README.md@@ -89,6 +89,11 @@- Note: 在Windows端,Shapely库可能自动安装会有问题,解决方案参见[Q15](../docs/FAQ.md#q15-装完环境之后运行python-mainpy之后报错oserror-winerror-126-找不到指定的模組)4. 运行示例+ - 运行单元测试+ ```bash+ cd tests+ pytest test_*.py+ ```- 接口调用```pythonimport cv2@@ -129,7 +134,7 @@|Global| `text_score` | [0, 1] | 0.5 | 文本识别结果置信度,值越大,把握越大 ||Global| `use_angle_cls` | `bool` | `true` | 是否使用文本行的方向分类 ||Global| `print_verbose` | `bool` | `true` | 是否打印各个部分耗时信息 |-|Global| `min_heigh` | `int` | 50 | 图像高度,单位是像素 |+|Global| `min_heigh` | `int` | 30 | 图像最小高度(单位是像素),低于这个值,会跳过文本检测阶段,直接进行后续识别 ||||||||Det| `box_thresh` | [0, 1] | 0.5 | 文本检测所得框是否保留的阈值,值越大,召回率越低 ||Det| `unclip_ratio` | [1.6, 2.0] | 1.6 | 控制文本检测框的大小,值越大,检测框整体越大 |diff --git a/python/rapidocr_onnxruntime/__init__.py b/python/rapidocr_onnxruntime/__init__.pyindex 90121b5..e0e6353 100644--- a/python/rapidocr_onnxruntime/__init__.py+++ b/python/rapidocr_onnxruntime/__init__.py@@ -1,4 +1,4 @@# -*- encoding: utf-8 -*-# @Author: SWHL# @Contact: [email protected]-from .rapid_ocr_api import TextSystem\ No newline at end of file+from .rapid_ocr_api import TextSystemdiff --git a/python/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py b/python/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.pyindex 38d8549..bdd6e17 100644--- a/python/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py+++ b/python/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py@@ -19,7 +19,6 @@ from typing import Listimport cv2import numpy as np-import onnxruntime as orttry:from .utils import ClsPostProcess, read_yaml, OrtInferSession@@ -38,29 +37,6 @@ class TextClassifier(object):self.session = session_instance.sessionself.input_name = session_instance.get_input_name()- def resize_norm_img(self, img):- img_c, img_h, img_w = self.cls_image_shape- h, w = img.shape[:2]- ratio = w / float(h)- if math.ceil(img_h * ratio) > img_w:- resized_w = img_w- else:- resized_w = int(math.ceil(img_h * ratio))-- resized_image = cv2.resize(img, (resized_w, img_h))- resized_image = resized_image.astype('float32')- if img_c == 1:- resized_image = resized_image / 255- resized_image = resized_image[np.newaxis, :]- else:- resized_image = resized_image.transpose((2, 0, 1)) / 255-- resized_image -= 0.5- resized_image /= 0.5- padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32)- padding_im[:, :, :resized_w] = resized_image- return padding_im-def __call__(self, img_list: List[np.ndarray]):if isinstance(img_list, np.ndarray):img_list = [img_list]@@ -106,6 +82,29 @@ class TextClassifier(object):img_list[indices[beg_img_no + rno]], 1)return img_list, cls_res, elapse+ def resize_norm_img(self, img):+ img_c, img_h, img_w = self.cls_image_shape+ h, w = img.shape[:2]+ ratio = w / float(h)+ if math.ceil(img_h * ratio) > img_w:+ resized_w = img_w+ else:+ resized_w = int(math.ceil(img_h * ratio))++ resized_image = cv2.resize(img, (resized_w, img_h))+ resized_image = resized_image.astype('float32')+ if img_c == 1:+ resized_image = resized_image / 255+ resized_image = resized_image[np.newaxis, :]+ else:+ resized_image = resized_image.transpose((2, 0, 1)) / 255++ resized_image -= 0.5+ resized_image /= 0.5+ padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32)+ padding_im[:, :, :resized_w] = resized_image+ return padding_im+if __name__ == "__main__":parser = argparse.ArgumentParser()diff --git a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yamlindex 428ccfc..21bc186 100644--- a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml+++ b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml@@ -1,11 +1,9 @@-model_path: G:\ProgramFiles\_self\RapidOCR\python\resources\models\ch_PP-OCRv2_det_infer.onnx+model_path: resources/models/ch_PP-OCRv2_det_infer.onnxuse_cuda: false-# Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.htmlCUDAExecutionProvider:device_id: 0arena_extend_strategy: kNextPowerOfTwo- gpu_mem_limit: 2 * 1024 * 1024 * 1024cudnn_conv_algo_search: EXHAUSTIVEdo_copy_in_default_stream: truediff --git a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.pyindex 19b6b31..e04c2b0 100644--- a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py+++ b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py@@ -20,7 +20,6 @@ import timeimport cv2import numpy as np-try:from .utils import (DBPostProcess, create_operators,draw_text_det_res, transform, read_yaml, OrtInferSession)diff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.pyindex 91c5b5c..b056524 100644--- a/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py@@ -40,29 +40,6 @@ class TextClassifier(object):self.session = ort.InferenceSession(config['model_path'], sess_opt)self.input_name = self.session.get_inputs()[0].name- def resize_norm_img(self, img):- img_c, img_h, img_w = self.cls_image_shape- h, w = img.shape[:2]- ratio = w / float(h)- if math.ceil(img_h * ratio) > img_w:- resized_w = img_w- else:- resized_w = int(math.ceil(img_h * ratio))-- resized_image = cv2.resize(img, (resized_w, img_h))- resized_image = resized_image.astype('float32')- if img_c == 1:- resized_image = resized_image / 255- resized_image = resized_image[np.newaxis, :]- else:- resized_image = resized_image.transpose((2, 0, 1)) / 255-- resized_image -= 0.5- resized_image /= 0.5- padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32)- padding_im[:, :, :resized_w] = resized_image- return padding_im-def __call__(self, img_list: List[np.ndarray]):if isinstance(img_list, np.ndarray):img_list = [img_list]@@ -108,6 +85,29 @@ class TextClassifier(object):img_list[indices[beg_img_no + rno]], 1)return img_list, cls_res, elapse+ def resize_norm_img(self, img):+ img_c, img_h, img_w = self.cls_image_shape+ h, w = img.shape[:2]+ ratio = w / float(h)+ if math.ceil(img_h * ratio) > img_w:+ resized_w = img_w+ else:+ resized_w = int(math.ceil(img_h * ratio))++ resized_image = cv2.resize(img, (resized_w, img_h))+ resized_image = resized_image.astype('float32')+ if img_c == 1:+ resized_image = resized_image / 255+ resized_image = resized_image[np.newaxis, :]+ else:+ resized_image = resized_image.transpose((2, 0, 1)) / 255++ resized_image -= 0.5+ resized_image /= 0.5+ padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32)+ padding_im[:, :, :resized_w] = resized_image+ return padding_im+if __name__ == "__main__":parser = argparse.ArgumentParser()diff --git a/python/requirements.txt b/python/requirements.txtindex fb2231c..ac08210 100644--- a/python/requirements.txt+++ b/python/requirements.txt@@ -4,4 +4,5 @@ opencv_python==4.5.1.48six>=1.15.0numpy>=1.19.2Pillow==8.3.0-PyYAML\ No newline at end of file+PyYAML+pytest\ No newline at end of filediff --git a/python/tests/base.py b/python/tests/base.pynew file mode 100644index 0000000..8b07ee7--- /dev/null+++ b/python/tests/base.py@@ -0,0 +1,26 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]++import importlib+from pathlib import Path+import sys++import yaml++package_name = 'rapidocr_onnxruntime'++root_dir = Path(__file__).resolve().parent.parent+sys.path.append(str(root_dir))+sys.path.append(str(root_dir / package_name))+++def init_module(module_name, class_name):+ module_part = importlib.import_module(module_name)+ return getattr(module_part, class_name)+++def read_yaml(yaml_path):+ with open(yaml_path, 'rb') as f:+ data = yaml.load(f, Loader=yaml.Loader)+ return data\ No newline at end of filediff --git a/python/tests/test_cls.py b/python/tests/test_cls.pynew file mode 100644index 0000000..d8c6dc5--- /dev/null+++ b/python/tests/test_cls.py@@ -0,0 +1,23 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import base+import cv2+++module_name = 'ch_ppocr_v2_cls'+class_name = 'TextClassifier'+TextClassifier = base.init_module(module_name, class_name)++yaml_path = base.root_dir / base.package_name / module_name / 'config.yaml'+config = base.read_yaml(str(yaml_path))+config['model_path'] = str(base.root_dir / config['model_path'])++text_cls = TextClassifier(config)+++def test_cls():+ img_path = 'test_files/text_cls.jpg'+ img = cv2.imread(img_path)+ result = text_cls([img])+ assert result[1][0][0] == '180'diff --git a/python/tests/test_det.py b/python/tests/test_det.pynew file mode 100644index 0000000..b0f8f2a--- /dev/null+++ b/python/tests/test_det.py@@ -0,0 +1,25 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import base+import cv2+++module_name = 'ch_ppocr_v2_det'+class_name = 'TextDetector'+TextDetector = base.init_module(module_name, class_name)++yaml_path = base.root_dir / base.package_name / module_name / 'config.yaml'+config = base.read_yaml(str(yaml_path))+config['model_path'] = str(base.root_dir / config['model_path'])++text_det = TextDetector(config)+++def test_det():+ img_path = 'test_files/ch_en_num.jpg'++ img = cv2.imread(img_path)++ dt_boxes, elapse = text_det(img)+ assert dt_boxes.shape == (18, 4, 2)diff --git a/python/tests/test_files/ch_en_num.jpg b/python/tests/test_files/ch_en_num.jpgnew file mode 100644index 0000000..d352416Binary files /dev/null and b/python/tests/test_files/ch_en_num.jpg differdiff --git a/python/tests/test_files/text_cls.jpg b/python/tests/test_files/text_cls.jpgnew file mode 100644index 0000000..fcd7e12Binary files /dev/null and b/python/tests/test_files/text_cls.jpg differ