📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
Update openvino infer
SWHL624d14a6a7e2
diff --git a/README.md b/README.mdindex ca6b9f3..9d4e1d6 100755--- a/README.md+++ b/README.md@@ -5,7 +5,7 @@# RapidOCR (捷智OCR)-简体中文 | [English](./doc/README_en.md)+简体中文 | [English](./docs/README_en.md)<p align="left"><a href="https://colab.research.google.com/github/RapidAI/RapidOCR/blob/main/assets/RapidOCRDemo.ipynb" target="_blank"><img src="./assets/colab-badge.svg" alt="Open in Colab"></a>@@ -58,12 +58,12 @@- 基于百度的开源PaddleOCR 模型及训练,任何人可以使用本推理库,也可以根据自己的需求使用百度的paddlepaddle框架进行模型优化。-## 近期更新([more](./doc/change_log.md))+## 近期更新([more](./docs/change_log.md))#### 🥟2022-05-25 update-- 增加基于PaddleOCR v3 rec的python版本推理代码,详情参见[v3 rec](./python/onnxruntime_infer/ch_ppocr_mobile_v3_rec/)+- 增加基于PaddleOCR v3 rec的python版本推理代码,详情参见[v3 rec](./python/rapidocr_onnxruntime/ch_ppocr_v3_rec)#### 🍿2022-05-15 update-- 增加PaddleOCR v3 rec模型转换后的ONNX模型,直接去网盘下载替换即可。([百度网盘](https://pan.baidu.com/s/1mkirNltJS481In4g81jP3w?pwd=zy37) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing))+- 增加PaddleOCR v3 rec模型转换后的ONNX模型,直接去网盘下载替换即可。([百度网盘](https://pan.baidu.com/s/1PTcgXG2zEgQU6A_A3kGJ3Q?pwd=jhai) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing))- 增加文本识别模型各个版本效果对比表格,详情点击[各个版本ONNX模型效果对比](#各个版本onnx模型效果对比)。v3的文本识别模型从自己构建测试集上的指标来看不如之前的好。#### 😀2022-05-12 upadte@@ -72,8 +72,7 @@#### 🎧2022-04-04 update- 增加python下的基于OpenVINO推理引擎的支持-- 给出OpenVINO和ONNXRuntime的性能对比表格-- 详情参见:[python/README](./python/README.md)+- 给出OpenVINO和ONNXRuntime的性能对比表格,详情参见:[python/rapidocr_openvino/README](./python/rapidocr_openvino/README.md)## 整个框架@@ -81,7 +80,7 @@<img src="./assets/RapidOCR_system.png"></div>-## 常见问题 [FAQ](./doc/FAQ.md)+## 常见问题 [FAQ](./docs/FAQ.md)## SDK 编译状态鉴于ubuntu用户都是商业用户,也有编译能力,暂不提供预编译包使用,可自行编译。@@ -136,7 +135,7 @@- [ ] 依据python版本重写C++推理代码,以提升推理效果,并增加对gif/tga/webp 格式图片的支持## 模型相关-- 可以直接下载使用的模型 ([百度网盘](https://pan.baidu.com/s/1mkirNltJS481In4g81jP3w?pwd=zy37) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing))+- 可以直接下载使用的模型 ([百度网盘](https://pan.baidu.com/s/1PTcgXG2zEgQU6A_A3kGJ3Q?pwd=jhai) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing))|模型名称|模型简介|模型大小|备注||:---:|:---:|:---:|:---:|@@ -166,7 +165,7 @@#### 模型转onnx- - ⭐[PaddleOCRModelConverter](https://github.com/RapidAI/PaddleOCRModelConverter) by @[SWHL](https://github.com/SWHL)+ - [PaddleOCRModelConverter](https://github.com/RapidAI/PaddleOCRModelConverter) by @[SWHL](https://github.com/SWHL)- [Paddle2OnnxConvertor](https://github.com/RapidAI/Paddle2OnnxConvertor) by @[benjaminwan](https://github.com/benjaminwan)- [手把手教你使用ONNXRunTime部署PP-OCR](https://aistudio.baidu.com/aistudio/projectdetail/1479970?channelType=0&channel=0) by @[Channingss](https://github.com/Channingss)diff --git a/docs/FAQ.md b/docs/FAQ.mdindex f7390d1..b946edb 100644--- a/docs/FAQ.md+++ b/docs/FAQ.md@@ -1,8 +1,8 @@## 常见问题-#### Q15: 装完环境之后,运行python main.py之后,报错OSError: [WinError 126] 找不到指定的模組+#### Q15: Windows系统下,装完环境之后,运行示例程序之后,报错OSError: [WinError 126] 找不到指定的模組**A**: 原因是Shapely库没有正确安装,如果是在Windows,可以在[Shapely whl](https://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely)下载对应的whl包,离线安装即可;另外一种解决办法是用conda安装也可。-#### Q14: Linux部署python的程序时,import cv2,会报`ImportError: ligGL.so.1: cannot open shared object file: No such file or directory`?+#### Q14: Linux部署python的程序时,`import cv2`时会报`ImportError: ligGL.so.1: cannot open shared object file: No such file or directory`?**A:**: [解决方法](https://stackoverflow.com/a/63978454/3335415) 有两个(来自群友ddeef):1. 安装`opencv-python-headless`取代`opencv-python`;diff --git a/python/README.md b/python/README.mdindex 725ed3b..b4382f3 100755--- a/python/README.md+++ b/python/README.md@@ -8,6 +8,15 @@- 每个独立的模块下均有独立的`config.yaml`配置文件,可以单独使用- `det`的`mobile`和`server`版,共用一个推理代码,直接更改配置文件中模型路径即可- `rec`的`mobile`和`server`版本,共用一个推理代码,直接更改配置文件中模型路径即可+- onnxruntime和OpenVINO调用方式如下:+ ```python+ # 基于onnxruntime引擎推理+ from rapidocr_onnxruntime import TextSystem++ # 基于openvin引擎推理+ from rapidocr_openvino import TextSystem+ ```+- 值得说明的是,基于openvino推理部分中`ch_ppocr_v2_cls`部分仍然是基于onnxruntime的,原因是openvino有bug,详情见[openvino/issue](https://github.com/openvinotoolkit/openvino/issues/11501)### 使用步骤1. 下载当前下的`rapidocr_onnxruntime`目录到本地@@ -44,16 +53,28 @@└── rec_images```3. 安装运行环境- ```bash- pip install -r requirements.txt -i https://pypi.douban.com/simple/- ```+ - 基于onnxruntime推理所需环境安装:+ ```bash+ pip install onnxruntime>=1.7.0+ ```+ - 基于OpenVINO推理所需环境安装:+ ```bash+ # Windows端+ pip install openvino==2022.1.0++ pip install -r requirements.txt -i https://pypi.douban.com/simple/+ ```- Note: 在Windows端,Shapely库可能自动安装会有问题,解决方案参见[Q15](../docs/FAQ.md#q15-装完环境之后运行python-mainpy之后报错oserror-winerror-126-找不到指定的模組)4. 运行示例- 接口调用```python+ # 基于onnxruntime引擎推理from rapidocr_onnxruntime import TextSystem+ # 基于OpenVINO引擎推理+ # from rapidocr_openvino import TextSystem+config_path = 'config.yaml'text_sys = TextSystem(config_path)diff --git a/python/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py b/python/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.pyindex 19af358..2753ea7 100644--- a/python/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py+++ b/python/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py@@ -110,7 +110,6 @@ class TextRecognizer(object):if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument('--image_path', type=str, help='image_dir|image_path')- parser.add_argument('--model_path', type=str, help='rec_model_path')parser.add_argument('--config_path', type=str, default='config.yaml')args = parser.parse_args()diff --git a/python/rapidocr_openvino/README.md b/python/rapidocr_openvino/README.mdnew file mode 100644index 0000000..8cc4858--- /dev/null+++ b/python/rapidocr_openvino/README.md@@ -0,0 +1,87 @@+#### 基于OpenVINO推理引擎+- OpenVINO推理方向分类模型有误,已经提了[issue](https://github.com/openvinotoolkit/openvino/issues/11501)→ 问题有已经解决,但是需要自己编译OpenVINO,参见[Answer](https://github.com/openvinotoolkit/openvino/issues/11501#issuecomment-1096366363)++#### 安装+```bash+# Windows端+pip install openvino==2022.1.0++# 里面含有mo+pip install openvino-dev==2022.1.0+```++#### 模型问题+- 因为OpenVINO可以直接推理ONNX模型,故这里暂时不作转换,直接推理之前ONNX模型即可+- 这里仍然给出转换的代码,用作参考:+ ```bash+ mo --input_model models/ch_PP-OCRv2_det_infer.onnx --output_dir models/IR/++ mo --input_model models/ch_PP-OCRv2_det_infer.onnx \+ --output_dir models/IR/static \+ --input_shape "[1,3,12128,800]"+ ```+++### 关于OpenVINO+- OpenVINO可以直接推理IR、ONNX和PaddlePaddle模型,具体如下(图来源:[link](https://docs.openvino.ai/latest/openvino_docs_OV_UG_OV_Runtime_User_Guide.html#doxid-openvino-docs-o-v-u-g-o-v-runtime-user-guide)):++ <div align="center">+ <img src="../assets/BASIC_FLOW_IE_C.svg">+ </div>++- 和ONNXRuntime同时推理同一个ONNX模型,OpenVINO推理速度更快+- 但是从对比来看,OpenVINO占用内存更大,其原因是拿空间换的时间+ - 当指定`input_shape`在一个区间范围时,推理时内存占用会减少一些+ - 示例命令:+ ```bash+ mo --input_model models/ch_PP-OCRv2_det_infer.onnx \+ --output_dir models/IR/static \+ --input_shape "[1,3,960:1200,800]"+ ```++### OpenVINO与ONNXRuntime性能对比+- 推理设备:`Windows 64位 Intel(R) Core(TM) i5-4210M CPU @ 2.60GHz 2.59 GHz`+- [测试图像宽高](https://drive.google.com/file/d/1iJcGvOVIdUlyOS52bBdvO8uzx8QORo5M/view?usp=sharing): `12119x810`++| 测试模型 | 推理框架 | 占用内存(3次平均) | 推理时间(3次平均) |+| ------------------------------------ | -------------------- | ----------------- | ----------------- |+| `ch_PP-OCRv2_det_infer.onnx` | `ONNXRuntime=1.10.0` | 0.8G | 5.354s |+| `ch_PP-OCRv2_det_infer.onnx` | `openvino=2022.1.0` | 3.225G | 2.53s |+| `ch_PP-OCRv2_det_infer.xml` FP32 动态图 | `openvino=2022.1.0` | 3.175G | 2.0455s |+++### OpenVINO与ONNXRuntime推理代码写法对比+NOTE: 以`ch_ppocr_mobile_v2_det`中推理代码为例子++- ONNXRuntime+```python+import onnxruntime++# 声明+sess_opt = onnxruntime.SessionOptions()+sess_opt.log_severity_level = 4+sess_opt.enable_cpu_mem_arena = False+self.session = onnxruntime.InferenceSession(det_model_path, sess_opt)+self.input_name = self.session.get_inputs()[0].name+self.output_name = self.session.get_outputs()[0].name++# 推理+preds = self.session.run([self.output_name],+ {self.input_name: img})+```++- OpenVINO+```python+from openvino.runtime import Core++# 初始化+ie = Core()+model_onnx = ie.read_model(det_model_path)+compile_model = ie.compile_model(model=model_onnx,+ device_name='CPU')+self.vino_session = compile_model.create_infer_request()++# 推理+self.vino_session.infer(inputs=[img])+vino_preds = self.vino_session.get_output_tensor().data+```diff --git a/python/rapidocr_openvino/__init__.py b/python/rapidocr_openvino/__init__.pynew file mode 100644index 0000000..90121b5--- /dev/null+++ b/python/rapidocr_openvino/__init__.py@@ -0,0 +1,4 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from .rapid_ocr_api import TextSystem\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/__init__.py b/python/rapidocr_openvino/ch_ppocr_v2_cls/__init__.pynew file mode 100644index 0000000..c5a5e1f--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/__init__.py@@ -0,0 +1,4 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from .text_cls import TextClassifier\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/config.yaml b/python/rapidocr_openvino/ch_ppocr_v2_cls/config.yamlnew file mode 100644index 0000000..e6fa00e--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/config.yaml@@ -0,0 +1,6 @@+model_path: resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx++cls_image_shape: [3, 48, 192]+cls_batch_num: 6+cls_thresh: 0.9+label_list: ['0', '180']\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.pynew file mode 100644index 0000000..fc06ac1--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py@@ -0,0 +1,126 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import argparse+import copy+import math+import time+from typing import List++import cv2+import numpy as np+import onnxruntime as ort++try:+ from .utils import ClsPostProcess, read_yaml+except:+ from utils import ClsPostProcess, read_yaml+++class TextClassifier(object):+ def __init__(self, config):+ self.cls_image_shape = config['cls_image_shape']+ self.cls_batch_num = config['cls_batch_num']+ self.cls_thresh = config['cls_thresh']+ self.postprocess_op = ClsPostProcess(config['label_list'])++ sess_opt = ort.SessionOptions()+ sess_opt.log_severity_level = 4+ sess_opt.enable_cpu_mem_arena = False+ 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]++ img_list = copy.deepcopy(img_list)++ # Calculate the aspect ratio of all text bars+ width_list = [img.shape[1] / float(img.shape[0]) for img in img_list]++ # Sorting can speed up the cls process+ indices = np.argsort(np.array(width_list))++ img_num = len(img_list)+ cls_res = [['', 0.0]] * img_num+ batch_num = self.cls_batch_num+ elapse = 0+ for beg_img_no in range(0, img_num, batch_num):+ end_img_no = min(img_num, beg_img_no + batch_num)+ max_wh_ratio = 0+ for ino in range(beg_img_no, end_img_no):+ h, w = img_list[indices[ino]].shape[0:2]+ wh_ratio = w * 1.0 / h+ max_wh_ratio = max(max_wh_ratio, wh_ratio)++ norm_img_batch = []+ for ino in range(beg_img_no, end_img_no):+ norm_img = self.resize_norm_img(img_list[indices[ino]])+ norm_img = norm_img[np.newaxis, :]+ norm_img_batch.append(norm_img)+ norm_img_batch = np.concatenate(norm_img_batch).astype(np.float32)++ starttime = time.time()+ onnx_inputs = {self.input_name: norm_img_batch}+ prob_out = self.session.run(None, onnx_inputs)[0]+ cls_result = self.postprocess_op(prob_out)+ elapse += time.time() - starttime++ for rno in range(len(cls_result)):+ label, score = cls_result[rno]+ cls_res[indices[beg_img_no + rno]] = [label, score]+ if '180' in label and score > self.cls_thresh:+ img_list[indices[beg_img_no + rno]] = cv2.rotate(+ img_list[indices[beg_img_no + rno]], 1)+ return img_list, cls_res, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('--image_path', type=str, help='image_dir|image_path')+ parser.add_argument('--config_path', type=str, default='config.yaml')+ args = parser.parse_args()++ config = read_yaml(args.config_path)++ text_classifier = TextClassifier(config)++ img = cv2.imread(args.image_path)+ img_list, cls_res, predict_time = text_classifier(img)+ for ino in range(len(img_list)):+ print(f"分类结果:{cls_res[ino]}")diff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/utils.py b/python/rapidocr_openvino/ch_ppocr_v2_cls/utils.pynew file mode 100644index 0000000..dae9175--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/utils.py@@ -0,0 +1,38 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import yaml+++def read_yaml(yaml_path):+ with open(yaml_path, 'rb') as f:+ data = yaml.load(f, Loader=yaml.Loader)+ return data+++class ClsPostProcess(object):+ """ Convert between text-label and text-index """++ def __init__(self, label_list):+ super(ClsPostProcess, self).__init__()+ self.label_list = label_list++ def __call__(self, preds, label=None):+ pred_idxs = preds.argmax(axis=1)+ decode_out = [(self.label_list[idx], preds[i, idx])+ for i, idx in enumerate(pred_idxs)]+ if label is None:+ return decode_out++ label = [(self.label_list[idx], 1.0) for idx in label]+ return decode_out, label\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_det/__init__.py b/python/rapidocr_openvino/ch_ppocr_v2_det/__init__.pynew file mode 100644index 0000000..dd23c8b--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_det/__init__.py@@ -0,0 +1,4 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from .text_detect import TextDetector\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_det/config.yaml b/python/rapidocr_openvino/ch_ppocr_v2_det/config.yamlnew file mode 100644index 0000000..0f08b09--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_det/config.yaml@@ -0,0 +1,21 @@+model_path: resources/models/ch_ppocr_server_v2.0_det_infer.onnx++pre_process:+ DetResizeForTest:+ limit_side_len: 736+ limit_type: min+ NormalizeImage:+ std: [0.229, 0.224, 0.225]+ mean: [0.485, 0.456, 0.406]+ scale: 1./255.+ order: hwc+ ToCHWImage:+ KeepKeys:+ keep_keys: ['image', 'shape']++post_process:+ thresh: 0.3+ box_thresh: 0.5+ max_candidates: 1000+ unclip_ratio: 1.6+ use_dilation: truediff --git a/python/rapidocr_openvino/ch_ppocr_v2_det/text_detect.py b/python/rapidocr_openvino/ch_ppocr_v2_det/text_detect.pynew file mode 100644index 0000000..a4e960a--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_det/text_detect.py@@ -0,0 +1,120 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# -*- encoding: utf-8 -*-+import argparse+import time++import cv2+import numpy as np+from openvino.runtime import Core++try:+ from .utils import (DBPostProcess, create_operators,+ draw_text_det_res, transform, read_yaml)+except:+ from utils import (DBPostProcess, create_operators,+ draw_text_det_res, transform, read_yaml)+++class TextDetector(object):+ def __init__(self, config):+ self.preprocess_op = create_operators(config['pre_process'])+ self.postprocess_op = DBPostProcess(**config['post_process'])++ ie = Core()+ model_onnx = ie.read_model(config['model_path'])+ compile_model = ie.compile_model(model=model_onnx, device_name='CPU')+ self.session = compile_model.create_infer_request()++ def order_points_clockwise(self, pts):+ """+ reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py+ # sort the points based on their x-coordinates+ """+ xSorted = pts[np.argsort(pts[:, 0]), :]++ # grab the left-most and right-most points from the sorted+ # x-roodinate points+ leftMost = xSorted[:2, :]+ rightMost = xSorted[2:, :]++ # now, sort the left-most coordinates according to their+ # y-coordinates so we can grab the top-left and bottom-left+ # points, respectively+ leftMost = leftMost[np.argsort(leftMost[:, 1]), :]+ (tl, bl) = leftMost++ rightMost = rightMost[np.argsort(rightMost[:, 1]), :]+ (tr, br) = rightMost++ rect = np.array([tl, tr, br, bl], dtype="float32")+ return rect++ def clip_det_res(self, points, img_height, img_width):+ for pno in range(points.shape[0]):+ points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))+ points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))+ return points++ def filter_tag_det_res(self, dt_boxes, image_shape):+ img_height, img_width = image_shape[:2]+ dt_boxes_new = []+ for box in dt_boxes:+ box = self.order_points_clockwise(box)+ box = self.clip_det_res(box, img_height, img_width)+ rect_width = int(np.linalg.norm(box[0] - box[1]))+ rect_height = int(np.linalg.norm(box[0] - box[3]))+ if rect_width <= 3 or rect_height <= 3:+ continue+ dt_boxes_new.append(box)+ dt_boxes = np.array(dt_boxes_new)+ return dt_boxes++ def __call__(self, img):+ ori_im = img.copy()+ data = {'image': img}+ data = transform(data, self.preprocess_op)+ img, shape_list = data+ if img is None:+ return None, 0++ img = np.expand_dims(img, axis=0).astype(np.float32)+ shape_list = np.expand_dims(shape_list, axis=0)++ starttime = time.time()+ self.session.infer(inputs=[img])+ preds = self.session.get_output_tensor().data++ post_result = self.postprocess_op(preds, shape_list)+ dt_boxes = post_result[0]['points']+ dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)+ elapse = time.time() - starttime+ return dt_boxes, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('--config_path', type=str, default='config.yaml')+ parser.add_argument('--image_path', type=str, default=None)+ args = parser.parse_args()++ config = read_yaml(args.config_path)++ text_detector = TextDetector(config)++ img = cv2.imread(args.image_path)+ dt_boxes, elapse = text_detector(img)+ src_im = draw_text_det_res(dt_boxes, args.image_path)+ cv2.imwrite('det_results.jpg', src_im)+ print('图像已经保存为det_results.jpg了')diff --git a/python/rapidocr_openvino/ch_ppocr_v2_det/utils.py b/python/rapidocr_openvino/ch_ppocr_v2_det/utils.pynew file mode 100644index 0000000..ffbd17f--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_det/utils.py@@ -0,0 +1,386 @@+"""+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""+# coding:utf-8+from __future__ import (absolute_import, division, print_function,+ unicode_literals)++import os+import sys++import cv2+import numpy as np+import pyclipper+import six+from shapely.geometry import Polygon+import yaml+++def read_yaml(yaml_path):+ with open(yaml_path, 'rb') as f:+ data = yaml.load(f, Loader=yaml.Loader)+ return data+++class DecodeImage(object):+ """ decode image """++ def __init__(self, img_mode='RGB', channel_first=False):+ self.img_mode = img_mode+ self.channel_first = channel_first++ def __call__(self, data):+ img = data['image']+ if six.PY2:+ assert type(img) is str and len(img) > 0, "invalid input 'img' in DecodeImage"+ else:+ assert type(img) is bytes and len(img) > 0, "invalid input 'img' in DecodeImage"++ img = np.frombuffer(img, dtype='uint8')+ img = cv2.imdecode(img, 1)+ if img is None:+ return None++ if self.img_mode == 'GRAY':+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ elif self.img_mode == 'RGB':+ assert img.shape[2] == 3, f'invalid shape of image[{img.shape}]'+ img = img[:, :, ::-1]++ if self.channel_first:+ img = img.transpose((2, 0, 1))+ data['image'] = img+ return data+++class NormalizeImage(object):+ """ normalize image such as substract mean, divide std"""++ def __init__(self, scale=None, mean=None, std=None, order='chw'):+ if isinstance(scale, str):+ scale = eval(scale)+ self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)+ mean = mean if mean is not None else [0.485, 0.456, 0.406]+ std = std if std is not None else [0.229, 0.224, 0.225]++ shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)+ self.mean = np.array(mean).reshape(shape).astype('float32')+ self.std = np.array(std).reshape(shape).astype('float32')++ def __call__(self, data):+ img = np.array(data['image']).astype(np.float32)+ data['image'] = (img * self.scale - self.mean) / self.std+ return data+++class ToCHWImage(object):+ """ convert hwc image to chw image"""+ def __init__(self):+ pass++ def __call__(self, data):+ img = data['image']+ from PIL import Image+ if isinstance(img, Image.Image):+ img = np.array(img)+ data['image'] = img.transpose((2, 0, 1))+ return data+++class KeepKeys(object):+ def __init__(self, keep_keys):+ self.keep_keys = keep_keys++ def __call__(self, data):+ data_list = []+ for key in self.keep_keys:+ data_list.append(data[key])+ return data_list+++class DetResizeForTest(object):+ def __init__(self, **kwargs):+ super(DetResizeForTest, self).__init__()+ self.resize_type = 0+ if 'image_shape' in kwargs:+ self.image_shape = kwargs['image_shape']+ self.resize_type = 1+ elif 'limit_side_len' in kwargs:+ self.limit_side_len = kwargs['limit_side_len']+ self.limit_type = kwargs.get('limit_type', 'min')++ if 'resize_long' in kwargs:+ self.resize_type = 2+ self.resize_long = kwargs.get('resize_long', 960)+ else:+ self.limit_side_len = 736+ self.limit_type = 'min'++ def __call__(self, data):+ img = data['image']+ src_h, src_w, _ = img.shape++ if self.resize_type == 0:+ # img, shape = self.resize_image_type0(img)+ img, [ratio_h, ratio_w] = self.resize_image_type0(img)+ elif self.resize_type == 2:+ img, [ratio_h, ratio_w] = self.resize_image_type2(img)+ else:+ # img, shape = self.resize_image_type1(img)+ img, [ratio_h, ratio_w] = self.resize_image_type1(img)+ data['image'] = img+ data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w])+ return data++ def resize_image_type1(self, img):+ resize_h, resize_w = self.image_shape+ ori_h, ori_w = img.shape[:2] # (h, w, c)+ ratio_h = float(resize_h) / ori_h+ ratio_w = float(resize_w) / ori_w+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ # return img, np.array([ori_h, ori_w])+ return img, [ratio_h, ratio_w]++ def resize_image_type0(self, img):+ """+ resize image to a size multiple of 32 which is required by the network+ args:+ img(array): array with shape [h, w, c]+ return(tuple):+ img, (ratio_h, ratio_w)+ """+ limit_side_len = self.limit_side_len+ h, w, _ = img.shape++ # limit the max side+ if self.limit_type == 'max':+ if max(h, w) > limit_side_len:+ if h > w:+ ratio = float(limit_side_len) / h+ else:+ ratio = float(limit_side_len) / w+ else:+ ratio = 1.+ else:+ if min(h, w) < limit_side_len:+ if h < w:+ ratio = float(limit_side_len) / h+ else:+ ratio = float(limit_side_len) / w+ else:+ ratio = 1.+ resize_h = int(h * ratio)+ resize_w = int(w * ratio)++ resize_h = int(round(resize_h / 32) * 32)+ resize_w = int(round(resize_w / 32) * 32)++ try:+ if int(resize_w) <= 0 or int(resize_h) <= 0:+ return None, (None, None)+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ except:+ print(img.shape, resize_w, resize_h)+ sys.exit(0)+ ratio_h = resize_h / float(h)+ ratio_w = resize_w / float(w)+ return img, [ratio_h, ratio_w]++ def resize_image_type2(self, img):+ h, w, _ = img.shape++ resize_w = w+ resize_h = h++ # Fix the longer side+ if resize_h > resize_w:+ ratio = float(self.resize_long) / resize_h+ else:+ ratio = float(self.resize_long) / resize_w++ resize_h = int(resize_h * ratio)+ resize_w = int(resize_w * ratio)++ max_stride = 128+ resize_h = (resize_h + max_stride - 1) // max_stride * max_stride+ resize_w = (resize_w + max_stride - 1) // max_stride * max_stride+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ ratio_h = resize_h / float(h)+ ratio_w = resize_w / float(w)++ return img, [ratio_h, ratio_w]+++def transform(data, ops=None):+ """ transform """+ if ops is None:+ ops = []+ for op in ops:+ data = op(data)+ if data is None:+ return None+ return data+++def create_operators(op_param_dict):+ """+ create operators based on the config+ """+ ops = []+ for op_name, param in op_param_dict.items():+ if param is None:+ param = {}+ op = eval(op_name)(**param)+ ops.append(op)+ return ops+++def draw_text_det_res(dt_boxes, img_path):+ src_im = cv2.imread(img_path)+ for box in dt_boxes:+ box = np.array(box).astype(np.int32).reshape(-1, 2)+ cv2.polylines(src_im, [box], True,+ color=(255, 255, 0), thickness=2)+ return src_im+++class DBPostProcess(object):+ """The post process for Differentiable Binarization (DB)."""++ def __init__(self,+ thresh=0.3,+ box_thresh=0.7,+ max_candidates=1000,+ unclip_ratio=2.0,+ use_dilation=False):+ self.thresh = thresh+ self.box_thresh = box_thresh+ self.max_candidates = max_candidates+ self.unclip_ratio = unclip_ratio+ self.min_size = 3++ if use_dilation:+ self.dilation_kernel = np.array([[1, 1], [1, 1]])+ else:+ self.dilation_kernel = None++ def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):+ '''+ _bitmap: single map with shape (1, H, W),+ whose values are binarized as {0, 1}+ '''++ bitmap = _bitmap+ height, width = bitmap.shape++ outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST,+ cv2.CHAIN_APPROX_SIMPLE)+ if len(outs) == 3:+ img, contours, _ = outs[0], outs[1], outs[2]+ elif len(outs) == 2:+ contours, _ = outs[0], outs[1]++ num_contours = min(len(contours), self.max_candidates)++ boxes = []+ scores = []+ for index in range(num_contours):+ contour = contours[index]+ points, sside = self.get_mini_boxes(contour)+ if sside < self.min_size:+ continue+ points = np.array(points)+ score = self.box_score_fast(pred, points.reshape(-1, 2))+ if self.box_thresh > score:+ continue++ box = self.unclip(points).reshape(-1, 1, 2)+ box, sside = self.get_mini_boxes(box)+ if sside < self.min_size + 2:+ continue+ box = np.array(box)++ box[:, 0] = np.clip(+ np.round(box[:, 0] / width * dest_width), 0, dest_width)+ box[:, 1] = np.clip(+ np.round(box[:, 1] / height * dest_height), 0, dest_height)+ boxes.append(box.astype(np.int16))+ scores.append(score)+ return np.array(boxes, dtype=np.int16), scores++ def unclip(self, box):+ unclip_ratio = self.unclip_ratio+ poly = Polygon(box)+ distance = poly.area * unclip_ratio / poly.length+ offset = pyclipper.PyclipperOffset()+ offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)+ expanded = np.array(offset.Execute(distance))+ return expanded++ def get_mini_boxes(self, contour):+ bounding_box = cv2.minAreaRect(contour)+ points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])++ index_1, index_2, index_3, index_4 = 0, 1, 2, 3+ if points[1][1] > points[0][1]:+ index_1 = 0+ index_4 = 1+ else:+ index_1 = 1+ index_4 = 0+ if points[3][1] > points[2][1]:+ index_2 = 2+ index_3 = 3+ else:+ index_2 = 3+ index_3 = 2++ box = [+ points[index_1], points[index_2], points[index_3], points[index_4]+ ]+ return box, min(bounding_box[1])++ def box_score_fast(self, bitmap, _box):+ h, w = bitmap.shape[:2]+ box = _box.copy()+ xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1)+ xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1)+ ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1)+ ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1)++ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)+ box[:, 0] = box[:, 0] - xmin+ box[:, 1] = box[:, 1] - ymin+ cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)+ return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]++ def __call__(self, pred, shape_list):+ pred = pred[:, 0, :, :]+ segmentation = pred > self.thresh++ boxes_batch = []+ for batch_index in range(pred.shape[0]):+ src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]+ if self.dilation_kernel is not None:+ mask = cv2.dilate(+ np.array(segmentation[batch_index]).astype(np.uint8),+ self.dilation_kernel)+ else:+ mask = segmentation[batch_index]+ boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask,+ src_w, src_h)++ boxes_batch.append({'points': boxes})+ return boxes_batchdiff --git a/python/rapidocr_openvino/ch_ppocr_v2_rec/__init__.py b/python/rapidocr_openvino/ch_ppocr_v2_rec/__init__.pynew file mode 100644index 0000000..686ffdd--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_rec/__init__.py@@ -0,0 +1 @@+from .text_recognize import TextRecognizer\ No newline at end of filediff --git a/python/rapidocr_openvino/ch_ppocr_v2_rec/config.yaml b/python/rapidocr_openvino/ch_ppocr_v2_rec/config.yamlnew file mode 100644index 0000000..3c3c9df--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_rec/config.yaml@@ -0,0 +1,5 @@+model_path: resources/models/ch_ppocr_server_v2.0_rec_infer.onnx++rec_img_shape: [3, 32, 320]+rec_batch_num: 6+keys_path: resources/rec_dict/ppocr_keys_v1.txtdiff --git a/python/rapidocr_openvino/ch_ppocr_v2_rec/text_recognize.py b/python/rapidocr_openvino/ch_ppocr_v2_rec/text_recognize.pynew file mode 100644index 0000000..f62b91a--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_rec/text_recognize.py@@ -0,0 +1,119 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import argparse+import math+import time+from pathlib import Path+from typing import List++import cv2+import numpy as np+from openvino.runtime import Core++try:+ from .utils import CTCLabelDecode, read_yaml+except:+ from utils import CTCLabelDecode, read_yaml+++class TextRecognizer(object):+ def __init__(self, config):+ self.rec_image_shape = config['rec_img_shape']+ self.rec_batch_num = config['rec_batch_num']+ self.character_dict_path = config['keys_path']+ self.postprocess_op = CTCLabelDecode(self.character_dict_path)++ ie = Core()+ model_onnx = ie.read_model(config['model_path'])+ compile_model = ie.compile_model(model=model_onnx, device_name='CPU')+ self.session = compile_model.create_infer_request()++ def resize_norm_img(self, img, max_wh_ratio):+ img_channel, img_height, img_width = self.rec_image_shape+ assert img_channel == img.shape[2]++ img_width = int((32 * max_wh_ratio))+ max_wh_ratio = 1++ h, w = img.shape[:2]+ ratio = w / float(h)+ if math.ceil(img_height * ratio) > img_width:+ resized_w = img_width+ else:+ resized_w = int(math.ceil(img_height * ratio))++ resized_image = cv2.resize(img, (resized_w, img_height))+ resized_image = resized_image.astype('float32')+ resized_image = resized_image.transpose((2, 0, 1)) / 255+ resized_image -= 0.5+ resized_image /= 0.5++ padding_im = np.zeros((img_channel, img_height, img_width),+ dtype=np.float32)+ padding_im[:, :, 0: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]++ # Calculate the aspect ratio of all text bars+ width_list = [img.shape[1] / float(img.shape[0]) for img in img_list]++ # Sorting can speed up the recognition process+ indices = np.argsort(np.array(width_list))++ img_num = len(img_list)+ rec_res = [['', 0.0]] * img_num++ batch_num = self.rec_batch_num+ elapse = 0+ for beg_img_no in range(0, img_num, batch_num):+ end_img_no = min(img_num, beg_img_no + batch_num)+ max_wh_ratio = 0+ for ino in range(beg_img_no, end_img_no):+ h, w = img_list[indices[ino]].shape[0:2]+ wh_ratio = w * 1.0 / h+ max_wh_ratio = max(max_wh_ratio, wh_ratio)++ norm_img_batch = []+ for ino in range(beg_img_no, end_img_no):+ norm_img = self.resize_norm_img(img_list[indices[ino]],+ max_wh_ratio)+ norm_img_batch.append(norm_img[np.newaxis, :])+ norm_img_batch = np.concatenate(norm_img_batch).astype(np.float32)++ starttime = time.time()+ self.session.infer(inputs=[norm_img_batch])+ preds = self.session.get_output_tensor().data++ rec_result = self.postprocess_op(preds)+ for rno in range(len(rec_result)):+ rec_res[indices[beg_img_no + rno]] = rec_result[rno]+ elapse += time.time() - starttime+ return rec_res, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('--image_path', type=str, help='image_dir|image_path')+ parser.add_argument('--config_path', type=str, default='config.yaml')+ args = parser.parse_args()++ config = read_yaml(args.config_path)+ text_recognizer = TextRecognizer(config)++ img = cv2.imread(args.image_path)+ rec_res, predict_time = text_recognizer(img)+ print(f'识别结果: {rec_res}\t cost: {predict_time}s')diff --git a/python/rapidocr_openvino/ch_ppocr_v2_rec/utils.py b/python/rapidocr_openvino/ch_ppocr_v2_rec/utils.pynew file mode 100644index 0000000..c6edeb6--- /dev/null+++ b/python/rapidocr_openvino/ch_ppocr_v2_rec/utils.py@@ -0,0 +1,79 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import numpy as np+import yaml+++def read_yaml(yaml_path):+ with open(yaml_path, 'rb') as f:+ data = yaml.load(f, Loader=yaml.Loader)+ return data+++class CTCLabelDecode(object):+ """ Convert between text-label and text-index """++ def __init__(self, character_dict_path):+ super(CTCLabelDecode, self).__init__()++ self.character_str = []+ assert character_dict_path is not None, "character_dict_path should not be None"+ with open(character_dict_path, "rb") as fin:+ lines = fin.readlines()+ for line in lines:+ line = line.decode('utf-8').strip("\n").strip("\r\n")+ self.character_str.append(line)+ self.character_str.append(' ')++ dict_character = self.add_special_char(self.character_str)+ self.character = dict_character++ self.dict = {}+ for i, char in enumerate(dict_character):+ self.dict[char] = i++ def __call__(self, preds, label=None):+ preds_idx = preds.argmax(axis=2)+ preds_prob = preds.max(axis=2)+ text = self.decode(preds_idx, preds_prob,+ is_remove_duplicate=True)+ if label is None:+ return text+ label = self.decode(label)+ return text, label++ def add_special_char(self, dict_character):+ dict_character = ['blank'] + dict_character+ return dict_character++ def get_ignored_tokens(self):+ return [0] # for ctc blank++ def decode(self, text_index, text_prob=None, is_remove_duplicate=False):+ """ convert text-index into text-label. """++ result_list = []+ ignored_tokens = self.get_ignored_tokens()+ batch_size = len(text_index)+ for batch_idx in range(batch_size):+ char_list = []+ conf_list = []+ for idx in range(len(text_index[batch_idx])):+ if text_index[batch_idx][idx] in ignored_tokens:+ continue+ if is_remove_duplicate:+ # only for predict+ if idx > 0 and text_index[batch_idx][idx - 1] == text_index[+ batch_idx][idx]:+ continue+ char_list.append(self.character[int(text_index[batch_idx][+ idx])])+ if text_prob is not None:+ conf_list.append(text_prob[batch_idx][idx])+ else:+ conf_list.append(1)+ text = ''.join(char_list)+ result_list.append((text, np.mean(conf_list)))+ return result_list+diff --git a/python/rapidocr_openvino/ch_ppocr_v2_rec/word_1.jpg b/python/rapidocr_openvino/ch_ppocr_v2_rec/word_1.jpgnew file mode 100644index 0000000..934cc1cBinary files /dev/null and b/python/rapidocr_openvino/ch_ppocr_v2_rec/word_1.jpg differdiff --git a/python/rapidocr_openvino/rapid_ocr_api.py b/python/rapidocr_openvino/rapid_ocr_api.pynew file mode 100644index 0000000..59647db--- /dev/null+++ b/python/rapidocr_openvino/rapid_ocr_api.py@@ -0,0 +1,143 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+import copy+import importlib+import sys+from pathlib import Path++import cv2+import numpy as np+import yaml++root_dir = Path(__file__).resolve().parent+sys.path.append(str(root_dir))+++class TextSystem(object):+ def __init__(self, config_path=str(root_dir / 'config.yaml')):+ super(TextSystem).__init__()+ config = self.read_yaml(config_path)++ self.print_verbose = config['Global']['print_verbose']+ self.text_score = config['Global']['text_score']++ TextDetector = self.init_module(config['Det']['module_name'],+ config['Det']['class_name'])+ self.text_detector = TextDetector(config['Det'])++ TextRecognizer = self.init_module(config['Rec']['module_name'],+ config['Rec']['class_name'])+ self.text_recognizer = TextRecognizer(config['Rec'])++ self.use_angle_cls = config['Global']['use_angle_cls']+ if self.use_angle_cls:+ TextClassifier = self.init_module(config['Cls']['module_name'],+ config['Cls']['class_name'])+ self.text_cls = TextClassifier(config['Cls'])++ @staticmethod+ def read_yaml(yaml_path):+ with open(yaml_path, 'rb') as f:+ data = yaml.load(f, Loader=yaml.Loader)+ return data++ @staticmethod+ def init_module(module_name, class_name):+ module_part = importlib.import_module(module_name)+ return getattr(module_part, class_name)++ def get_rotate_crop_image(self, img, points):+ '''+ img_height, img_width = img.shape[0:2]+ left = int(np.min(points[:, 0]))+ right = int(np.max(points[:, 0]))+ top = int(np.min(points[:, 1]))+ bottom = int(np.max(points[:, 1]))+ img_crop = img[top:bottom, left:right, :].copy()+ points[:, 0] = points[:, 0] - left+ points[:, 1] = points[:, 1] - top+ '''+ img_crop_width = int(+ max(+ np.linalg.norm(points[0] - points[1]),+ np.linalg.norm(points[2] - points[3])))+ img_crop_height = int(+ max(+ np.linalg.norm(points[0] - points[3]),+ np.linalg.norm(points[1] - points[2])))+ pts_std = np.float32([[0, 0], [img_crop_width, 0],+ [img_crop_width, img_crop_height],+ [0, img_crop_height]])+ M = cv2.getPerspectiveTransform(points, pts_std)+ dst_img = cv2.warpPerspective(+ img,+ M, (img_crop_width, img_crop_height),+ borderMode=cv2.BORDER_REPLICATE,+ flags=cv2.INTER_CUBIC)+ dst_img_height, dst_img_width = dst_img.shape[0:2]+ if dst_img_height * 1.0 / dst_img_width >= 1.5:+ dst_img = np.rot90(dst_img)+ return dst_img++ @staticmethod+ def sorted_boxes(dt_boxes):+ """+ Sort text boxes in order from top to bottom, left to right+ args:+ dt_boxes(array):detected text boxes with shape [4, 2]+ return:+ sorted boxes(array) with shape [4, 2]+ """+ num_boxes = dt_boxes.shape[0]+ sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))+ _boxes = list(sorted_boxes)++ for i in range(num_boxes - 1):+ if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \+ (_boxes[i + 1][0][0] < _boxes[i][0][0]):+ tmp = _boxes[i]+ _boxes[i] = _boxes[i + 1]+ _boxes[i + 1] = tmp+ return _boxes++ def __call__(self, img: np.ndarray):+ dt_boxes, elapse = self.text_detector(img)+ if self.print_verbose:+ print(f'dt_boxes num: { len(dt_boxes)}, elapse: {elapse}')++ if dt_boxes is None or len(dt_boxes) < 1:+ return None, None+ dt_boxes = self.sorted_boxes(dt_boxes)++ img_crop_list = []+ for bno in range(len(dt_boxes)):+ tmp_box = copy.deepcopy(dt_boxes[bno])+ img_crop = self.get_rotate_crop_image(img, tmp_box)+ img_crop_list.append(img_crop)++ if self.use_angle_cls:+ img_crop_list, angle_list, elapse = self.text_cls(img_crop_list)+ if self.print_verbose:+ print(f'cls num: {len(img_crop_list)}, elapse: {elapse}')++ rec_res, elapse = self.text_recognizer(img_crop_list)+ if self.print_verbose:+ print(f'rec_res num: {len(rec_res)}, elapse: {elapse}')++ filter_boxes, filter_rec_res = [], []+ for box, rec_reuslt in zip(dt_boxes, rec_res):+ text, score = rec_reuslt+ if score >= self.text_score:+ filter_boxes.append(box)+ filter_rec_res.append(rec_reuslt)+ return filter_boxes, filter_rec_res+++if __name__ == '__main__':+ text_sys = TextSystem('config.yaml')++ import cv2+ img = cv2.imread('resources/test_images/det_images/ch_en_num.jpg')++ result = text_sys(img)+ print(result)diff --git a/python/requirements.txt b/python/requirements.txtindex 95ebc08..fb2231c 100644--- a/python/requirements.txt+++ b/python/requirements.txt@@ -1,6 +1,5 @@pyclipper>=1.2.0Shapely>=1.7.1-onnxruntime>=1.7.0opencv_python==4.5.1.48six>=1.15.0numpy>=1.19.2diff --git a/python/test_demo.py b/python/test_demo.pyindex be86d50..64177a8 100644--- a/python/test_demo.py+++ b/python/test_demo.py@@ -9,7 +9,8 @@ import cv2import numpy as npfrom PIL import Image, ImageDraw, ImageFont-from rapidocr_onnxruntime import TextSystem+# from rapidocr_onnxruntime import TextSystem+from rapidocr_openvino import TextSystemdef draw_ocr_box_txt(image, boxes, txts, font_path,