Skip to content

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

add ch_ppocr_mobile_v2_cls

SWHL66655b8ab03b
diff --git a/python/bpocr.py b/python/bpocr.py
index 22cc455..9e17066 100755
--- a/python/bpocr.py
+++ b/python/bpocr.py
@@ -10,43 +10,14 @@ import numpy as np
from PIL import Image, ImageDraw, ImageFont
# from ch_ppocr_mobile_v1_det import TextDetector
-from ch_ppocr_mobile_v2_det_train import TextDetector
+from ch_ppocr_mobile_v2_det import TextDetector
+from ch_ppocr_mobile_v2_cls import TextClassifier
from ch_ppocr_mobile_v2_rec import TextRecognizer
font_path = r'resources\simfang.ttf'
drop_score = 0.5
-def test_text_det():
- # 单独跑文本检测模型
- det_model_path = 'models\ch_mobile_v1.1_det.onnx'
- image_path = r'test_images\det_images\1.jpg'
-
- test_detector = TextDetector(det_model_path)
-
- img, flag = check_and_read_gif(image_path)
- if not flag:
- img = cv2.imread(image_path)
- if img is None:
- raise ValueError(f"error in loading image:{image_path}")
-
- # dst_boxes: 检测到图像中的文本框坐标,ndarray格式
- # (10, 4, 2)→[10个,4个坐标,每个坐标两个点]
- dt_boxes, elapse = test_detector(img)
- print(dt_boxes.shape)
- print(elapse)
-
-
-def test_text_rec():
- # 单独跑文本识别模型
- rec_model_path = r'models\ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
- image_path = r'test_images\rec_images\2021-01-19_13-44-34.png'
- text_recongnizer = TextRecognizer(rec_model_path)
-
- rec_res, elapse = text_recongnizer(image_path)
- print(f'识别结果:{rec_res}\tcost: {elapse}s')
-
-
def check_and_read_gif(img_path):
if Path(img_path).name[-3:] in ['gif', 'GIF']:
gif = cv2.VideoCapture(img_path)
@@ -140,11 +111,16 @@ def visualize(image_path, boxes, rec_res):
class TextSystem(object):
- def __init__(self, det_model_path, rec_model_path) -> None:
+ def __init__(self, det_model_path,
+ rec_model_path,
+ use_angle_cls=False,
+ cls_model_path=None) -> None:
super(TextSystem).__init__()
self.text_detector = TextDetector(det_model_path)
self.text_recognizer = TextRecognizer(rec_model_path)
- self.use_angle_cls = False
+ self.use_angle_cls = use_angle_cls
+ if self.use_angle_cls:
+ self.text_classifier = TextClassifier(cls_model_path)
def get_rotate_crop_image(self, img, points):
'''
@@ -244,14 +220,14 @@ class TextSystem(object):
if __name__ == '__main__':
- test_text_det()
- # test_text_rec()
-
- # 文本检测+文本识别
- # det_model_path = 'models\ch_ppocr_mobile_v2_det_train.onnx'
- # rec_model_path = 'models\ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
- # image_path = r'test_images\2021-01-23_12-30-56.png'
-
- # text_sys = TextSystem(det_model_path, rec_model_path)
- # dt_boxes, rec_res = text_sys(image_path)
- # visualize(image_path, dt_boxes, rec_res)
+ # 文本检测+方向分类+文本识别
+ det_model_path = 'models/ch_ppocr_mobile_v2_det_train.onnx'
+ cls_model_path = 'models/ch_ppocr_mobile_v2.0_cls_infer.onnx'
+ rec_model_path = 'models/ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
+ image_path = r'test_images\long1.jpg'
+
+ text_sys = TextSystem(det_model_path, rec_model_path,
+ use_angle_cls=True,
+ cls_model_path=cls_model_path)
+ dt_boxes, rec_res = text_sys(image_path)
+ visualize(image_path, dt_boxes, rec_res)
diff --git a/python/ch_ppocr_mobile_v2_cls/__init__.py b/python/ch_ppocr_mobile_v2_cls/__init__.py
new file mode 100644
index 0000000..3ecae8d
--- /dev/null
+++ b/python/ch_ppocr_mobile_v2_cls/__init__.py
@@ -0,0 +1,6 @@
+# !/usr/bin/env python
+# -*- encoding: utf-8 -*-
+# @File: __init__.py
+# @Time: 2021/01/31 11:02:53
+# @Author: Max
+from .text_cls import TextClassifier
\ No newline at end of file
diff --git a/python/ch_ppocr_mobile_v2_cls/text_cls.py b/python/ch_ppocr_mobile_v2_cls/text_cls.py
new file mode 100644
index 0000000..b226403
--- /dev/null
+++ b/python/ch_ppocr_mobile_v2_cls/text_cls.py
@@ -0,0 +1,132 @@
+# 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
+
+import cv2
+import numpy as np
+import onnxruntime as ort
+
+try:
+ from .utils import check_and_read_gif, get_image_file_list, ClsPostProcess
+except:
+ from utils import check_and_read_gif, get_image_file_list, ClsPostProcess
+
+
+class TextClassifier(object):
+ def __init__(self, cls_model_path):
+ self.cls_image_shape = [3, 48, 192]
+ self.cls_batch_num = 6
+ self.cls_thresh = 0.9
+ self.postprocess_op = ClsPostProcess(label_list=['0', '180'])
+ self.session = ort.InferenceSession(cls_model_path)
+
+ def resize_norm_img(self, img):
+ imgC, imgH, imgW = self.cls_image_shape
+ h = img.shape[0]
+ w = img.shape[1]
+ ratio = w / float(h)
+ if math.ceil(imgH * ratio) > imgW:
+ resized_w = imgW
+ else:
+ resized_w = int(math.ceil(imgH * ratio))
+ resized_image = cv2.resize(img, (resized_w, imgH))
+ resized_image = resized_image.astype('float32')
+ if self.cls_image_shape[0] == 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((imgC, imgH, imgW), dtype=np.float32)
+ padding_im[:, :, 0:resized_w] = resized_image
+ return padding_im
+
+ def load_image(self, image_dir):
+ image_file_list = get_image_file_list(image_dir)
+ valid_image_file_list = []
+ img_list = []
+ for image_file in image_file_list:
+ img, flag = check_and_read_gif(image_file)
+ if not flag:
+ img = cv2.imread(image_file)
+ if img is None:
+ print(f"error in loading image:{image_file}")
+ continue
+ valid_image_file_list.append(image_file)
+ img_list.append(img)
+ return img_list
+
+ def __call__(self, image_dir):
+ if isinstance(image_dir[0], (list, str)):
+ img_list = self.load_image(image_dir)
+ else:
+ img_list = image_dir
+
+ img_list = copy.deepcopy(img_list)
+ img_num = len(img_list)
+ # Calculate the aspect ratio of all text bars
+ width_list = []
+ for img in img_list:
+ width_list.append(img.shape[1] / float(img.shape[0]))
+ # Sorting can speed up the cls process
+ indices = np.argsort(np.array(width_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)
+ norm_img_batch = []
+ 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)
+ 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)
+ onnx_inputs = {self.session.get_inputs()[0].name: norm_img_batch}
+
+ starttime = time.time()
+ 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_dir', type=str, help='image_dir|image_path')
+ parser.add_argument('--cls_model_dir', type=str, help='cls_model_dir')
+ args = parser.parse_args()
+
+ text_classifier = TextClassifier(args.cls_model_dir)
+
+ img_list, cls_res, predict_time = text_classifier(args.image_dir)
+ for ino in range(len(img_list)):
+ print(f"分类结果:{cls_res[ino]}")
diff --git a/python/ch_ppocr_mobile_v2_cls/utils.py b/python/ch_ppocr_mobile_v2_cls/utils.py
new file mode 100644
index 0000000..edbd6a2
--- /dev/null
+++ b/python/ch_ppocr_mobile_v2_cls/utils.py
@@ -0,0 +1,65 @@
+# 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 os
+import cv2
+import imghdr
+
+
+def get_image_file_list(img_file):
+ imgs_lists = []
+ if img_file is None or not os.path.exists(img_file):
+ raise ValueError("not found any img file in {}".format(img_file))
+
+ img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}
+ if os.path.isfile(img_file) and imghdr.what(img_file) in img_end:
+ imgs_lists.append(img_file)
+ elif os.path.isdir(img_file):
+ for single_file in os.listdir(img_file):
+ file_path = os.path.join(img_file, single_file)
+ if os.path.isfile(file_path) and imghdr.what(file_path) in img_end:
+ imgs_lists.append(file_path)
+ if len(imgs_lists) == 0:
+ raise ValueError("not found any img file in {}".format(img_file))
+ return imgs_lists
+
+
+def check_and_read_gif(img_path):
+ if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:
+ gif = cv2.VideoCapture(img_path)
+ ret, frame = gif.read()
+ if not ret:
+ print("Cannot read {}. This gif image maybe corrupted.")
+ return None, False
+ if len(frame.shape) == 2 or frame.shape[-1] == 1:
+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
+ imgvalue = frame[:, :, ::-1]
+ return imgvalue, True
+ return None, False
+
+
+class ClsPostProcess(object):
+ """ Convert between text-label and text-index """
+
+ def __init__(self, label_list, **kwargs):
+ super(ClsPostProcess, self).__init__()
+ self.label_list = label_list
+
+ def __call__(self, preds, label=None, *args, **kwargs):
+ 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 file
diff --git a/python/ch_ppocr_mobile_v2_det_train/__init__.py b/python/ch_ppocr_mobile_v2_det/__init__.py
similarity index 100%
rename from python/ch_ppocr_mobile_v2_det_train/__init__.py
rename to python/ch_ppocr_mobile_v2_det/__init__.py
diff --git a/python/ch_ppocr_mobile_v2_det_train/text_detect.py b/python/ch_ppocr_mobile_v2_det/text_detect.py
similarity index 100%
rename from python/ch_ppocr_mobile_v2_det_train/text_detect.py
rename to python/ch_ppocr_mobile_v2_det/text_detect.py
diff --git a/python/ch_ppocr_mobile_v2_det_train/utils.py b/python/ch_ppocr_mobile_v2_det/utils.py
similarity index 100%
rename from python/ch_ppocr_mobile_v2_det_train/utils.py
rename to python/ch_ppocr_mobile_v2_det/utils.py
diff --git a/python/readme.md b/python/readme.md
index 36095e6..993eca6 100755
--- a/python/readme.md
+++ b/python/readme.md
@@ -1,39 +1,43 @@
#### TODO:
-- [ ] 超轻量2.0方向分类器模型整理
+- [x] 超轻量2.0方向分类器模型整理
- [ ] 通用2.0文本检测模型整理
- [ ] 通用2.0文本识别模型整理
- [ ] 通用2.0方向分类器模型整理
-### 检测和识别模型下载:
+### 检测、方向分类和识别模型下载:
- [链接](https://pan.baidu.com/s/1qkqWK4wRdMjqGGbzR-FyWg)
- 提取码:30jv
- 下载之后放在`models`目录即可
-### 文本检测+文本识别
-- 具体参见`bpocr.py`
+### 文本检测+方向分类+文本识别
+- 具体参见[bpocr.py](./bpocr.py)
-#### 使用方法:
+#### 简单示例
```python
-det_model_path = 'models\ch_ppocr_mobile_v2_det_train.onnx'
-rec_model_path = 'models\ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
-image_path = r'test_images\2021-01-23_12-30-56.png'
-
-text_sys = TextSystem(det_model_path, rec_model_path)
+det_model_path = 'models/ch_ppocr_mobile_v2_det_train.onnx'
+cls_model_path = 'models/ch_ppocr_mobile_v2.0_cls_infer.onnx'
+rec_model_path = 'models/ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
+image_path = r'test_images\long1.jpg'
+
+text_sys = TextSystem(det_model_path, rec_model_path,
+ use_angle_cls=True,
+ cls_model_path=cls_model_path)
dt_boxes, rec_res = text_sys(image_path)
visualize(image_path, dt_boxes, rec_res)
+
```
### 通用超轻量文本检测模型 ch_ppocr_mobile_v2_det_train
- **Note: 支持任意尺寸输入**
-- 详细见`ch_ppocr_mobile_v2_det_train\text_detect.py`
+- 详细见[ch_ppocr_mobile_v2_det/text_detect.py](./ch_ppocr_mobile_v2_det/text_detect.py)
#### 简单示例
```python
-det_model_path = 'models\ch_ppocr_mobile_v2_det_train.onnx'
-image_path = r'test_images\det_images\1.jpg'
+det_model_path = 'models/ch_ppocr_mobile_v2_det_train.onnx'
+image_path = r'test_images/det_images/1.jpg'
test_detector = TextDetector(det_model_path)
@@ -50,26 +54,41 @@ print(dt_boxes.shape)
print(elapse)
```
-### 通用超轻量文本识别模型ch_ppocr_mobile_v2_rec
+### 通用超轻量方向分类器模型 ch_ppocr_mobile_v2_cls
+- **Note**: 支持`0 180`两个方向分类
+- 详细见[ch_ppocr_mobile_v2_cls/text_cls.py](./ch_ppocr_mobile_v2_cls/text_cls.py)
+
+#### 简单示例
+```python
+text_classifier = TextClassifier(args.cls_model_dir)
+
+img_list, cls_res, predict_time = text_classifier(args.image_dir)
+for ino in range(len(img_list)):
+ print(f"分类结果:{cls_res[ino]}")
+```
+
+### 通用超轻量文本识别模型 ch_ppocr_mobile_v2_rec
- **Note: 支持任意尺寸输入**
-- 详细见`ch_ppocr_mobile_v2_rec\text_recognize.py`
+- 详细见[ch_ppocr_mobile_v2_rec/text_recognize.py](./ch_ppocr_mobile_v2_rec/text_recognize.py)
#### 简单示例:
```python
-rec_model_path = r'models\ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
-image_path = r'test_images\rec_images\2021-01-19_13-44-34.png'
+rec_model_path = r'models/ch_ppocr_mobile_v2.0_rec_pre_infer.onnx'
+image_path = r'test_images/rec_images/2021-01-19_13-44-34.png'
text_recongnizer = TextRecognizer(rec_model_path)
rec_res, elapse = text_recongnizer(image_path)
-print(f'识别结果:{rec_res}\tcost: {elapse}s')
+print(f'识别结果:{rec_res}/tcost: {elapse}s')
```
+---
+
### 通用超轻量文本检测模型 ch_ppocr_mobile_v1.1_det
- **Note: 支持任意尺寸输入**
-- 详细见`ch_ppocr_mobile_v1_det\text_detect.py`
+- 详细见[ch_ppocr_mobile_v1_det/text_detect.py](./ch_ppocr_mobile_v1_det/text_detect.py)
#### 简单示例