Skip to content

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

Add processing logic for single line text.

SWHLd82132f5108c
diff --git a/README.md b/README.md
index 1e69b4d..7e15bc9 100755
--- a/README.md
+++ b/README.md
@@ -23,12 +23,12 @@
- [RapidOCR (捷智OCR)](#rapidocr-捷智ocr)
- [简介](#简介)
- [近期更新(more)](#近期更新more)
+ - [😁2022-07-05 update:](#2022-07-05-update)
- [🏝2022-06-30 update:](#2022-06-30-update)
- [📌2022-06-25 update:](#2022-06-25-update)
- [🥟2022-05-25 update](#2022-05-25-update)
- [🍿2022-05-15 update](#2022-05-15-update)
- [😀2022-05-12 upadte](#2022-05-12-upadte)
- - [🎧2022-04-04 update](#2022-04-04-update)
- [整个框架](#整个框架)
- [常见问题 FAQ](#常见问题--faq)
- [SDK 编译状态](#sdk-编译状态)
@@ -62,6 +62,11 @@
- 基于百度的开源PaddleOCR 模型及训练,任何人可以使用本推理库,也可以根据自己的需求使用百度的paddlepaddle框架进行模型优化。
## 近期更新([more](./docs/change_log.md))
+
+#### 😁2022-07-05 update:
+- 添加对单行文本的处理能力,对于单行文本,可自行设定阈值,不过检测模块,直接识别即可。详情参见[README](./python/README.md#configyamlconfigyaml中常用参数介绍)
+- 优化python部分代码逻辑,更优雅简洁。
+
#### 🏝2022-06-30 update:
- python推理部分,增加参数选择使用GPU推理的配置选项,在正确安装`onnxruntime-gpu`版本前提下,可以一键使用(Fix [issue#30](https://github.com/RapidAI/RapidOCR/issues/30))
- 具体基于GPU的推理情况,需要等我后续整理一下,再更新出来
@@ -82,11 +87,6 @@
- 增加PaddleOCR v3 det模型转换的ONNX模型,直接去网盘下载,替换即可。([百度网盘](https://pan.baidu.com/s/1mkirNltJS481In4g81jP3w?pwd=zy37) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing))
- 增加各个版本文本检测模型效果对比表格,详情点击[各个版本ONNX模型效果对比](#各个版本onnx模型效果对比)。v3的文本检测模型从自己构建测试集上的指标来看是好于之前的v2的,推荐使用。
-#### 🎧2022-04-04 update
-- 增加python下的基于OpenVINO推理引擎的支持
-- 给出OpenVINO和ONNXRuntime的性能对比表格,详情参见:[python/rapidocr_openvino/README](./python/rapidocr_openvino/README.md)
-
-
## 整个框架
<div align="center">
<img src="./assets/RapidOCR_system.jpg">
diff --git a/docs/README_en.md b/docs/README_en.md
index 09c3bbf..b2471f9 100644
--- a/docs/README_en.md
+++ b/docs/README_en.md
@@ -22,11 +22,11 @@
- [RapidOCR](#rapidocr)
- [Introduction](#introduction)
- [Recently updates(more)](#recently-updatesmore)
+ - [😁2022-07-05 update:](#2022-07-05-update)
- [🏝2022-06-30 update:](#2022-06-30-update)
- [📌2022-06-25 update:](#2022-06-25-update)
- [🍿2022-05-15 update](#2022-05-15-update)
- [😀2022-05-12 upadte](#2022-05-12-upadte)
- - [🎧2022-04-04 update](#2022-04-04-update)
- [FAQ](#faq)
- [SDK compilation status](#sdk-compilation-status)
- [Online demo](#online-demo)
@@ -60,6 +60,10 @@
- Based on Baidu's open source PaddleOCR model and training, anyone can use this inference library, or use Baidu's paddlepaddle framework for model optimization according to their own needs.
## Recently updates([more](./change_log_en.md))
+#### 😁2022-07-05 update:
+- Add the ability to handle single line text, for single line text, you can set your own threshold, but the detection module, direct recognition can be. For details, see [README](./python/README.md#configyamlconfigyaml中常用参数介绍)
+- Optimize some code logic of python, more elegant and concise.
+
#### 🏝2022-06-30 update:
- In the python inference section, add a configuration option for whether to use GPU inference, which can be used with one click if the `onnxruntime-gpu` version is correctly installed (Fix [issue#30](https://github.com/RapidAI/RapidOCR/issues/30))
- The specific GPU-based reasoning will need to wait for me to sort it out and update it later.
@@ -77,10 +81,6 @@
- Add the ONNX model converted from the PaddleOCR v3 det model, download it directly from the network disk, and replace it. ([Baidu Netdisk](https://pan.baidu.com/s/1mkirNltJS481In4g81jP3w?pwd=zy37) | [Google Drive](https://drive.google.com/drive/folders/1x_a9KpCo_1blxH1xFOfgKVkw1HYRVywY?usp=sharing ))
- Added a comparison table of text detection model effects of various versions. For details, click [Comparison of the effects of various versions of ONNX models] (#Comparison of the effects of various versions of onnx models). The text detection model of v3 is better than the previous v2 in terms of the indicators on the test set constructed by itself, and it is recommended to use it.
-#### 🎧2022-04-04 update
-- Add suport for OpenVINO under python
-- Give the performance comparison table of OpenVINO and ONNXRuntime
-- For details:[python/README](./python/README.md)
## [FAQ](./doc/FAQ.md)
diff --git a/docs/change_log.md b/docs/change_log.md
index e30bb99..dc32aff 100644
--- a/docs/change_log.md
+++ b/docs/change_log.md
@@ -1,3 +1,7 @@
+#### 😁2022-07-05 update:
+- 添加对单行文本的处理能力,对于单行文本,可自行设定阈值,不过检测模块,直接识别即可。详情参见[README](./python/README.md#configyamlconfigyaml中常用参数介绍)
+- 优化python部分代码逻辑,更优雅简洁。
+
#### 🏝2022-06-30 update:
- python推理部分,增加参数选择使用GPU推理的配置选项,在正确安装`onnxruntime-gpu`版本前提下,可以一键使用(Fix [issue#30](https://github.com/RapidAI/RapidOCR/issues/30))
- 具体基于GPU的推理情况,需要等我后续整理一下,再更新出来
diff --git a/docs/change_log_en.md b/docs/change_log_en.md
index b44b52c..3babaf7 100644
--- a/docs/change_log_en.md
+++ b/docs/change_log_en.md
@@ -1,3 +1,7 @@
+#### 😁2022-07-05 update:
+- Add the ability to handle single line text, for single line text, you can set your own threshold, but the detection module, direct recognition can be. For details, see [README](./python/README.md#configyamlconfigyaml中常用参数介绍)
+- Optimize some code logic of python, more elegant and concise.
+
#### 🏝2022-06-30 update:
- In the python inference section, add a configuration option for whether to use GPU inference, which can be used with one click if the `onnxruntime-gpu` version is correctly installed (Fix [issue#30](https://github.com/RapidAI/RapidOCR/issues/30))
- The specific GPU-based reasoning will need to wait for me to sort it out and update it later.
diff --git a/ocrweb/config.yaml b/ocrweb/config.yaml
index d0e711f..19ef378 100644
--- a/ocrweb/config.yaml
+++ b/ocrweb/config.yaml
@@ -2,12 +2,22 @@ Global:
text_score: 0.5
use_angle_cls: true
print_verbose: true
+ min_height: 50
+ width_height_ratio: 8
Det:
module_name: ch_ppocr_v2_det
class_name: TextDetector
model_path: resources/models/ch_PP-OCRv3_det_infer.onnx
+ use_cuda: false
+ # Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html
+ CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
pre_process:
DetResizeForTest:
limit_side_len: 736
@@ -33,6 +43,13 @@ Cls:
class_name: TextClassifier
model_path: resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx
+ use_cuda: false
+ CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
cls_image_shape: [3, 48, 192]
cls_batch_num: 6
cls_thresh: 0.9
@@ -43,6 +60,13 @@ Rec:
class_name: TextRecognizer
model_path: resources/models/ch_ppocr_mobile_v2.0_rec_infer.onnx
+ use_cuda: false
+ CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
rec_img_shape: [3, 32, 320]
rec_batch_num: 6
keys_path: resources/rec_dict/ppocr_keys_v1.txt
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/config.yaml b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/config.yaml
index e6fa00e..89497ae 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/config.yaml
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/config.yaml
@@ -1,5 +1,14 @@
model_path: resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx
+use_cuda: false
+# Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html
+CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ gpu_mem_limit: 2 * 1024 * 1024 * 1024
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
cls_image_shape: [3, 48, 192]
cls_batch_num: 6
cls_thresh: 0.9
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py
index fc06ac1..38d8549 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/text_cls.py
@@ -22,9 +22,9 @@ import numpy as np
import onnxruntime as ort
try:
- from .utils import ClsPostProcess, read_yaml
+ from .utils import ClsPostProcess, read_yaml, OrtInferSession
except:
- from utils import ClsPostProcess, read_yaml
+ from utils import ClsPostProcess, read_yaml, OrtInferSession
class TextClassifier(object):
@@ -34,11 +34,9 @@ class TextClassifier(object):
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
+ session_instance = OrtInferSession(config)
+ self.session = session_instance.session
+ self.input_name = session_instance.get_input_name()
def resize_norm_img(self, img):
img_c, img_h, img_w = self.cls_image_shape
@@ -63,7 +61,6 @@ class TextClassifier(object):
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]
@@ -123,4 +120,4 @@ if __name__ == "__main__":
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]}")
+ print(f"cls result:{cls_res[ino]}")
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/utils.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/utils.py
index dae9175..8ee0fa5 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/utils.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_cls/utils.py
@@ -11,7 +11,44 @@
# 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 warnings
+
import yaml
+from onnxruntime import (get_available_providers, get_device,
+ SessionOptions, InferenceSession)
+
+
+class OrtInferSession(object):
+ def __init__(self, config):
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+
+ cuda_ep = 'CUDAExecutionProvider'
+ cpu_ep = 'CPUExecutionProvider'
+
+ EP_list = []
+ if config['use_cuda'] and get_device() == 'GPU' \
+ and cuda_ep in get_available_providers():
+ EP_list = [(cuda_ep, config[cuda_ep])]
+ EP_list.append(cpu_ep)
+
+ self.session = InferenceSession(config['model_path'],
+ sess_options=sess_opt,
+ providers=EP_list)
+
+ if config['use_cuda'] and cuda_ep not in self.session.get_providers():
+ warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
+ 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
+ 'you can check their relations from the offical web site: '
+ 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
+ RuntimeWarning)
+
+ def get_input_name(self, input_idx=0):
+ return self.session.get_inputs()[input_idx].name
+
+ def get_output_name(self, output_idx=0):
+ return self.session.get_outputs()[output_idx].name
def read_yaml(yaml_path):
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml
index 0f08b09..428ccfc 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/config.yaml
@@ -1,4 +1,13 @@
-model_path: resources/models/ch_ppocr_server_v2.0_det_infer.onnx
+model_path: G:\ProgramFiles\_self\RapidOCR\python\resources\models\ch_PP-OCRv2_det_infer.onnx
+
+use_cuda: false
+# Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html
+CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ gpu_mem_limit: 2 * 1024 * 1024 * 1024
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
pre_process:
DetResizeForTest:
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
index 30af2e3..19b6b31 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
@@ -12,19 +12,21 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
import argparse
import time
import cv2
import numpy as np
-import onnxruntime
+
try:
from .utils import (DBPostProcess, create_operators,
- draw_text_det_res, transform, read_yaml)
+ draw_text_det_res, transform, read_yaml, OrtInferSession)
except:
from utils import (DBPostProcess, create_operators,
- draw_text_det_res, transform, read_yaml)
+ draw_text_det_res, transform, read_yaml, OrtInferSession)
class TextDetector(object):
@@ -32,18 +34,40 @@ class TextDetector(object):
self.preprocess_op = create_operators(config['pre_process'])
self.postprocess_op = DBPostProcess(**config['post_process'])
- sess_opt = onnxruntime.SessionOptions()
- sess_opt.log_severity_level = 4
- sess_opt.enable_cpu_mem_arena = False
- self.session = onnxruntime.InferenceSession(config['model_path'],
- sess_opt)
- self.input_name = self.session.get_inputs()[0].name
- self.output_name = self.session.get_outputs()[0].name
+ session_instance = OrtInferSession(config)
+ self.session = session_instance.session
+ self.input_name = session_instance.get_input_name()
+
+ def __call__(self, img):
+ if img is None:
+ raise ValueError('img is None')
+
+ ori_im_shape = img.shape[:2]
+
+ 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()
+ preds = self.session.run(None, {self.input_name: img})
+
+ post_result = self.postprocess_op(preds[0], 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
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
+ 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]), :]
@@ -84,28 +108,6 @@ class TextDetector(object):
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()
- preds = self.session.run([self.output_name],
- {self.input_name: img})
-
- post_result = self.postprocess_op(preds[0], 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()
@@ -121,4 +123,4 @@ if __name__ == "__main__":
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了')
+ print('The det_results.jpg has been saved in the current directory.')
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/utils.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/utils.py
index ffbd17f..674ed8b 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/utils.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_det/utils.py
@@ -13,19 +13,53 @@
# 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
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
import sys
+import warnings
import cv2
import numpy as np
import pyclipper
import six
-from shapely.geometry import Polygon
import yaml
+from shapely.geometry import Polygon
+from onnxruntime import (get_available_providers, get_device,
+ SessionOptions, InferenceSession)
+
+
+class OrtInferSession(object):
+ def __init__(self, config):
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+
+ cuda_ep = 'CUDAExecutionProvider'
+ cpu_ep = 'CPUExecutionProvider'
+
+ EP_list = []
+ if config['use_cuda'] and get_device() == 'GPU' \
+ and cuda_ep in get_available_providers():
+ EP_list = [(cuda_ep, config[cuda_ep])]
+ EP_list.append(cpu_ep)
+
+ self.session = InferenceSession(config['model_path'],
+ sess_options=sess_opt,
+ providers=EP_list)
+
+ if config['use_cuda'] and cuda_ep not in self.session.get_providers():
+ warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
+ 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
+ 'you can check their relations from the offical web site: '
+ 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
+ RuntimeWarning)
+
+ def get_input_name(self, input_idx=0):
+ return self.session.get_inputs()[input_idx].name
+
+ def get_output_name(self, output_idx=0):
+ return self.session.get_outputs()[output_idx].name
def read_yaml(yaml_path):
@@ -227,6 +261,7 @@ def transform(data, ops=None):
""" transform """
if ops is None:
ops = []
+
for op in ops:
data = op(data)
if data is None:
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/config.yaml b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/config.yaml
index 3c3c9df..ffcfc1d 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/config.yaml
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/config.yaml
@@ -1,5 +1,14 @@
model_path: resources/models/ch_ppocr_server_v2.0_rec_infer.onnx
+use_cuda: false
+# Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html
+CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ gpu_mem_limit: 2 * 1024 * 1024 * 1024
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
rec_img_shape: [3, 32, 320]
rec_batch_num: 6
keys_path: resources/rec_dict/ppocr_keys_v1.txt
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py
index 2753ea7..4fd9265 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/text_recognize.py
@@ -14,17 +14,15 @@
import argparse
import math
import time
-from pathlib import Path
from typing import List
import cv2
import numpy as np
-import onnxruntime
try:
- from .utils import CTCLabelDecode, read_yaml
+ from .utils import CTCLabelDecode, read_yaml, OrtInferSession
except:
- from utils import CTCLabelDecode, read_yaml
+ from utils import CTCLabelDecode, read_yaml, OrtInferSession
class TextRecognizer(object):
@@ -34,12 +32,9 @@ class TextRecognizer(object):
self.character_dict_path = config['keys_path']
self.postprocess_op = CTCLabelDecode(self.character_dict_path)
- sess_opt = onnxruntime.SessionOptions()
- sess_opt.log_severity_level = 4
- sess_opt.enable_cpu_mem_arena = False
- self.session = onnxruntime.InferenceSession(config['model_path'],
- sess_opt)
- self.input_name = self.session.get_inputs()[0].name
+ session_instance = OrtInferSession(config)
+ self.session = session_instance.session
+ self.input_name = session_instance.get_input_name()
def resize_norm_img(self, img, max_wh_ratio):
img_channel, img_height, img_width = self.rec_image_shape
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/utils.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/utils.py
index c6edeb6..a0dbf8d 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/utils.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/utils.py
@@ -1,8 +1,46 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
+import warnings
+
import numpy as np
import yaml
+from onnxruntime import (get_available_providers, get_device,
+ SessionOptions, InferenceSession)
+
+
+class OrtInferSession(object):
+ def __init__(self, config):
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+
+ cuda_ep = 'CUDAExecutionProvider'
+ cpu_ep = 'CPUExecutionProvider'
+
+ EP_list = []
+ if config['use_cuda'] and get_device() == 'GPU' \
+ and cuda_ep in get_available_providers():
+ EP_list = [(cuda_ep, config[cuda_ep])]
+
+ EP_list.append(cpu_ep)
+
+ self.session = InferenceSession(config['model_path'],
+ sess_options=sess_opt,
+ providers=EP_list)
+
+ if config['use_cuda'] and cuda_ep not in self.session.get_providers():
+ warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
+ 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
+ 'you can check their relations from the offical web site: '
+ 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
+ RuntimeWarning)
+
+ def get_input_name(self, input_idx=0):
+ return self.session.get_inputs()[input_idx].name
+
+ def get_output_name(self, output_idx=0):
+ return self.session.get_outputs()[output_idx].name
def read_yaml(yaml_path):
@@ -76,4 +114,3 @@ class CTCLabelDecode(object):
text = ''.join(char_list)
result_list.append((text, np.mean(conf_list)))
return result_list
-
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/word_1.jpg b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/word_1.jpg
deleted file mode 100644
index 934cc1c..0000000
Binary files a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v2_rec/word_1.jpg and /dev/null differ
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/config.yaml b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/config.yaml
index 4f903d6..2428429 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/config.yaml
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/config.yaml
@@ -1,5 +1,14 @@
model_path: resources/models/PPOCRv3/ch_PP-OCRv3_rec_infer.onnx
+use_cuda: false
+# Details of the params: https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html
+CUDAExecutionProvider:
+ device_id: 0
+ arena_extend_strategy: kNextPowerOfTwo
+ gpu_mem_limit: 2 * 1024 * 1024 * 1024
+ cudnn_conv_algo_search: EXHAUSTIVE
+ do_copy_in_default_stream: true
+
rec_img_shape: [3, 48, 320]
rec_batch_num: 6
keys_path: resources/rec_dict/ppocr_keys_v1.txt
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/text_recognize.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/text_recognize.py
index ca88ce5..b00bf95 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/text_recognize.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/text_recognize.py
@@ -22,9 +22,9 @@ import numpy as np
import onnxruntime
try:
- from .utils import CTCLabelDecode, read_yaml
+ from .utils import CTCLabelDecode, read_yaml, OrtInferSession
except:
- from utils import CTCLabelDecode, read_yaml
+ from utils import CTCLabelDecode, read_yaml, OrtInferSession
root_path = Path(__file__).parent
@@ -36,12 +36,9 @@ class TextRecognizer(object):
self.character_dict_path = config['keys_path']
self.postprocess_op = CTCLabelDecode(self.character_dict_path)
- sess_opt = onnxruntime.SessionOptions()
- sess_opt.log_severity_level = 4
- sess_opt.enable_cpu_mem_arena = False
- self.session = onnxruntime.InferenceSession(config['model_path'],
- sess_opt)
- self.input_name = self.session.get_inputs()[0].name
+ session_instance = OrtInferSession(config)
+ self.session = session_instance.session
+ self.input_name = session_instance.get_input_name()
def resize_norm_img(self, img, max_wh_ratio):
img_channel, img_height, img_width = self.rec_image_shape
diff --git a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/utils.py b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/utils.py
index c6edeb6..9e0d436 100644
--- a/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/utils.py
+++ b/ocrweb/rapidocr_onnxruntime/ch_ppocr_v3_rec/utils.py
@@ -1,8 +1,45 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
+import warnings
+
import numpy as np
import yaml
+from onnxruntime import (InferenceSession, SessionOptions,
+ get_available_providers, get_device)
+
+
+class OrtInferSession(object):
+ def __init__(self, config):
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+
+ cuda_ep = 'CUDAExecutionProvider'
+ cpu_ep = 'CPUExecutionProvider'
+
+ EP_list = []
+ if config['use_cuda'] and get_device() == 'GPU' \
+ and cuda_ep in get_available_providers():
+ EP_list = [(cuda_ep, config[cuda_ep])]
+ EP_list.append(cpu_ep)
+
+ self.session = InferenceSession(config['model_path'],
+ sess_options=sess_opt,
+ providers=EP_list)
+
+ if config['use_cuda'] and cuda_ep not in self.session.get_providers():
+ warnings.warn(f'{cuda_ep} is not avaiable for current env, the inference part is automatically shifted to be executed under {cpu_ep}.\n'
+ 'Please ensure the installed onnxruntime-gpu version matches your cuda and cudnn version, '
+ 'you can check their relations from the offical web site: '
+ 'https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html',
+ RuntimeWarning)
+
+ def get_input_name(self, input_idx=0):
+ return self.session.get_inputs()[input_idx].name
+
+ def get_output_name(self, output_idx=0):
+ return self.session.get_outputs()[output_idx].name
def read_yaml(yaml_path):
@@ -76,4 +113,3 @@ class CTCLabelDecode(object):
text = ''.join(char_list)
result_list.append((text, np.mean(conf_list)))
return result_list
-
diff --git a/ocrweb/rapidocr_onnxruntime/rapid_ocr_api.py b/ocrweb/rapidocr_onnxruntime/rapid_ocr_api.py
index 48c8018..35f994f 100644
--- a/ocrweb/rapidocr_onnxruntime/rapid_ocr_api.py
+++ b/ocrweb/rapidocr_onnxruntime/rapid_ocr_api.py
@@ -1,9 +1,7 @@
+# !/usr/bin/env python
# -*- encoding: utf-8 -*-
-# @Author: SWHL
-# @Contact: [email protected]
import copy
import importlib
-import time
import sys
from pathlib import Path
@@ -20,8 +18,11 @@ class TextSystem(object):
super(TextSystem).__init__()
config = self.read_yaml(config_path)
- self.print_verbose = config['Global']['print_verbose']
- self.text_score = config['Global']['text_score']
+ global_config = config['Global']
+ self.print_verbose = global_config['print_verbose']
+ self.text_score = global_config['text_score']
+ self.min_height = global_config['min_height']
+ self.width_height_ratio = global_config['width_height_ratio']
TextDetector = self.init_module(config['Det']['module_name'],
config['Det']['class_name'])
@@ -37,6 +38,33 @@ class TextSystem(object):
config['Cls']['class_name'])
self.text_cls = TextClassifier(config['Cls'])
+ def __call__(self, img: np.ndarray):
+ h, w = img.shape[:2]
+ if h < self.min_height and w / h >= self.width_height_ratio:
+ dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
+ else:
+ dt_boxes, elapse = self.text_detector(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, None
+ if self.print_verbose:
+ print(f'dt_boxes num: {len(dt_boxes)}, elapse: {elapse}')
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ img_crop_list = self.get_crop_img_list(img, dt_boxes)
+
+ 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 = self.filter_boxes_rec_by_score(dt_boxes,
+ rec_res)
+ return filter_boxes, filter_rec_res
+
@staticmethod
def read_yaml(yaml_path):
with open(yaml_path, 'rb') as f:
@@ -48,38 +76,43 @@ class TextSystem(object):
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
+ def get_boxes_img_without_det(self, img, h, w):
+ x0, y0, x1, y1 = 0, 0, w, h
+ dt_boxes = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
+ dt_boxes = dt_boxes[np.newaxis, ...]
+ img_crop_list = [img]
+ return dt_boxes, img_crop_list
+
+ def get_crop_img_list(self, img, dt_boxes):
+ def get_rotate_crop_image(img, points):
+ 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
+
+ img_crop_list = []
+ for box in dt_boxes:
+ tmp_box = copy.deepcopy(box)
+ img_crop = get_rotate_crop_image(img, tmp_box)
+ img_crop_list.append(img_crop)
+ return img_crop_list
@staticmethod
def sorted_boxes(dt_boxes):
@@ -102,46 +135,14 @@ class TextSystem(object):
_boxes[i + 1] = tmp
return _boxes
- def __call__(self, img: np.ndarray):
- dt_boxes, det_elapse = self.text_detector(img)
- if self.print_verbose:
- print(f'dt_boxes num: { len(dt_boxes)}, elapse: {det_elapse}')
-
- if dt_boxes is None or len(dt_boxes) < 1:
- return None, None, img, None
-
- start_time = time.time()
- img_crop_list = []
- dt_boxes = self.sorted_boxes(dt_boxes)
- 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)
- crop_elapse = time.time() - start_time
-
- if self.use_angle_cls:
- img_crop_list, _, cls_elapse = self.text_cls(img_crop_list)
- if self.print_verbose:
- print(f'cls num: {len(img_crop_list)}, elapse: {cls_elapse}')
-
- rec_res, rec_elapse = self.text_recognizer(img_crop_list)
- if self.print_verbose:
- print(f'rec_res num: {len(rec_res)}, elapse: {rec_elapse}')
-
- start_time = time.time()
+ def filter_boxes_rec_by_score(self, dt_boxes, rec_res):
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)
-
- filter_elapse = time.time() - start_time
- elapse_part = [f'{det_elapse:.4f}',
- f'{(cls_elapse+crop_elapse):.4f}',
- f'{(rec_elapse+filter_elapse):.4f}'
- ]
- return filter_boxes, filter_rec_res, img, elapse_part
+ return filter_boxes, filter_rec_res
if __name__ == '__main__':
diff --git a/python/README.md b/python/README.md
index 09f32a7..b798665 100755
--- a/python/README.md
+++ b/python/README.md
@@ -124,12 +124,19 @@
### [`config.yaml`](./config.yaml)中常用参数介绍
-| 参数名称 | 建议取值范围 | 默认值 | 作用 |
-| :------------: | :----------: | :-----: | :----------------------------------------------:|
-| `box_thresh` | [0, 1] | 0.5 | 文本检测所得框是否保留的阈值,值越大,召回率越低 |
-| `unclip_ratio` | [1.6, 2.0] | 1.6 | 控制文本检测框的大小,值越大,检测框整体越大 |
-| `text_score` | [0, 1] | 0.5 | 文本识别结果置信度,值越大,把握越大 |
-| `use_cuda` | | `false` | 是否使用CUDA,加速推理 |
+|所在模块| 参数名称 | 取值范围 | 默认值 | 作用 |
+|:---:| :------------: | :----------: | :-----: | :----------------------------------------------:|
+|Global| `text_score` | [0, 1] | 0.5 | 文本识别结果置信度,值越大,把握越大 |
+|Global| `use_angle_cls` | `bool` | `true` | 是否使用文本行的方向分类 |
+|Global| `print_verbose` | `bool` | `true` | 是否打印各个部分耗时信息 |
+|Global| `min_heigh` | `int` | 50 | 图像高度,单位是像素 |
+|Global| `width_height_ratio` | `float` | 8.0 | 图像宽高比 |
+||||||
+|Det| `box_thresh` | [0, 1] | 0.5 | 文本检测所得框是否保留的阈值,值越大,召回率越低 |
+|Det| `unclip_ratio` | [1.6, 2.0] | 1.6 | 控制文本检测框的大小,值越大,检测框整体越大 |
+|Det/Cls/Rec| `use_cuda` | | `false` | 是否使用CUDA,加速推理 |
+- `min_height`和`width_height_ratio`这两个参数是用来卡那些只有一行文本的图像,例如下图,这类图像不会进入文本检测模块,直接进入后续过程即可。
+ ![](./test_images/single_line_text.jpg)
### onnxruntime-gpu版推理配置
diff --git a/python/config.yaml b/python/config.yaml
index 559a31f..19ef378 100644
--- a/python/config.yaml
+++ b/python/config.yaml
@@ -2,6 +2,8 @@ Global:
text_score: 0.5
use_angle_cls: true
print_verbose: true
+ min_height: 50
+ width_height_ratio: 8
Det:
module_name: ch_ppocr_v2_det
@@ -13,7 +15,6 @@ Det:
CUDAExecutionProvider:
device_id: 0
arena_extend_strategy: kNextPowerOfTwo
- # gpu_mem_limit: 2 * 1024 * 1024 * 1024
cudnn_conv_algo_search: EXHAUSTIVE
do_copy_in_default_stream: true
@@ -46,7 +47,6 @@ Cls:
CUDAExecutionProvider:
device_id: 0
arena_extend_strategy: kNextPowerOfTwo
- # gpu_mem_limit: 2 * 1024 * 1024 * 1024
cudnn_conv_algo_search: EXHAUSTIVE
do_copy_in_default_stream: true
@@ -64,7 +64,6 @@ Rec:
CUDAExecutionProvider:
device_id: 0
arena_extend_strategy: kNextPowerOfTwo
- # gpu_mem_limit: 2 * 1024 * 1024 * 1024
cudnn_conv_algo_search: EXHAUSTIVE
do_copy_in_default_stream: true
diff --git a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
index 7308253..19b6b31 100644
--- a/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
+++ b/python/rapidocr_onnxruntime/ch_ppocr_v2_det/text_detect.py
@@ -38,6 +38,31 @@ class TextDetector(object):
self.session = session_instance.session
self.input_name = session_instance.get_input_name()
+ def __call__(self, img):
+ if img is None:
+ raise ValueError('img is None')
+
+ ori_im_shape = img.shape[:2]
+
+ 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()
+ preds = self.session.run(None, {self.input_name: img})
+
+ post_result = self.postprocess_op(preds[0], 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
+
def order_points_clockwise(self, pts):
"""
reference from:
@@ -83,31 +108,6 @@ class TextDetector(object):
dt_boxes = np.array(dt_boxes_new)
return dt_boxes
- def __call__(self, img):
- if img is None:
- raise ValueError('img is None')
-
- ori_im_shape = img.shape[:2]
-
- 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()
- preds = self.session.run(None, {self.input_name: img})
-
- post_result = self.postprocess_op(preds[0], 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()
diff --git a/python/rapidocr_onnxruntime/rapid_ocr_api.py b/python/rapidocr_onnxruntime/rapid_ocr_api.py
index 59647db..35f994f 100644
--- a/python/rapidocr_onnxruntime/rapid_ocr_api.py
+++ b/python/rapidocr_onnxruntime/rapid_ocr_api.py
@@ -18,8 +18,11 @@ class TextSystem(object):
super(TextSystem).__init__()
config = self.read_yaml(config_path)
- self.print_verbose = config['Global']['print_verbose']
- self.text_score = config['Global']['text_score']
+ global_config = config['Global']
+ self.print_verbose = global_config['print_verbose']
+ self.text_score = global_config['text_score']
+ self.min_height = global_config['min_height']
+ self.width_height_ratio = global_config['width_height_ratio']
TextDetector = self.init_module(config['Det']['module_name'],
config['Det']['class_name'])
@@ -35,6 +38,33 @@ class TextSystem(object):
config['Cls']['class_name'])
self.text_cls = TextClassifier(config['Cls'])
+ def __call__(self, img: np.ndarray):
+ h, w = img.shape[:2]
+ if h < self.min_height and w / h >= self.width_height_ratio:
+ dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
+ else:
+ dt_boxes, elapse = self.text_detector(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, None
+ if self.print_verbose:
+ print(f'dt_boxes num: {len(dt_boxes)}, elapse: {elapse}')
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ img_crop_list = self.get_crop_img_list(img, dt_boxes)
+
+ 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 = self.filter_boxes_rec_by_score(dt_boxes,
+ rec_res)
+ return filter_boxes, filter_rec_res
+
@staticmethod
def read_yaml(yaml_path):
with open(yaml_path, 'rb') as f:
@@ -46,38 +76,43 @@ class TextSystem(object):
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
+ def get_boxes_img_without_det(self, img, h, w):
+ x0, y0, x1, y1 = 0, 0, w, h
+ dt_boxes = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
+ dt_boxes = dt_boxes[np.newaxis, ...]
+ img_crop_list = [img]
+ return dt_boxes, img_crop_list
+
+ def get_crop_img_list(self, img, dt_boxes):
+ def get_rotate_crop_image(img, points):
+ 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
+
+ img_crop_list = []
+ for box in dt_boxes:
+ tmp_box = copy.deepcopy(box)
+ img_crop = get_rotate_crop_image(img, tmp_box)
+ img_crop_list.append(img_crop)
+ return img_crop_list
@staticmethod
def sorted_boxes(dt_boxes):
@@ -100,30 +135,7 @@ class TextSystem(object):
_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}')
-
+ def filter_boxes_rec_by_score(self, dt_boxes, rec_res):
filter_boxes, filter_rec_res = [], []
for box, rec_reuslt in zip(dt_boxes, rec_res):
text, score = rec_reuslt
diff --git a/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py
index fc06ac1..91c5b5c 100644
--- a/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py
+++ b/python/rapidocr_openvino/ch_ppocr_v2_cls/text_cls.py
@@ -63,7 +63,6 @@ class TextClassifier(object):
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]
diff --git a/python/rapidocr_openvino/rapid_ocr_api.py b/python/rapidocr_openvino/rapid_ocr_api.py
index 59647db..35f994f 100644
--- a/python/rapidocr_openvino/rapid_ocr_api.py
+++ b/python/rapidocr_openvino/rapid_ocr_api.py
@@ -18,8 +18,11 @@ class TextSystem(object):
super(TextSystem).__init__()
config = self.read_yaml(config_path)
- self.print_verbose = config['Global']['print_verbose']
- self.text_score = config['Global']['text_score']
+ global_config = config['Global']
+ self.print_verbose = global_config['print_verbose']
+ self.text_score = global_config['text_score']
+ self.min_height = global_config['min_height']
+ self.width_height_ratio = global_config['width_height_ratio']
TextDetector = self.init_module(config['Det']['module_name'],
config['Det']['class_name'])
@@ -35,6 +38,33 @@ class TextSystem(object):
config['Cls']['class_name'])
self.text_cls = TextClassifier(config['Cls'])
+ def __call__(self, img: np.ndarray):
+ h, w = img.shape[:2]
+ if h < self.min_height and w / h >= self.width_height_ratio:
+ dt_boxes, img_crop_list = self.get_boxes_img_without_det(img, h, w)
+ else:
+ dt_boxes, elapse = self.text_detector(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, None
+ if self.print_verbose:
+ print(f'dt_boxes num: {len(dt_boxes)}, elapse: {elapse}')
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ img_crop_list = self.get_crop_img_list(img, dt_boxes)
+
+ 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 = self.filter_boxes_rec_by_score(dt_boxes,
+ rec_res)
+ return filter_boxes, filter_rec_res
+
@staticmethod
def read_yaml(yaml_path):
with open(yaml_path, 'rb') as f:
@@ -46,38 +76,43 @@ class TextSystem(object):
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
+ def get_boxes_img_without_det(self, img, h, w):
+ x0, y0, x1, y1 = 0, 0, w, h
+ dt_boxes = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
+ dt_boxes = dt_boxes[np.newaxis, ...]
+ img_crop_list = [img]
+ return dt_boxes, img_crop_list
+
+ def get_crop_img_list(self, img, dt_boxes):
+ def get_rotate_crop_image(img, points):
+ 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
+
+ img_crop_list = []
+ for box in dt_boxes:
+ tmp_box = copy.deepcopy(box)
+ img_crop = get_rotate_crop_image(img, tmp_box)
+ img_crop_list.append(img_crop)
+ return img_crop_list
@staticmethod
def sorted_boxes(dt_boxes):
@@ -100,30 +135,7 @@ class TextSystem(object):
_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}')
-
+ def filter_boxes_rec_by_score(self, dt_boxes, rec_res):
filter_boxes, filter_rec_res = [], []
for box, rec_reuslt in zip(dt_boxes, rec_res):
text, score = rec_reuslt
diff --git a/python/test_demo.py b/python/test_demo.py
index 67c10f8..d58d0bc 100644
--- a/python/test_demo.py
+++ b/python/test_demo.py
@@ -91,7 +91,7 @@ def visualize(image_path, boxes, rec_res, font_path="fonts/msyh.ttc"):
if __name__ == '__main__':
text_sys = TextSystem('config.yaml')
- image_path = r'test_images/det_images/ch_en_num.jpg'
+ image_path = r'test_images/ch_en_num.jpg'
img = cv2.imread(image_path)
dt_boxes, rec_res = text_sys(img)
print(rec_res)
diff --git a/python/test_images/det_images/ch_en_num.jpg b/python/test_images/ch_en_num.jpg
similarity index 100%
rename from python/test_images/det_images/ch_en_num.jpg
rename to python/test_images/ch_en_num.jpg
diff --git a/python/test_images/single_line_text.jpg b/python/test_images/single_line_text.jpg
new file mode 100644
index 0000000..f98cc39
Binary files /dev/null and b/python/test_images/single_line_text.jpg differ