Skip to content

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

chore: update files

SWHL1518e7223516
diff --git a/python/demo.py b/python/demo.py
index 81a77d6..446756d 100644
--- a/python/demo.py
+++ b/python/demo.py
@@ -3,7 +3,7 @@
# @Contact: [email protected]
import cv2
-from rapidocr_onnxruntime import RapidOCR, VisRes
+from rapidocr import RapidOCR, VisRes
# from rapidocr_paddle import RapidOCR, VisRes
# from rapidocr_openvino import RapidOCR, VisRes
@@ -16,7 +16,7 @@ with open(image_path, "rb") as f:
img = f.read()
# result, elapse_list = engine(img, use_det=True, use_cls=False, use_rec=False)
-result, elapse_list = engine(img)
+result, elapse_list = engine(img, return_word_box=True)
print(result)
print(elapse_list)
diff --git a/python/rapidocr/__init__.py b/python/rapidocr/__init__.py
new file mode 100644
index 0000000..c978620
--- /dev/null
+++ b/python/rapidocr/__init__.py
@@ -0,0 +1,5 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .main import RapidOCR
+from .utils import LoadImageError, VisRes
diff --git a/python/rapidocr/cal_rec_boxes/__init__.py b/python/rapidocr/cal_rec_boxes/__init__.py
new file mode 100644
index 0000000..5127715
--- /dev/null
+++ b/python/rapidocr/cal_rec_boxes/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .main import CalRecBoxes
diff --git a/python/rapidocr/cal_rec_boxes/main.py b/python/rapidocr/cal_rec_boxes/main.py
new file mode 100644
index 0000000..296997f
--- /dev/null
+++ b/python/rapidocr/cal_rec_boxes/main.py
@@ -0,0 +1,288 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL / Joker1212
+# @Contact: [email protected]
+import copy
+import math
+from typing import List, Optional, Tuple
+
+import cv2
+import numpy as np
+
+from ..ch_ppocr_rec.utils import TextRecognizerOutput
+
+
+class CalRecBoxes:
+ """计算识别文字的汉字单字和英文单词的坐标框。代码借鉴自PaddlePaddle/PaddleOCR和fanqie03/char-detection"""
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self,
+ imgs: Optional[List[np.ndarray]],
+ dt_boxes: Optional[List[np.ndarray]],
+ rec_res: TextRecognizerOutput,
+ ) -> TextRecognizerOutput:
+ # rec_res = list(zip(rec_res.line_results, rec_res.word_results))
+ word_results = []
+ for idx, (img, box) in enumerate(zip(imgs, dt_boxes)):
+ direction = self.get_box_direction(box)
+
+ rec_txt, rec_conf = rec_res.line_results[idx]
+ rec_word_info = rec_res.word_results[idx]
+
+ h, w = img.shape[:2]
+ img_box = np.array([[0, 0], [w, 0], [w, h], [0, h]])
+ word_box_content_list, word_box_list, conf_list = self.cal_ocr_word_box(
+ rec_txt, img_box, rec_word_info
+ )
+ word_box_list = self.adjust_box_overlap(copy.deepcopy(word_box_list))
+ word_box_list = self.reverse_rotate_crop_image(
+ copy.deepcopy(box), word_box_list, direction
+ )
+ word_results.extend(
+ list(zip(word_box_content_list, conf_list, word_box_list))
+ )
+
+ rec_res.word_results = tuple(list(v) for v in word_results)
+ return rec_res
+
+ @staticmethod
+ def get_box_direction(box: np.ndarray) -> str:
+ direction = "w"
+ img_crop_width = int(
+ max(
+ np.linalg.norm(box[0] - box[1]),
+ np.linalg.norm(box[2] - box[3]),
+ )
+ )
+ img_crop_height = int(
+ max(
+ np.linalg.norm(box[0] - box[3]),
+ np.linalg.norm(box[1] - box[2]),
+ )
+ )
+ if img_crop_height * 1.0 / img_crop_width >= 1.5:
+ direction = "h"
+ return direction
+
+ @staticmethod
+ def cal_ocr_word_box(
+ rec_txt: str, box: np.ndarray, rec_word_info: List[Tuple[str, List[int]]]
+ ) -> Tuple[List[str], List[List[int]], List[float]]:
+ """Calculate the detection frame for each word based on the results of recognition and detection of ocr
+ 汉字坐标是单字的
+ 英语坐标是单词级别的
+ """
+
+ col_num, word_list, word_col_list, state_list, conf_list = rec_word_info
+ box = box.tolist()
+ bbox_x_start = box[0][0]
+ bbox_x_end = box[1][0]
+ bbox_y_start = box[0][1]
+ bbox_y_end = box[2][1]
+
+ cell_width = (bbox_x_end - bbox_x_start) / col_num
+ word_box_list = []
+ word_box_content_list = []
+ cn_width_list = []
+ en_width_list = []
+ cn_col_list = []
+ en_col_list = []
+
+ def cal_char_width(width_list, word_col_):
+ if len(word_col_) == 1:
+ return
+ char_total_length = (word_col_[-1] - word_col_[0]) * cell_width
+ char_width = char_total_length / (len(word_col_) - 1)
+ width_list.append(char_width)
+
+ def cal_box(col_list, width_list, word_box_list_):
+ if len(col_list) == 0:
+ return
+ if len(width_list) != 0:
+ avg_char_width = np.mean(width_list)
+ else:
+ avg_char_width = (bbox_x_end - bbox_x_start) / len(rec_txt)
+
+ for center_idx in col_list:
+ center_x = (center_idx + 0.5) * cell_width
+ cell_x_start = max(int(center_x - avg_char_width / 2), 0) + bbox_x_start
+ cell_x_end = (
+ min(int(center_x + avg_char_width / 2), bbox_x_end - bbox_x_start)
+ + bbox_x_start
+ )
+ cell = [
+ [cell_x_start, bbox_y_start],
+ [cell_x_end, bbox_y_start],
+ [cell_x_end, bbox_y_end],
+ [cell_x_start, bbox_y_end],
+ ]
+ word_box_list_.append(cell)
+
+ for word, word_col, state in zip(word_list, word_col_list, state_list):
+ if state == "cn":
+ cal_char_width(cn_width_list, word_col)
+ cn_col_list += word_col
+ word_box_content_list += word
+ else:
+ cal_char_width(en_width_list, word_col)
+ en_col_list += word_col
+ word_box_content_list += word
+
+ cal_box(cn_col_list, cn_width_list, word_box_list)
+ cal_box(en_col_list, en_width_list, word_box_list)
+ sorted_word_box_list = sorted(word_box_list, key=lambda box: box[0][0])
+ return word_box_content_list, sorted_word_box_list, conf_list
+
+ @staticmethod
+ def adjust_box_overlap(
+ word_box_list: List[List[List[int]]],
+ ) -> List[List[List[int]]]:
+ # 调整bbox有重叠的地方
+ for i in range(len(word_box_list) - 1):
+ cur, nxt = word_box_list[i], word_box_list[i + 1]
+ if cur[1][0] > nxt[0][0]: # 有交集
+ distance = abs(cur[1][0] - nxt[0][0])
+ cur[1][0] -= distance / 2
+ cur[2][0] -= distance / 2
+ nxt[0][0] += distance - distance / 2
+ nxt[3][0] += distance - distance / 2
+ return word_box_list
+
+ def reverse_rotate_crop_image(
+ self,
+ bbox_points: np.ndarray,
+ word_points_list: List[List[List[int]]],
+ direction: str = "w",
+ ) -> List[List[List[int]]]:
+ """
+ get_rotate_crop_image的逆操作
+ img为原图
+ part_img为crop后的图
+ bbox_points为part_img中对应在原图的bbox, 四个点,左上,右上,右下,左下
+ part_points为在part_img中的点[(x, y), (x, y)]
+ """
+ bbox_points = np.float32(bbox_points)
+
+ left = int(np.min(bbox_points[:, 0]))
+ top = int(np.min(bbox_points[:, 1]))
+ bbox_points[:, 0] = bbox_points[:, 0] - left
+ bbox_points[:, 1] = bbox_points[:, 1] - top
+
+ img_crop_width = int(np.linalg.norm(bbox_points[0] - bbox_points[1]))
+ img_crop_height = int(np.linalg.norm(bbox_points[0] - bbox_points[3]))
+
+ pts_std = np.array(
+ [
+ [0, 0],
+ [img_crop_width, 0],
+ [img_crop_width, img_crop_height],
+ [0, img_crop_height],
+ ]
+ ).astype(np.float32)
+ M = cv2.getPerspectiveTransform(bbox_points, pts_std)
+ _, IM = cv2.invert(M)
+
+ new_word_points_list = []
+ for word_points in word_points_list:
+ new_word_points = []
+ for point in word_points:
+ new_point = point
+ if direction == "h":
+ new_point = self.s_rotate(
+ math.radians(-90), new_point[0], new_point[1], 0, 0
+ )
+ new_point[0] = new_point[0] + img_crop_width
+
+ p = np.float32(new_point + [1])
+ x, y, z = np.dot(IM, p)
+ new_point = [x / z, y / z]
+
+ new_point = [int(new_point[0] + left), int(new_point[1] + top)]
+ new_word_points.append(new_point)
+ new_word_points = self.order_points(new_word_points)
+ new_word_points_list.append(new_word_points)
+ return new_word_points_list
+
+ @staticmethod
+ def s_rotate(angle, valuex, valuey, pointx, pointy):
+ """绕pointx,pointy顺时针旋转
+ https://blog.csdn.net/qq_38826019/article/details/84233397
+ """
+ valuex = np.array(valuex)
+ valuey = np.array(valuey)
+ sRotatex = (
+ (valuex - pointx) * math.cos(angle)
+ + (valuey - pointy) * math.sin(angle)
+ + pointx
+ )
+ sRotatey = (
+ (valuey - pointy) * math.cos(angle)
+ - (valuex - pointx) * math.sin(angle)
+ + pointy
+ )
+ return [sRotatex, sRotatey]
+
+ @staticmethod
+ def order_points(box: List[List[int]]) -> List[List[int]]:
+ """矩形框顺序排列"""
+
+ def convert_to_1x2(p):
+ if p.shape == (2,):
+ return p.reshape((1, 2))
+ elif p.shape == (1, 2):
+ return p
+ else:
+ return p[:1, :]
+
+ box = np.array(box).reshape((-1, 2))
+ center_x, center_y = np.mean(box[:, 0]), np.mean(box[:, 1])
+ if np.any(box[:, 0] == center_x) and np.any(
+ box[:, 1] == center_y
+ ): # 有两点横坐标相等,有两点纵坐标相等,菱形
+ p1 = box[np.where(box[:, 0] == np.min(box[:, 0]))]
+ p2 = box[np.where(box[:, 1] == np.min(box[:, 1]))]
+ p3 = box[np.where(box[:, 0] == np.max(box[:, 0]))]
+ p4 = box[np.where(box[:, 1] == np.max(box[:, 1]))]
+ elif np.all(box[:, 0] == center_x): # 四个点的横坐标都相同
+ y_sort = np.argsort(box[:, 1])
+ p1 = box[y_sort[0]]
+ p2 = box[y_sort[1]]
+ p3 = box[y_sort[2]]
+ p4 = box[y_sort[3]]
+ elif np.any(box[:, 0] == center_x) and np.all(
+ box[:, 1] != center_y
+ ): # 只有两点横坐标相等,先上下再左右
+ p12, p34 = (
+ box[np.where(box[:, 1] < center_y)],
+ box[np.where(box[:, 1] > center_y)],
+ )
+ p1, p2 = (
+ p12[np.where(p12[:, 0] == np.min(p12[:, 0]))],
+ p12[np.where(p12[:, 0] == np.max(p12[:, 0]))],
+ )
+ p3, p4 = (
+ p34[np.where(p34[:, 0] == np.max(p34[:, 0]))],
+ p34[np.where(p34[:, 0] == np.min(p34[:, 0]))],
+ )
+ else: # 只有两点纵坐标相等,或者是没有相等的,先左右再上下
+ p14, p23 = (
+ box[np.where(box[:, 0] < center_x)],
+ box[np.where(box[:, 0] > center_x)],
+ )
+ p1, p4 = (
+ p14[np.where(p14[:, 1] == np.min(p14[:, 1]))],
+ p14[np.where(p14[:, 1] == np.max(p14[:, 1]))],
+ )
+ p2, p3 = (
+ p23[np.where(p23[:, 1] == np.min(p23[:, 1]))],
+ p23[np.where(p23[:, 1] == np.max(p23[:, 1]))],
+ )
+
+ # 解决单字切割后横坐标完全相同的shape错误
+ p1 = convert_to_1x2(p1)
+ p2 = convert_to_1x2(p2)
+ p3 = convert_to_1x2(p3)
+ p4 = convert_to_1x2(p4)
+ return np.array([p1, p2, p3, p4]).reshape((-1, 2)).tolist()
diff --git a/python/rapidocr/ch_ppocr_cls/__init__.py b/python/rapidocr/ch_ppocr_cls/__init__.py
new file mode 100644
index 0000000..7fc854c
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_cls/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .text_cls import TextClassifier
diff --git a/python/rapidocr/ch_ppocr_cls/text_cls.py b/python/rapidocr/ch_ppocr_cls/text_cls.py
new file mode 100644
index 0000000..183f6ed
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_cls/text_cls.py
@@ -0,0 +1,114 @@
+# 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 Any, Dict, List, Tuple, Union
+
+import cv2
+import numpy as np
+from rapidocr.utils import OrtInferSession, read_yaml
+
+from .utils import ClsPostProcess
+
+
+class TextClassifier:
+ def __init__(self, config: Dict[str, Any]):
+ 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"])
+
+ self.infer = OrtInferSession(config)
+
+ def __call__(
+ self, img_list: Union[np.ndarray, List[np.ndarray]]
+ ) -> Tuple[List[np.ndarray], List[List[Union[str, float]]], float]:
+ 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)
+
+ 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()
+ prob_out = self.infer(norm_img_batch)[0]
+ cls_result = self.postprocess_op(prob_out)
+ elapse += time.time() - starttime
+
+ for rno, (label, score) in enumerate(cls_result):
+ 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
+
+ def resize_norm_img(self, img: np.ndarray) -> np.ndarray:
+ img_c, img_h, img_w = self.cls_image_shape
+ h, w = img.shape[:2]
+ ratio = w / float(h)
+ if math.ceil(img_h * ratio) > img_w:
+ resized_w = img_w
+ else:
+ resized_w = int(math.ceil(img_h * ratio))
+
+ resized_image = cv2.resize(img, (resized_w, img_h))
+ resized_image = resized_image.astype("float32")
+ if img_c == 1:
+ resized_image = resized_image / 255
+ resized_image = resized_image[np.newaxis, :]
+ else:
+ resized_image = resized_image.transpose((2, 0, 1)) / 255
+
+ resized_image -= 0.5
+ resized_image /= 0.5
+ padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32)
+ padding_im[:, :, :resized_w] = resized_image
+ return padding_im
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ 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 result:{cls_res[ino]}")
diff --git a/python/rapidocr/ch_ppocr_cls/utils.py b/python/rapidocr/ch_ppocr_cls/utils.py
new file mode 100644
index 0000000..6549fcb
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_cls/utils.py
@@ -0,0 +1,28 @@
+# 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.
+from typing import List, Tuple
+
+import numpy as np
+
+
+class ClsPostProcess:
+ def __init__(self, label_list: List[str]):
+ self.label_list = label_list
+
+ def __call__(self, preds: np.ndarray) -> List[Tuple[str, float]]:
+ pred_idxs = preds.argmax(axis=1)
+ decode_out = [
+ (self.label_list[idx], preds[i, idx]) for i, idx in enumerate(pred_idxs)
+ ]
+ return decode_out
diff --git a/python/rapidocr/ch_ppocr_det/__init__.py b/python/rapidocr/ch_ppocr_det/__init__.py
new file mode 100644
index 0000000..502f4a3
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_det/__init__.py
@@ -0,0 +1,4 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .text_detect import TextDetector
diff --git a/python/rapidocr/ch_ppocr_det/text_detect.py b/python/rapidocr/ch_ppocr_det/text_detect.py
new file mode 100644
index 0000000..c0c578e
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_det/text_detect.py
@@ -0,0 +1,124 @@
+# 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 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import time
+from typing import Any, Dict, Optional, Tuple
+
+import numpy as np
+
+from rapidocr.utils import OrtInferSession
+
+from .utils import DBPostProcess, DetPreProcess
+
+
+class TextDetector:
+ def __init__(self, config: Dict[str, Any]):
+ self.limit_side_len = config.get("limit_side_len")
+ self.limit_type = config.get("limit_type")
+ self.mean = config.get("mean")
+ self.std = config.get("std")
+ self.preprocess_op = None
+
+ post_process = {
+ "thresh": config.get("thresh", 0.3),
+ "box_thresh": config.get("box_thresh", 0.5),
+ "max_candidates": config.get("max_candidates", 1000),
+ "unclip_ratio": config.get("unclip_ratio", 1.6),
+ "use_dilation": config.get("use_dilation", True),
+ "score_mode": config.get("score_mode", "fast"),
+ }
+ self.postprocess_op = DBPostProcess(**post_process)
+
+ self.infer = OrtInferSession(config)
+
+ def __call__(self, img: np.ndarray) -> Tuple[Optional[np.ndarray], float]:
+ start_time = time.perf_counter()
+
+ if img is None:
+ raise ValueError("img is None")
+
+ ori_img_shape = img.shape[0], img.shape[1]
+ self.preprocess_op = self.get_preprocess(max(img.shape[0], img.shape[1]))
+ prepro_img = self.preprocess_op(img)
+ if prepro_img is None:
+ return None, 0
+
+ preds = self.infer(prepro_img)[0]
+ dt_boxes, dt_boxes_scores = self.postprocess_op(preds, ori_img_shape)
+ dt_boxes = self.filter_tag_det_res(dt_boxes, ori_img_shape)
+ elapse = time.perf_counter() - start_time
+ return dt_boxes, elapse
+
+ def get_preprocess(self, max_wh):
+ if self.limit_type == "min":
+ limit_side_len = self.limit_side_len
+ elif max_wh < 960:
+ limit_side_len = 960
+ elif max_wh < 1500:
+ limit_side_len = 1500
+ else:
+ limit_side_len = 2000
+ return DetPreProcess(limit_side_len, self.limit_type, self.mean, self.std)
+
+ def filter_tag_det_res(
+ self, dt_boxes: np.ndarray, image_shape: Tuple[int, int]
+ ) -> np.ndarray:
+ img_height, img_width = image_shape
+ 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)
+ return np.array(dt_boxes_new)
+
+ def order_points_clockwise(self, pts: np.ndarray) -> np.ndarray:
+ """
+ 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: np.ndarray, img_height: int, img_width: int
+ ) -> np.ndarray:
+ 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
diff --git a/python/rapidocr/ch_ppocr_det/utils.py b/python/rapidocr/ch_ppocr_det/utils.py
new file mode 100644
index 0000000..ef41063
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_det/utils.py
@@ -0,0 +1,237 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from typing import List, Optional, Tuple
+
+import cv2
+import numpy as np
+import pyclipper
+from shapely.geometry import Polygon
+
+
+class DetPreProcess:
+ def __init__(
+ self, limit_side_len: int = 736, limit_type: str = "min", mean=None, std=None
+ ):
+ if mean is None:
+ mean = [0.5, 0.5, 0.5]
+
+ if std is None:
+ std = [0.5, 0.5, 0.5]
+
+ self.mean = np.array(mean)
+ self.std = np.array(std)
+ self.scale = 1 / 255.0
+
+ self.limit_side_len = limit_side_len
+ self.limit_type = limit_type
+
+ def __call__(self, img: np.ndarray) -> Optional[np.ndarray]:
+ resized_img = self.resize(img)
+ if resized_img is None:
+ return None
+
+ img = self.normalize(resized_img)
+ img = self.permute(img)
+ img = np.expand_dims(img, axis=0).astype(np.float32)
+ return img
+
+ def normalize(self, img: np.ndarray) -> np.ndarray:
+ return (img.astype("float32") * self.scale - self.mean) / self.std
+
+ def permute(self, img: np.ndarray) -> np.ndarray:
+ return img.transpose((2, 0, 1))
+
+ def resize(self, img: np.ndarray) -> Optional[np.ndarray]:
+ """resize image to a size multiple of 32 which is required by the network"""
+ h, w = img.shape[:2]
+
+ if self.limit_type == "max":
+ if max(h, w) > self.limit_side_len:
+ if h > w:
+ ratio = float(self.limit_side_len) / h
+ else:
+ ratio = float(self.limit_side_len) / w
+ else:
+ ratio = 1.0
+ else:
+ if min(h, w) < self.limit_side_len:
+ if h < w:
+ ratio = float(self.limit_side_len) / h
+ else:
+ ratio = float(self.limit_side_len) / w
+ else:
+ ratio = 1.0
+
+ 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
+ img = cv2.resize(img, (int(resize_w), int(resize_h)))
+ except Exception as exc:
+ raise ResizeImgError from exc
+
+ return img
+
+
+class ResizeImgError(Exception):
+ pass
+
+
+class DBPostProcess:
+ """The post process for Differentiable Binarization (DB)."""
+
+ def __init__(
+ self,
+ thresh: float = 0.3,
+ box_thresh: float = 0.7,
+ max_candidates: int = 1000,
+ unclip_ratio: float = 2.0,
+ score_mode: str = "fast",
+ use_dilation: bool = False,
+ ):
+ self.thresh = thresh
+ self.box_thresh = box_thresh
+ self.max_candidates = max_candidates
+ self.unclip_ratio = unclip_ratio
+ self.min_size = 3
+ self.score_mode = score_mode
+
+ self.dilation_kernel = None
+ if use_dilation:
+ self.dilation_kernel = np.array([[1, 1], [1, 1]])
+
+ def __call__(
+ self, pred: np.ndarray, ori_shape: Tuple[int, int]
+ ) -> Tuple[np.ndarray, List[float]]:
+ src_h, src_w = ori_shape
+ pred = pred[:, 0, :, :]
+ segmentation = pred > self.thresh
+
+ mask = segmentation[0]
+ if self.dilation_kernel is not None:
+ mask = cv2.dilate(
+ np.array(segmentation[0]).astype(np.uint8), self.dilation_kernel
+ )
+ boxes, scores = self.boxes_from_bitmap(pred[0], mask, src_w, src_h)
+ return boxes, scores
+
+ def boxes_from_bitmap(
+ self, pred: np.ndarray, bitmap: np.ndarray, dest_width: int, dest_height: int
+ ) -> Tuple[np.ndarray, List[float]]:
+ """
+ bitmap: single map with shape (1, H, W),
+ whose values are binarized as {0, 1}
+ """
+
+ 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
+
+ if self.score_mode == "fast":
+ score = self.box_score_fast(pred, points.reshape(-1, 2))
+ else:
+ score = self.box_score_slow(pred, contour)
+
+ if self.box_thresh > score:
+ continue
+
+ box = self.unclip(points)
+ box, sside = self.get_mini_boxes(box)
+ if sside < self.min_size + 2:
+ continue
+
+ 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.int32))
+ scores.append(score)
+ return np.array(boxes, dtype=np.int32), scores
+
+ def get_mini_boxes(self, contour: np.ndarray) -> Tuple[np.ndarray, float]:
+ 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 = np.array(
+ [points[index_1], points[index_2], points[index_3], points[index_4]]
+ )
+ return box, min(bounding_box[1])
+
+ @staticmethod
+ def box_score_fast(bitmap: np.ndarray, _box: np.ndarray) -> float:
+ h, w = bitmap.shape[:2]
+ box = _box.copy()
+ xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int32), 0, w - 1)
+ xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int32), 0, w - 1)
+ ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int32), 0, h - 1)
+ ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int32), 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 box_score_slow(self, bitmap: np.ndarray, contour: np.ndarray) -> float:
+ """use polyon mean score as the mean score"""
+ h, w = bitmap.shape[:2]
+ contour = contour.copy()
+ contour = np.reshape(contour, (-1, 2))
+
+ xmin = np.clip(np.min(contour[:, 0]), 0, w - 1)
+ xmax = np.clip(np.max(contour[:, 0]), 0, w - 1)
+ ymin = np.clip(np.min(contour[:, 1]), 0, h - 1)
+ ymax = np.clip(np.max(contour[:, 1]), 0, h - 1)
+
+ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
+
+ contour[:, 0] = contour[:, 0] - xmin
+ contour[:, 1] = contour[:, 1] - ymin
+
+ cv2.fillPoly(mask, contour.reshape(1, -1, 2).astype(np.int32), 1)
+ return cv2.mean(bitmap[ymin : ymax + 1, xmin : xmax + 1], mask)[0]
+
+ def unclip(self, box: np.ndarray) -> np.ndarray:
+ 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)).reshape((-1, 1, 2))
+ return expanded
diff --git a/python/rapidocr/ch_ppocr_rec/__init__.py b/python/rapidocr/ch_ppocr_rec/__init__.py
new file mode 100644
index 0000000..46477ba
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_rec/__init__.py
@@ -0,0 +1,5 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from .main import TextRecognizer
+from .utils import TextRecognizerOutput
diff --git a/python/rapidocr_onnxruntime/ch_ppocr_rec/main.py b/python/rapidocr/ch_ppocr_rec/main.py
similarity index 93%
rename from python/rapidocr_onnxruntime/ch_ppocr_rec/main.py
rename to python/rapidocr/ch_ppocr_rec/main.py
index 0847878..a37d575 100644
--- a/python/rapidocr_onnxruntime/ch_ppocr_rec/main.py
+++ b/python/rapidocr/ch_ppocr_rec/main.py
@@ -19,12 +19,9 @@ from typing import Any, Dict, List, Union
import cv2
import numpy as np
-from rapidocr_onnxruntime.utils import OrtInferSession, read_yaml
+from rapidocr.utils import OrtInferSession, read_yaml
-from .utils import (
- CTCLabelDecode,
- TextRecognizerOutput,
-)
+from .utils import CTCLabelDecode, TextRecognizerOutput
class TextRecognizer:
@@ -91,7 +88,11 @@ class TextRecognizer:
)
for rno, one_res in enumerate(line_results):
- rec_res[indices[beg_img_no + rno]] = (one_res, word_results[rno])
+ if return_word_box:
+ rec_res[indices[beg_img_no + rno]] = (one_res, word_results[rno])
+ continue
+
+ rec_res[indices[beg_img_no + rno]] = (one_res, None)
elapse += time.time() - starttime
all_line_results, all_word_results = list(zip(*rec_res))
diff --git a/python/rapidocr/ch_ppocr_rec/utils.py b/python/rapidocr/ch_ppocr_rec/utils.py
new file mode 100644
index 0000000..1fadcf8
--- /dev/null
+++ b/python/rapidocr/ch_ppocr_rec/utils.py
@@ -0,0 +1,217 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+
+
+@dataclass
+class TextRecognizerConfig:
+ intra_op_num_threads: int = -1
+ inter_op_num_threads: int = -1
+ use_cuda: bool = False
+ use_dml: bool = False
+ model_path: Union[str, Path, None] = None
+
+ rec_batch_num: int = 6
+ rec_img_shape: Tuple[int, int, int] = (3, 48, 320)
+ rec_keys_path: Union[str, Path, None] = None
+
+
+@dataclass
+class TextRecognizerInput:
+ img_list: Union[np.ndarray, List[np.ndarray]] = field(init=False)
+ return_word_box: bool = False
+
+ def __pose_init__(self):
+ if isinstance(self.img_list, np.ndarray):
+ self.img_list = [self.img_list]
+
+
+@dataclass
+class TextRecognizerOutput:
+ line_results: Optional[Tuple[List]] = None
+ word_results: Optional[List[List]] = None
+ elapse: Optional[float] = None
+
+
+class CTCLabelDecode:
+ def __init__(
+ self,
+ character: Optional[List[str]] = None,
+ character_path: Union[str, Path, None] = None,
+ ):
+ self.character = self.get_character(character, character_path)
+ self.dict = {char: i for i, char in enumerate(self.character)}
+
+ def __call__(
+ self, preds: np.ndarray, return_word_box: bool = False, **kwargs
+ ) -> Tuple[List[Tuple[str, float]], List[List]]:
+ preds_idx = preds.argmax(axis=2)
+ preds_prob = preds.max(axis=2)
+ line_results, word_results = self.decode(
+ preds_idx, preds_prob, return_word_box, is_remove_duplicate=True
+ )
+ if return_word_box:
+ for rec_idx, rec in enumerate(word_results):
+ wh_ratio = kwargs["wh_ratio_list"][rec_idx]
+ max_wh_ratio = kwargs["max_wh_ratio"]
+ rec[0] *= wh_ratio / max_wh_ratio
+ return line_results, word_results
+
+ def get_character(
+ self,
+ character: Optional[List[str]] = None,
+ character_path: Union[str, Path, None] = None,
+ ) -> List[str]:
+ if character is None and character_path is None:
+ raise ValueError("character must not be None")
+
+ character_list = None
+ if character:
+ character_list = character
+
+ if character_path:
+ character_list = self.read_character_file(character_path)
+
+ if character_list is None:
+ raise ValueError("character must not be None")
+
+ character_list = self.insert_special_char(
+ character_list, " ", len(character_list)
+ )
+ character_list = self.insert_special_char(character_list, "blank", 0)
+ return character_list
+
+ @staticmethod
+ def read_character_file(character_path: Union[str, Path]) -> List[str]:
+ character_list = []
+ with open(character_path, "rb") as f:
+ lines = f.readlines()
+ for line in lines:
+ line = line.decode("utf-8").strip("\n").strip("\r\n")
+ character_list.append(line)
+ return character_list
+
+ @staticmethod
+ def insert_special_char(
+ character_list: List[str], special_char: str, loc: int = -1
+ ) -> List[str]:
+ character_list.insert(loc, special_char)
+ return character_list
+
+ def decode(
+ self,
+ text_index: np.ndarray,
+ text_prob: Optional[np.ndarray] = None,
+ return_word_box: bool = False,
+ is_remove_duplicate: bool = False,
+ ) -> List[Tuple[str, float]]:
+ result_list, result_words_list = [], []
+ ignored_tokens = self.get_ignored_tokens()
+ batch_size = len(text_index)
+ for batch_idx in range(batch_size):
+ selection = np.ones(len(text_index[batch_idx]), dtype=bool)
+ if is_remove_duplicate:
+ selection[1:] = text_index[batch_idx][1:] != text_index[batch_idx][:-1]
+
+ for ignored_token in ignored_tokens:
+ selection &= text_index[batch_idx] != ignored_token
+
+ if text_prob is not None:
+ conf_list = np.array(text_prob[batch_idx][selection]).tolist()
+ conf_list = [round(conf, 5) for conf in conf_list]
+ else:
+ conf_list = [1] * len(selection)
+
+ if len(conf_list) == 0:
+ conf_list = [0]
+
+ char_list = [
+ self.character[text_id] for text_id in text_index[batch_idx][selection]
+ ]
+ text = "".join(char_list)
+
+ result_list.append([text, np.mean(conf_list).round(5).tolist()])
+
+ if return_word_box:
+ word_list, word_col_list, state_list = self.get_word_info(
+ text, selection
+ )
+ result_words_list.append(
+ [
+ len(text_index[batch_idx]),
+ word_list,
+ word_col_list,
+ state_list,
+ conf_list,
+ ]
+ )
+ return result_list, result_words_list
+
+ @staticmethod
+ def get_word_info(
+ text: str, selection: np.ndarray
+ ) -> Tuple[List[List[str]], List[List[int]], List[str]]:
+ """
+ Group the decoded characters and record the corresponding decoded positions.
+ from https://github.com/PaddlePaddle/PaddleOCR/blob/fbba2178d7093f1dffca65a5b963ec277f1a6125/ppocr/postprocess/rec_postprocess.py#L70
+
+ Args:
+ text: the decoded text
+ selection: the bool array that identifies which columns of features are decoded as non-separated characters
+ Returns:
+ word_list: list of the grouped words
+ word_col_list: list of decoding positions corresponding to each character in the grouped word
+ state_list: list of marker to identify the type of grouping words, including two types of grouping words:
+ - 'cn': continous chinese characters (e.g., 你好啊)
+ - 'en&num': continous english characters (e.g., hello), number (e.g., 123, 1.123), or mixed of them connected by '-' (e.g., VGG-16)
+ """
+ state = None
+ word_content = []
+ word_col_content = []
+ word_list = []
+ word_col_list = []
+ state_list = []
+ valid_col = np.where(selection)[0]
+ col_width = np.zeros(valid_col.shape)
+ if len(valid_col) > 0:
+ col_width[1:] = valid_col[1:] - valid_col[:-1]
+ col_width[0] = min(
+ 3 if "\u4e00" <= text[0] <= "\u9fff" else 2, int(valid_col[0])
+ )
+
+ for c_i, char in enumerate(text):
+ if "\u4e00" <= char <= "\u9fff":
+ c_state = "cn"
+ else:
+ c_state = "en&num"
+
+ if state is None:
+ state = c_state
+
+ if state != c_state or col_width[c_i] > 4:
+ if len(word_content) != 0:
+ word_list.append(word_content)
+ word_col_list.append(word_col_content)
+ state_list.append(state)
+ word_content = []
+ word_col_content = []
+ state = c_state
+
+ word_content.append(char)
+ word_col_content.append(int(valid_col[c_i]))
+
+ if len(word_content) != 0:
+ word_list.append(word_content)
+ word_col_list.append(word_col_content)
+ state_list.append(state)
+
+ return word_list, word_col_list, state_list
+
+ @staticmethod
+ def get_ignored_tokens() -> List[int]:
+ return [0] # for ctc blank
diff --git a/python/rapidocr/config.yaml b/python/rapidocr/config.yaml
new file mode 100644
index 0000000..d249ce8
--- /dev/null
+++ b/python/rapidocr/config.yaml
@@ -0,0 +1,61 @@
+Global:
+ text_score: 0.5
+ use_det: true
+ use_cls: true
+ use_rec: true
+ print_verbose: false
+ min_height: 30
+ width_height_ratio: 8
+ max_side_len: 2000
+ min_side_len: 30
+ return_word_box: false
+
+ intra_op_num_threads: &intra_nums -1
+ inter_op_num_threads: &inter_nums -1
+
+Det:
+ intra_op_num_threads: *intra_nums
+ inter_op_num_threads: *inter_nums
+
+ use_cuda: false
+ use_dml: false
+
+ model_path: models/ch_PP-OCRv4_det_infer.onnx
+
+ limit_side_len: 736
+ limit_type: min
+ std: [ 0.5, 0.5, 0.5 ]
+ mean: [ 0.5, 0.5, 0.5 ]
+
+ thresh: 0.3
+ box_thresh: 0.5
+ max_candidates: 1000
+ unclip_ratio: 1.6
+ use_dilation: true
+ score_mode: fast
+
+Cls:
+ intra_op_num_threads: *intra_nums
+ inter_op_num_threads: *inter_nums
+
+ use_cuda: false
+ use_dml: false
+
+ model_path: 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']
+
+Rec:
+ intra_op_num_threads: *intra_nums
+ inter_op_num_threads: *inter_nums
+
+ use_cuda: false
+ use_dml: false
+
+ model_path: models/ch_PP-OCRv4_rec_infer.onnx
+
+ rec_img_shape: [3, 48, 320]
+ rec_batch_num: 6
diff --git a/python/rapidocr/main.py b/python/rapidocr/main.py
new file mode 100644
index 0000000..e818b6d
--- /dev/null
+++ b/python/rapidocr/main.py
@@ -0,0 +1,372 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import copy
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import cv2
+import numpy as np
+
+from .cal_rec_boxes import CalRecBoxes
+from .ch_ppocr_cls import TextClassifier
+from .ch_ppocr_det import TextDetector
+from .ch_ppocr_rec import TextRecognizer, TextRecognizerOutput
+from .utils import (
+ LoadImage,
+ UpdateParameters,
+ VisRes,
+ add_round_letterbox,
+ get_logger,
+ increase_min_side,
+ init_args,
+ read_yaml,
+ reduce_max_side,
+ update_model_path,
+)
+
+root_dir = Path(__file__).resolve().parent
+DEFAULT_CFG_PATH = root_dir / "config.yaml"
+logger = get_logger("RapidOCR")
+
+
+class RapidOCR:
+ def __init__(self, config_path: Optional[str] = None, **kwargs):
+ if config_path is not None and Path(config_path).exists():
+ config = read_yaml(config_path)
+ else:
+ config = read_yaml(DEFAULT_CFG_PATH)
+ config = update_model_path(config)
+
+ if kwargs:
+ updater = UpdateParameters()
+ config = updater(config, **kwargs)
+
+ 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"]
+
+ self.use_det = global_config["use_det"]
+ self.text_det = TextDetector(config["Det"])
+
+ self.use_cls = global_config["use_cls"]
+ self.text_cls = TextClassifier(config["Cls"])
+
+ self.use_rec = global_config["use_rec"]
+ self.text_rec = TextRecognizer(config["Rec"])
+
+ self.load_img = LoadImage()
+ self.max_side_len = global_config["max_side_len"]
+ self.min_side_len = global_config["min_side_len"]
+
+ self.cal_rec_boxes = CalRecBoxes()
+
+ def __call__(
+ self,
+ img_content: Union[str, np.ndarray, bytes, Path],
+ use_det: Optional[bool] = None,
+ use_cls: Optional[bool] = None,
+ use_rec: Optional[bool] = None,
+ **kwargs,
+ ) -> Tuple[Optional[List[List[Union[Any, str]]]], Optional[List[float]]]:
+ use_det = self.use_det if use_det is None else use_det
+ use_cls = self.use_cls if use_cls is None else use_cls
+ use_rec = self.use_rec if use_rec is None else use_rec
+ return_word_box = False
+ if kwargs:
+ box_thresh = kwargs.get("box_thresh", 0.5)
+ unclip_ratio = kwargs.get("unclip_ratio", 1.6)
+ text_score = kwargs.get("text_score", 0.5)
+ return_word_box = kwargs.get("return_word_box", False)
+ self.text_det.postprocess_op.box_thresh = box_thresh
+ self.text_det.postprocess_op.unclip_ratio = unclip_ratio
+ self.text_score = text_score
+
+ self.return_word_box = return_word_box
+
+ img = self.load_img(img_content)
+
+ raw_h, raw_w = img.shape[:2]
+ op_record = {}
+ img, ratio_h, ratio_w = self.preprocess(img)
+ op_record["preprocess"] = {"ratio_h": ratio_h, "ratio_w": ratio_w}
+
+ dt_boxes, cls_res, rec_res = None, None, None
+ det_elapse, cls_elapse, rec_elapse = 0.0, 0.0, 0.0
+
+ if use_det:
+ img, op_record = self.maybe_add_letterbox(img, op_record)
+ dt_boxes, det_elapse = self.auto_text_det(img)
+ if dt_boxes is None:
+ return None, None
+
+ img = self.get_crop_img_list(img, dt_boxes)
+
+ if use_cls:
+ img, cls_res, cls_elapse = self.text_cls(img)
+
+ if use_rec:
+ rec_res = self.text_rec(img, return_word_box)
+
+ if return_word_box and dt_boxes is not None and all(rec_res.word_results):
+ rec_res = self.cal_rec_boxes(img, dt_boxes, rec_res)
+ for rec_res_i in rec_res.word_results:
+ if rec_res_i[2]:
+ rec_res_i[2] = (
+ self._get_origin_points([rec_res_i[2]], op_record, raw_h, raw_w)
+ .astype(np.int32)
+ .tolist()
+ )
+
+ if dt_boxes is not None:
+ dt_boxes = self._get_origin_points(dt_boxes, op_record, raw_h, raw_w)
+
+ ocr_res = self.get_final_res(
+ # dt_boxes, cls_res, rec_res, det_elapse, cls_elapse, rec_elapse
+ dt_boxes,
+ cls_res,
+ rec_res,
+ det_elapse,
+ cls_elapse,
+ )
+ return ocr_res
+
+ def preprocess(self, img: np.ndarray) -> Tuple[np.ndarray, float, float]:
+ h, w = img.shape[:2]
+ max_value = max(h, w)
+ ratio_h = ratio_w = 1.0
+ if max_value > self.max_side_len:
+ img, ratio_h, ratio_w = reduce_max_side(img, self.max_side_len)
+
+ h, w = img.shape[:2]
+ min_value = min(h, w)
+ if min_value < self.min_side_len:
+ img, ratio_h, ratio_w = increase_min_side(img, self.min_side_len)
+ return img, ratio_h, ratio_w
+
+ def maybe_add_letterbox(
+ self, img: np.ndarray, op_record: Dict[str, Any]
+ ) -> Tuple[np.ndarray, Dict[str, Any]]:
+ h, w = img.shape[:2]
+
+ if self.width_height_ratio == -1:
+ use_limit_ratio = False
+ else:
+ use_limit_ratio = w / h > self.width_height_ratio
+
+ if h <= self.min_height or use_limit_ratio:
+ padding_h = self._get_padding_h(h, w)
+ block_img = add_round_letterbox(img, (padding_h, padding_h, 0, 0))
+ op_record["padding_1"] = {"top": padding_h, "left": 0}
+ return block_img, op_record
+
+ op_record["padding_1"] = {"top": 0, "left": 0}
+ return img, op_record
+
+ def _get_padding_h(self, h: int, w: int) -> int:
+ new_h = max(int(w / self.width_height_ratio), self.min_height) * 2
+ padding_h = int(abs(new_h - h) / 2)
+ return padding_h
+
+ def auto_text_det(
+ self, img: np.ndarray
+ ) -> Tuple[Optional[List[np.ndarray]], float]:
+ dt_boxes, det_elapse = self.text_det(img)
+ if dt_boxes is None or len(dt_boxes) < 1:
+ return None, 0.0
+
+ dt_boxes = self.sorted_boxes(dt_boxes)
+ return dt_boxes, det_elapse
+
+ def get_crop_img_list(
+ self, img: np.ndarray, dt_boxes: List[np.ndarray]
+ ) -> List[np.ndarray]:
+ def get_rotate_crop_image(img: np.ndarray, points: np.ndarray) -> np.ndarray:
+ 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.array(
+ [
+ [0, 0],
+ [img_crop_width, 0],
+ [img_crop_width, img_crop_height],
+ [0, img_crop_height],
+ ]
+ ).astype(np.float32)
+ 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: np.ndarray) -> List[np.ndarray]:
+ """
+ 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):
+ for j in range(i, -1, -1):
+ if (
+ abs(_boxes[j + 1][0][1] - _boxes[j][0][1]) < 10
+ and _boxes[j + 1][0][0] < _boxes[j][0][0]
+ ):
+ tmp = _boxes[j]
+ _boxes[j] = _boxes[j + 1]
+ _boxes[j + 1] = tmp
+ else:
+ break
+ return _boxes
+
+ def _get_origin_points(
+ self,
+ dt_boxes: List[np.ndarray],
+ op_record: Dict[str, Any],
+ raw_h: int,
+ raw_w: int,
+ ) -> np.ndarray:
+ dt_boxes_array = np.array(dt_boxes).astype(np.float32)
+ for op in reversed(list(op_record.keys())):
+ v = op_record[op]
+ if "padding" in op:
+ top, left = v.get("top"), v.get("left")
+ dt_boxes_array[:, :, 0] -= left
+ dt_boxes_array[:, :, 1] -= top
+ elif "preprocess" in op:
+ ratio_h = v.get("ratio_h")
+ ratio_w = v.get("ratio_w")
+ dt_boxes_array[:, :, 0] *= ratio_w
+ dt_boxes_array[:, :, 1] *= ratio_h
+
+ dt_boxes_array = np.where(dt_boxes_array < 0, 0, dt_boxes_array)
+ dt_boxes_array[..., 0] = np.where(
+ dt_boxes_array[..., 0] > raw_w, raw_w, dt_boxes_array[..., 0]
+ )
+ dt_boxes_array[..., 1] = np.where(
+ dt_boxes_array[..., 1] > raw_h, raw_h, dt_boxes_array[..., 1]
+ )
+ return dt_boxes_array
+
+ def get_final_res(
+ self,
+ dt_boxes: Optional[List[np.ndarray]],
+ cls_res: Optional[List[List[Union[str, float]]]],
+ rec_res: TextRecognizerOutput,
+ det_elapse: float,
+ cls_elapse: float,
+ ) -> Tuple[Optional[List[List[Union[Any, str]]]], Optional[List[float]]]:
+ if dt_boxes is None and rec_res is None and cls_res is not None:
+ return cls_res, [cls_elapse]
+
+ if dt_boxes is None and rec_res is None:
+ return None, None
+
+ if dt_boxes is None and rec_res is not None:
+ return [[v[0], v[1]] for v in rec_res.line_results], [rec_res.elapse]
+
+ if dt_boxes is not None and rec_res is None:
+ return [box.tolist() for box in dt_boxes], [det_elapse]
+
+ dt_boxes, rec_res = self.filter_result(dt_boxes, rec_res)
+ if not dt_boxes or not rec_res or len(dt_boxes) <= 0:
+ return None, None
+
+ ocr_res = [
+ [box.tolist(), *res] for box, res in zip(dt_boxes, rec_res.line_results)
+ ], [
+ det_elapse,
+ cls_elapse,
+ rec_res.elapse,
+ ]
+ return ocr_res
+
+ def filter_result(
+ self,
+ dt_boxes: Optional[List[np.ndarray]],
+ rec_res: Optional[List[Tuple[str, float]]],
+ ) -> Tuple[Optional[List[np.ndarray]], TextRecognizerOutput]:
+ if dt_boxes is None or rec_res is None:
+ return None, None
+
+ filter_boxes, filter_rec_res = [], []
+ for box, rec_reuslt in zip(dt_boxes, rec_res.line_results):
+ text, score = rec_reuslt[0], rec_reuslt[1]
+ if float(score) >= self.text_score:
+ filter_boxes.append(box)
+ filter_rec_res.append(rec_reuslt)
+
+ rec_res.line_results = filter_rec_res
+ return filter_boxes, rec_res
+
+
+def main():
+ args = init_args()
+ ocr_engine = RapidOCR(**vars(args))
+
+ use_det = not args.no_det
+ use_cls = not args.no_cls
+ use_rec = not args.no_rec
+ result, elapse_list = ocr_engine(
+ args.img_path, use_det=use_det, use_cls=use_cls, use_rec=use_rec, **vars(args)
+ )
+ logger.info(result)
+
+ if args.print_cost:
+ logger.info(elapse_list)
+
+ if args.vis_res:
+ vis = VisRes()
+ Path(args.vis_save_path).mkdir(parents=True, exist_ok=True)
+ save_path = Path(args.vis_save_path) / f"{Path(args.img_path).stem}_vis.png"
+
+ if use_det and not use_cls and not use_rec:
+ boxes, *_ = list(zip(*result))
+ vis_img = vis(args.img_path, boxes)
+ cv2.imwrite(str(save_path), vis_img)
+ logger.info("The vis result has saved in %s", save_path)
+
+ elif use_det and use_rec:
+ font_path = Path(args.vis_font_path)
+ if not font_path.exists():
+ raise FileExistsError(f"{font_path} does not exist!")
+
+ boxes, txts, scores = list(zip(*result))
+ vis_img = vis(args.img_path, boxes, txts, scores, font_path=font_path)
+ cv2.imwrite(str(save_path), vis_img)
+ logger.info("The vis result has saved in %s", save_path)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python/rapidocr/models/.gitkeep b/python/rapidocr/models/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/python/rapidocr/utils/__init__.py b/python/rapidocr/utils/__init__.py
new file mode 100644
index 0000000..150da63
--- /dev/null
+++ b/python/rapidocr/utils/__init__.py
@@ -0,0 +1,20 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from pathlib import Path
+from typing import Dict, Union
+
+import yaml
+
+from .infer_engine import OrtInferSession
+from .load_image import LoadImage, LoadImageError
+from .logger import get_logger
+from .parse_parameters import UpdateParameters, init_args, update_model_path
+from .process_img import add_round_letterbox, increase_min_side, reduce_max_side
+from .vis_res import VisRes
+
+
+def read_yaml(yaml_path: Union[str, Path]) -> Dict[str, Dict]:
+ with open(yaml_path, "rb") as f:
+ data = yaml.load(f, Loader=yaml.Loader)
+ return data
diff --git a/python/rapidocr/utils/infer_engine.py b/python/rapidocr/utils/infer_engine.py
new file mode 100644
index 0000000..fb1fd35
--- /dev/null
+++ b/python/rapidocr/utils/infer_engine.py
@@ -0,0 +1,231 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import os
+import platform
+import traceback
+from enum import Enum
+from pathlib import Path
+from typing import Any, Dict, List, Tuple, Union
+
+import numpy as np
+from onnxruntime import (
+ GraphOptimizationLevel,
+ InferenceSession,
+ SessionOptions,
+ get_available_providers,
+ get_device,
+)
+
+from .logger import get_logger
+
+
+class EP(Enum):
+ CPU_EP = "CPUExecutionProvider"
+ CUDA_EP = "CUDAExecutionProvider"
+ DIRECTML_EP = "DmlExecutionProvider"
+
+
+class OrtInferSession:
+ def __init__(self, config: Dict[str, Any]):
+ self.logger = get_logger("OrtInferSession")
+
+ model_path = config.get("model_path", None)
+ self._verify_model(model_path)
+
+ self.cfg_use_cuda = config.get("use_cuda", None)
+ self.cfg_use_dml = config.get("use_dml", None)
+
+ self.had_providers: List[str] = get_available_providers()
+ EP_list = self._get_ep_list()
+
+ sess_opt = self._init_sess_opts(config)
+ self.session = InferenceSession(
+ model_path,
+ sess_options=sess_opt,
+ providers=EP_list,
+ )
+ self._verify_providers()
+
+ @staticmethod
+ def _init_sess_opts(config: Dict[str, Any]) -> SessionOptions:
+ sess_opt = SessionOptions()
+ sess_opt.log_severity_level = 4
+ sess_opt.enable_cpu_mem_arena = False
+ sess_opt.graph_optimization_level = GraphOptimizationLevel.ORT_ENABLE_ALL
+
+ cpu_nums = os.cpu_count()
+ intra_op_num_threads = config.get("intra_op_num_threads", -1)
+ if intra_op_num_threads != -1 and 1 <= intra_op_num_threads <= cpu_nums:
+ sess_opt.intra_op_num_threads = intra_op_num_threads
+
+ inter_op_num_threads = config.get("inter_op_num_threads", -1)
+ if inter_op_num_threads != -1 and 1 <= inter_op_num_threads <= cpu_nums:
+ sess_opt.inter_op_num_threads = inter_op_num_threads
+
+ return sess_opt
+
+ def _get_ep_list(self) -> List[Tuple[str, Dict[str, Any]]]:
+ cpu_provider_opts = {
+ "arena_extend_strategy": "kSameAsRequested",
+ }
+ EP_list = [(EP.CPU_EP.value, cpu_provider_opts)]
+
+ cuda_provider_opts = {
+ "device_id": 0,
+ "arena_extend_strategy": "kNextPowerOfTwo",
+ "cudnn_conv_algo_search": "EXHAUSTIVE",
+ "do_copy_in_default_stream": True,
+ }
+ self.use_cuda = self._check_cuda()
+ if self.use_cuda:
+ EP_list.insert(0, (EP.CUDA_EP.value, cuda_provider_opts))
+
+ self.use_directml = self._check_dml()
+ if self.use_directml:
+ self.logger.info(
+ "Windows 10 or above detected, try to use DirectML as primary provider"
+ )
+ directml_options = (
+ cuda_provider_opts if self.use_cuda else cpu_provider_opts
+ )
+ EP_list.insert(0, (EP.DIRECTML_EP.value, directml_options))
+ return EP_list
+
+ def _check_cuda(self) -> bool:
+ if not self.cfg_use_cuda:
+ return False
+
+ cur_device = get_device()
+ if cur_device == "GPU" and EP.CUDA_EP.value in self.had_providers:
+ return True
+
+ self.logger.warning(
+ "%s is not in available providers (%s). Use %s inference by default.",
+ EP.CUDA_EP.value,
+ self.had_providers,
+ self.had_providers[0],
+ )
+ self.logger.info("!!!Recommend to use rapidocr_paddle for inference on GPU.")
+ self.logger.info(
+ "(For reference only) If you want to use GPU acceleration, you must do:"
+ )
+ self.logger.info(
+ "First, uninstall all onnxruntime pakcages in current environment."
+ )
+ self.logger.info(
+ "Second, install onnxruntime-gpu by `pip install onnxruntime-gpu`."
+ )
+ self.logger.info(
+ "\tNote the onnxruntime-gpu version must match your cuda and cudnn version."
+ )
+ self.logger.info(
+ "\tYou can refer this link: https://onnxruntime.ai/docs/execution-providers/CUDA-EP.html"
+ )
+ self.logger.info(
+ "Third, ensure %s is in available providers list. e.g. ['CUDAExecutionProvider', 'CPUExecutionProvider']",
+ EP.CUDA_EP.value,
+ )
+ return False
+
+ def _check_dml(self) -> bool:
+ if not self.cfg_use_dml:
+ return False
+
+ cur_os = platform.system()
+ if cur_os != "Windows":
+ self.logger.warning(
+ "DirectML is only supported in Windows OS. The current OS is %s. Use %s inference by default.",
+ cur_os,
+ self.had_providers[0],
+ )
+ return False
+
+ cur_window_version = int(platform.release().split(".")[0])
+ if cur_window_version < 10:
+ self.logger.warning(
+ "DirectML is only supported in Windows 10 and above OS. The current Windows version is %s. Use %s inference by default.",
+ cur_window_version,
+ self.had_providers[0],
+ )
+ return False
+
+ if EP.DIRECTML_EP.value in self.had_providers:
+ return True
+
+ self.logger.warning(
+ "%s is not in available providers (%s). Use %s inference by default.",
+ EP.DIRECTML_EP.value,
+ self.had_providers,
+ self.had_providers[0],
+ )
+ self.logger.info("If you want to use DirectML acceleration, you must do:")
+ self.logger.info(
+ "First, uninstall all onnxruntime pakcages in current environment."
+ )
+ self.logger.info(
+ "Second, install onnxruntime-directml by `pip install onnxruntime-directml`"
+ )
+ self.logger.info(
+ "Third, ensure %s is in available providers list. e.g. ['DmlExecutionProvider', 'CPUExecutionProvider']",
+ EP.DIRECTML_EP.value,
+ )
+ return False
+
+ def _verify_providers(self):
+ session_providers = self.session.get_providers()
+ first_provider = session_providers[0]
+
+ if self.use_cuda and first_provider != EP.CUDA_EP.value:
+ self.logger.warning(
+ "%s is not avaiable for current env, the inference part is automatically shifted to be executed under %s.",
+ EP.CUDA_EP.value,
+ first_provider,
+ )
+
+ if self.use_directml and first_provider != EP.DIRECTML_EP.value:
+ self.logger.warning(
+ "%s is not available for current env, the inference part is automatically shifted to be executed under %s.",
+ EP.DIRECTML_EP.value,
+ first_provider,
+ )
+
+ def __call__(self, input_content: np.ndarray) -> np.ndarray:
+ input_dict = dict(zip(self.get_input_names(), [input_content]))
+ try:
+ return self.session.run(self.get_output_names(), input_dict)
+ except Exception as e:
+ error_info = traceback.format_exc()
+ raise ONNXRuntimeError(error_info) from e
+
+ def get_input_names(self) -> List[str]:
+ return [v.name for v in self.session.get_inputs()]
+
+ def get_output_names(self) -> List[str]:
+ return [v.name for v in self.session.get_outputs()]
+
+ def get_character_list(self, key: str = "character") -> List[str]:
+ meta_dict = self.session.get_modelmeta().custom_metadata_map
+ return meta_dict[key].splitlines()
+
+ def have_key(self, key: str = "character") -> bool:
+ meta_dict = self.session.get_modelmeta().custom_metadata_map
+ if key in meta_dict.keys():
+ return True
+ return False
+
+ @staticmethod
+ def _verify_model(model_path: Union[str, Path, None]):
+ if model_path is None:
+ raise ValueError("model_path is None!")
+
+ model_path = Path(model_path)
+ if not model_path.exists():
+ raise FileNotFoundError(f"{model_path} does not exists.")
+
+ if not model_path.is_file():
+ raise FileExistsError(f"{model_path} is not a file.")
+
+
+class ONNXRuntimeError(Exception):
+ pass
diff --git a/python/rapidocr/utils/load_image.py b/python/rapidocr/utils/load_image.py
new file mode 100644
index 0000000..f34b549
--- /dev/null
+++ b/python/rapidocr/utils/load_image.py
@@ -0,0 +1,123 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from io import BytesIO
+from pathlib import Path
+from typing import Any, Union
+
+import cv2
+import numpy as np
+from PIL import Image, UnidentifiedImageError
+
+root_dir = Path(__file__).resolve().parent
+InputType = Union[str, np.ndarray, bytes, Path, Image.Image]
+
+
+class LoadImage:
+ def __init__(self):
+ pass
+
+ def __call__(self, img: InputType) -> np.ndarray:
+ if not isinstance(img, InputType.__args__):
+ raise LoadImageError(
+ f"The img type {type(img)} does not in {InputType.__args__}"
+ )
+
+ origin_img_type = type(img)
+ img = self.load_img(img)
+ img = self.convert_img(img, origin_img_type)
+ return img
+
+ def load_img(self, img: InputType) -> np.ndarray:
+ if isinstance(img, (str, Path)):
+ self.verify_exist(img)
+ try:
+ img = self.img_to_ndarray(Image.open(img))
+ except UnidentifiedImageError as e:
+ raise LoadImageError(f"cannot identify image file {img}") from e
+ return img
+
+ if isinstance(img, bytes):
+ img = self.img_to_ndarray(Image.open(BytesIO(img)))
+ return img
+
+ if isinstance(img, np.ndarray):
+ return img
+
+ if isinstance(img, Image.Image):
+ return self.img_to_ndarray(img)
+
+ raise LoadImageError(f"{type(img)} is not supported!")
+
+ def img_to_ndarray(self, img: Image.Image) -> np.ndarray:
+ if img.mode == "1":
+ img = img.convert("L")
+ return np.array(img)
+ return np.array(img)
+
+ def convert_img(self, img: np.ndarray, origin_img_type: Any) -> np.ndarray:
+ if img.ndim == 2:
+ return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
+
+ if img.ndim == 3:
+ channel = img.shape[2]
+ if channel == 1:
+ return cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
+
+ if channel == 2:
+ return self.cvt_two_to_three(img)
+
+ if channel == 3:
+ if issubclass(origin_img_type, (str, Path, bytes, Image.Image)):
+ return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
+ return img
+
+ if channel == 4:
+ return self.cvt_four_to_three(img)
+
+ raise LoadImageError(
+ f"The channel({channel}) of the img is not in [1, 2, 3, 4]"
+ )
+
+ raise LoadImageError(f"The ndim({img.ndim}) of the img is not in [2, 3]")
+
+ @staticmethod
+ def cvt_two_to_three(img: np.ndarray) -> np.ndarray:
+ """gray + alpha → BGR"""
+ img_gray = img[..., 0]
+ img_bgr = cv2.cvtColor(img_gray, cv2.COLOR_GRAY2BGR)
+
+ img_alpha = img[..., 1]
+ not_a = cv2.bitwise_not(img_alpha)
+ not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
+
+ new_img = cv2.bitwise_and(img_bgr, img_bgr, mask=img_alpha)
+ new_img = cv2.add(new_img, not_a)
+ return new_img
+
+ @staticmethod
+ def cvt_four_to_three(img: np.ndarray) -> np.ndarray:
+ """RGBA → BGR"""
+ r, g, b, a = cv2.split(img)
+ new_img = cv2.merge((b, g, r))
+
+ not_a = cv2.bitwise_not(a)
+ not_a = cv2.cvtColor(not_a, cv2.COLOR_GRAY2BGR)
+
+ new_img = cv2.bitwise_and(new_img, new_img, mask=a)
+
+ mean_color = np.mean(new_img)
+ if mean_color <= 0.0:
+ new_img = cv2.add(new_img, not_a)
+ else:
+ new_img = cv2.bitwise_not(new_img)
+ return new_img
+
+ @staticmethod
+ def verify_exist(file_path: Union[str, Path]):
+ if not Path(file_path).exists():
+ raise LoadImageError(f"{file_path} does not exist.")
+
+
+class LoadImageError(Exception):
+ pass
diff --git a/python/rapidocr/utils/logger.py b/python/rapidocr/utils/logger.py
new file mode 100644
index 0000000..66522c4
--- /dev/null
+++ b/python/rapidocr/utils/logger.py
@@ -0,0 +1,21 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import logging
+from functools import lru_cache
+
+
+@lru_cache(maxsize=32)
+def get_logger(name: str) -> logging.Logger:
+ logger = logging.getLogger(name)
+ logger.setLevel(logging.DEBUG)
+
+ fmt = "%(asctime)s - %(name)s - %(levelname)s: %(message)s"
+ format_str = logging.Formatter(fmt)
+
+ sh = logging.StreamHandler()
+ sh.setLevel(logging.DEBUG)
+
+ logger.addHandler(sh)
+ sh.setFormatter(format_str)
+ return logger
diff --git a/python/rapidocr/utils/parse_parameters.py b/python/rapidocr/utils/parse_parameters.py
new file mode 100644
index 0000000..4d0fa90
--- /dev/null
+++ b/python/rapidocr/utils/parse_parameters.py
@@ -0,0 +1,196 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import argparse
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+
+import numpy as np
+from PIL import Image
+
+root_dir = Path(__file__).resolve().parent.parent
+InputType = Union[str, np.ndarray, bytes, Path, Image.Image]
+
+
+def update_model_path(config: Dict[str, Any]) -> Dict[str, Any]:
+ key = "model_path"
+ config["Det"][key] = str(root_dir / config["Det"][key])
+ config["Rec"][key] = str(root_dir / config["Rec"][key])
+ config["Cls"][key] = str(root_dir / config["Cls"][key])
+ return config
+
+
+def init_args():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("-img", "--img_path", type=str, default=None, required=True)
+ parser.add_argument("-p", "--print_cost", action="store_true", default=False)
+
+ global_group = parser.add_argument_group(title="Global")
+ global_group.add_argument("--text_score", type=float, default=0.5)
+
+ global_group.add_argument("--no_det", action="store_true", default=False)
+ global_group.add_argument("--no_cls", action="store_true", default=False)
+ global_group.add_argument("--no_rec", action="store_true", default=False)
+
+ global_group.add_argument("--print_verbose", action="store_true", default=False)
+ global_group.add_argument("--min_height", type=int, default=30)
+ global_group.add_argument("--width_height_ratio", type=int, default=8)
+ global_group.add_argument("--max_side_len", type=int, default=2000)
+ global_group.add_argument("--min_side_len", type=int, default=30)
+ global_group.add_argument("--return_word_box", action="store_true", default=False)
+
+ global_group.add_argument("--intra_op_num_threads", type=int, default=-1)
+ global_group.add_argument("--inter_op_num_threads", type=int, default=-1)
+
+ det_group = parser.add_argument_group(title="Det")
+ det_group.add_argument("--det_use_cuda", action="store_true", default=False)
+ det_group.add_argument("--det_use_dml", action="store_true", default=False)
+ det_group.add_argument("--det_model_path", type=str, default=None)
+ det_group.add_argument("--det_limit_side_len", type=float, default=736)
+ det_group.add_argument(
+ "--det_limit_type", type=str, default="min", choices=["max", "min"]
+ )
+ det_group.add_argument("--det_thresh", type=float, default=0.3)
+ det_group.add_argument("--det_box_thresh", type=float, default=0.5)
+ det_group.add_argument("--det_unclip_ratio", type=float, default=1.6)
+ det_group.add_argument(
+ "--det_donot_use_dilation", action="store_true", default=False
+ )
+ det_group.add_argument(
+ "--det_score_mode", type=str, default="fast", choices=["slow", "fast"]
+ )
+
+ cls_group = parser.add_argument_group(title="Cls")
+ cls_group.add_argument("--cls_use_cuda", action="store_true", default=False)
+ cls_group.add_argument("--cls_use_dml", action="store_true", default=False)
+ cls_group.add_argument("--cls_model_path", type=str, default=None)
+ cls_group.add_argument("--cls_image_shape", type=list, default=[3, 48, 192])
+ cls_group.add_argument("--cls_label_list", type=list, default=["0", "180"])
+ cls_group.add_argument("--cls_batch_num", type=int, default=6)
+ cls_group.add_argument("--cls_thresh", type=float, default=0.9)
+
+ rec_group = parser.add_argument_group(title="Rec")
+ rec_group.add_argument("--rec_use_cuda", action="store_true", default=False)
+ rec_group.add_argument("--rec_use_dml", action="store_true", default=False)
+ rec_group.add_argument("--rec_model_path", type=str, default=None)
+ rec_group.add_argument("--rec_keys_path", type=str, default=None)
+ rec_group.add_argument("--rec_img_shape", type=list, default=[3, 48, 320])
+ rec_group.add_argument("--rec_batch_num", type=int, default=6)
+
+ vis_group = parser.add_argument_group(title="Visual Result")
+ vis_group.add_argument("-vis", "--vis_res", action="store_true", default=False)
+ vis_group.add_argument(
+ "--vis_font_path",
+ type=str,
+ default=None,
+ help="When -vis is True, the font_path must have value.",
+ )
+ vis_group.add_argument(
+ "--vis_save_path",
+ type=str,
+ default=".",
+ help="The directory of saving the vis image.",
+ )
+
+ args = parser.parse_args()
+ return args
+
+
+class UpdateParameters:
+ def __init__(self) -> None:
+ pass
+
+ def parse_kwargs(self, **kwargs):
+ global_dict, det_dict, cls_dict, rec_dict = {}, {}, {}, {}
+ for k, v in kwargs.items():
+ if k.startswith("det"):
+ k = k.split("det_")[1]
+ if k == "donot_use_dilation":
+ k = "use_dilation"
+ v = not v
+
+ det_dict[k] = v
+ elif k.startswith("cls"):
+ cls_dict[k] = v
+ elif k.startswith("rec"):
+ rec_dict[k] = v
+ else:
+ global_dict[k] = v
+ return global_dict, det_dict, cls_dict, rec_dict
+
+ def __call__(self, config, **kwargs):
+ global_dict, det_dict, cls_dict, rec_dict = self.parse_kwargs(**kwargs)
+ new_config = {
+ "Global": self.update_global_params(config["Global"], global_dict),
+ "Det": self.update_params(
+ config["Det"],
+ det_dict,
+ "det_",
+ ["det_model_path", "det_use_cuda", "det_use_dml"],
+ ),
+ "Cls": self.update_params(
+ config["Cls"],
+ cls_dict,
+ "cls_",
+ ["cls_label_list", "cls_model_path", "cls_use_cuda", "cls_use_dml"],
+ ),
+ "Rec": self.update_params(
+ config["Rec"],
+ rec_dict,
+ "rec_",
+ ["rec_model_path", "rec_use_cuda", "rec_use_dml"],
+ ),
+ }
+
+ update_params = ["intra_op_num_threads", "inter_op_num_threads"]
+ new_config = self.update_global_to_module(
+ config, update_params, src="Global", dsts=["Det", "Cls", "Rec"]
+ )
+ return new_config
+
+ def update_global_to_module(
+ self, config, params: List[str], src: str, dsts: List[str]
+ ):
+ for dst in dsts:
+ for param in params:
+ config[dst].update({param: config[src][param]})
+ return config
+
+ def update_global_params(self, config, global_dict):
+ if global_dict:
+ config.update(global_dict)
+ return config
+
+ def update_params(
+ self,
+ config,
+ param_dict: Dict[str, str],
+ prefix: str,
+ need_remove_prefix: Optional[List[str]] = None,
+ ):
+ if not param_dict:
+ return config
+
+ filter_dict = self.remove_prefix(param_dict, prefix, need_remove_prefix)
+ model_path = filter_dict.get("model_path", None)
+ if not model_path:
+ filter_dict["model_path"] = str(root_dir / config["model_path"])
+
+ config.update(filter_dict)
+ return config
+
+ @staticmethod
+ def remove_prefix(
+ config: Dict[str, str],
+ prefix: str,
+ need_remove_prefix: Optional[List[str]] = None,
+ ) -> Dict[str, str]:
+ if not need_remove_prefix:
+ return config
+
+ new_rec_dict = {}
+ for k, v in config.items():
+ if k in need_remove_prefix:
+ k = k.split(prefix)[1]
+ new_rec_dict[k] = v
+ return new_rec_dict
diff --git a/python/rapidocr/utils/process_img.py b/python/rapidocr/utils/process_img.py
new file mode 100644
index 0000000..7d3e194
--- /dev/null
+++ b/python/rapidocr/utils/process_img.py
@@ -0,0 +1,87 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+from typing import Tuple
+
+import cv2
+import numpy as np
+
+
+def reduce_max_side(
+ img: np.ndarray, max_side_len: int = 2000
+) -> Tuple[np.ndarray, float, float]:
+ h, w = img.shape[:2]
+
+ ratio = 1.0
+ if max(h, w) > max_side_len:
+ if h > w:
+ ratio = float(max_side_len) / h
+ else:
+ ratio = float(max_side_len) / w
+
+ 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:
+ raise ResizeImgError("resize_w or resize_h is less than or equal to 0")
+ img = cv2.resize(img, (resize_w, resize_h))
+ except Exception as exc:
+ raise ResizeImgError() from exc
+
+ ratio_h = h / resize_h
+ ratio_w = w / resize_w
+ return img, ratio_h, ratio_w
+
+
+def increase_min_side(
+ img: np.ndarray, min_side_len: int = 30
+) -> Tuple[np.ndarray, float, float]:
+ h, w = img.shape[:2]
+
+ ratio = 1.0
+ if min(h, w) < min_side_len:
+ if h < w:
+ ratio = float(min_side_len) / h
+ else:
+ ratio = float(min_side_len) / w
+
+ 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:
+ raise ResizeImgError("resize_w or resize_h is less than or equal to 0")
+ img = cv2.resize(img, (resize_w, resize_h))
+ except Exception as exc:
+ raise ResizeImgError() from exc
+
+ ratio_h = h / resize_h
+ ratio_w = w / resize_w
+ return img, ratio_h, ratio_w
+
+
+def add_round_letterbox(
+ img: np.ndarray,
+ padding_tuple: Tuple[int, int, int, int],
+) -> np.ndarray:
+ padded_img = cv2.copyMakeBorder(
+ img,
+ padding_tuple[0],
+ padding_tuple[1],
+ padding_tuple[2],
+ padding_tuple[3],
+ cv2.BORDER_CONSTANT,
+ value=(0, 0, 0),
+ )
+ return padded_img
+
+
+class ResizeImgError(Exception):
+ pass
diff --git a/python/rapidocr/utils/vis_res.py b/python/rapidocr/utils/vis_res.py
new file mode 100644
index 0000000..bd18031
--- /dev/null
+++ b/python/rapidocr/utils/vis_res.py
@@ -0,0 +1,143 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import math
+import random
+from pathlib import Path
+from typing import List, Optional, Tuple, Union
+
+import cv2
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+from .load_image import LoadImage
+
+root_dir = Path(__file__).resolve().parent
+InputType = Union[str, np.ndarray, bytes, Path, Image.Image]
+
+
+class VisRes:
+ def __init__(self, text_score: float = 0.5):
+ self.text_score = text_score
+ self.load_img = LoadImage()
+
+ def __call__(
+ self,
+ img_content: InputType,
+ dt_boxes: np.ndarray,
+ txts: Optional[Union[List[str], Tuple[str]]] = None,
+ scores: Optional[Tuple[float]] = None,
+ font_path: Optional[str] = None,
+ ) -> np.ndarray:
+ if txts is None:
+ return self.draw_dt_boxes(img_content, dt_boxes)
+ return self.draw_ocr_box_txt(img_content, dt_boxes, txts, scores, font_path)
+
+ def draw_dt_boxes(self, img_content: InputType, dt_boxes: np.ndarray) -> np.ndarray:
+ img = self.load_img(img_content)
+
+ for idx, box in enumerate(dt_boxes):
+ color = self.get_random_color()
+
+ points = np.array(box)
+ cv2.polylines(img, np.int32([points]), 1, color=color, thickness=1)
+
+ start_point = round(points[0][0]), round(points[0][1])
+ cv2.putText(
+ img, f"{idx}", start_point, cv2.FONT_HERSHEY_SIMPLEX, 1, color, 3
+ )
+ return img
+
+ def draw_ocr_box_txt(
+ self,
+ img_content: InputType,
+ dt_boxes: np.ndarray,
+ txts: Union[List[str], Tuple[str]],
+ scores: Optional[Tuple[float]] = None,
+ font_path: Optional[str] = None,
+ ) -> np.ndarray:
+ font_path = self.get_font_path(font_path)
+
+ image = Image.fromarray(self.load_img(img_content))
+ h, w = image.height, image.width
+ if image.mode == "L":
+ image = image.convert("RGB")
+
+ img_left = image.copy()
+ img_right = Image.new("RGB", (w, h), (255, 255, 255))
+
+ random.seed(0)
+ draw_left = ImageDraw.Draw(img_left)
+ draw_right = ImageDraw.Draw(img_right)
+ for idx, (box, txt) in enumerate(zip(dt_boxes, txts)):
+ if scores is not None and float(scores[idx]) < self.text_score:
+ continue
+
+ color = self.get_random_color()
+
+ box_list = np.array(box).reshape(8).tolist()
+ draw_left.polygon(box_list, fill=color)
+ draw_right.polygon(box_list, outline=color)
+
+ box_height = self.get_box_height(box)
+ box_width = self.get_box_width(box)
+ if box_height > 2 * box_width:
+ font_size = max(int(box_width * 0.9), 10)
+ font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
+ cur_y = box[0][1]
+
+ for c in txt:
+ draw_right.text(
+ (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font
+ )
+ cur_y += self.get_char_size(font, c)
+ else:
+ font_size = max(int(box_height * 0.8), 10)
+ font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
+ draw_right.text([box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)
+
+ img_left = Image.blend(image, img_left, 0.5)
+ img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
+ img_show.paste(img_left, (0, 0, w, h))
+ img_show.paste(img_right, (w, 0, w * 2, h))
+ return np.array(img_show)
+
+ @staticmethod
+ def get_font_path(font_path: Optional[Union[str, Path]] = None) -> str:
+ if font_path is None or not Path(font_path).exists():
+ raise FileNotFoundError(
+ f"The {font_path} does not exists! \n"
+ f"You could download the file in the https://drive.google.com/file/d/1evWVX38EFNwTq_n5gTFgnlv8tdaNcyIA/view?usp=sharing"
+ )
+ return str(font_path)
+
+ @staticmethod
+ def get_random_color() -> Tuple[int, int, int]:
+ return (
+ random.randint(0, 255),
+ random.randint(0, 255),
+ random.randint(0, 255),
+ )
+
+ @staticmethod
+ def get_box_height(box: List[List[float]]) -> float:
+ return math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
+
+ @staticmethod
+ def get_box_width(box: List[List[float]]) -> float:
+ return math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
+
+ @staticmethod
+ def get_char_size(font, char_str: str) -> float:
+ # compatible with Pillow v9 and v10.
+ if hasattr(font, "getsize"):
+ get_size_func = getattr(font, "getsize")
+ return get_size_func(char_str)[1]
+
+ if hasattr(font, "getlength"):
+ get_size_func = getattr(font, "getlength")
+ return get_size_func(char_str)
+
+ raise ValueError(
+ "The Pillow ImageFont instance has not getsize or getlength func."
+ )
diff --git a/python/rapidocr_onnxruntime/cal_rec_boxes/main.py b/python/rapidocr_onnxruntime/cal_rec_boxes/main.py
index 296997f..c8ea5da 100644
--- a/python/rapidocr_onnxruntime/cal_rec_boxes/main.py
+++ b/python/rapidocr_onnxruntime/cal_rec_boxes/main.py
@@ -3,13 +3,11 @@
# @Contact: [email protected]
import copy
import math
-from typing import List, Optional, Tuple
+from typing import Any, List, Optional, Tuple
import cv2
import numpy as np
-from ..ch_ppocr_rec.utils import TextRecognizerOutput
-
class CalRecBoxes:
"""计算识别文字的汉字单字和英文单词的坐标框。代码借鉴自PaddlePaddle/PaddleOCR和fanqie03/char-detection"""
@@ -21,16 +19,13 @@ class CalRecBoxes:
self,
imgs: Optional[List[np.ndarray]],
dt_boxes: Optional[List[np.ndarray]],
- rec_res: TextRecognizerOutput,
- ) -> TextRecognizerOutput:
- # rec_res = list(zip(rec_res.line_results, rec_res.word_results))
- word_results = []
- for idx, (img, box) in enumerate(zip(imgs, dt_boxes)):
+ rec_res: Optional[List[Any]],
+ ):
+ res = []
+ for img, box, rec_res in zip(imgs, dt_boxes, rec_res):
direction = self.get_box_direction(box)
- rec_txt, rec_conf = rec_res.line_results[idx]
- rec_word_info = rec_res.word_results[idx]
-
+ rec_txt, rec_conf, rec_word_info = rec_res[0], rec_res[1], rec_res[2]
h, w = img.shape[:2]
img_box = np.array([[0, 0], [w, 0], [w, h], [0, h]])
word_box_content_list, word_box_list, conf_list = self.cal_ocr_word_box(
@@ -40,12 +35,10 @@ class CalRecBoxes:
word_box_list = self.reverse_rotate_crop_image(
copy.deepcopy(box), word_box_list, direction
)
- word_results.extend(
- list(zip(word_box_content_list, conf_list, word_box_list))
+ res.append(
+ [rec_txt, rec_conf, word_box_list, word_box_content_list, conf_list]
)
-
- rec_res.word_results = tuple(list(v) for v in word_results)
- return rec_res
+ return res
@staticmethod
def get_box_direction(box: np.ndarray) -> str:
diff --git a/python/rapidocr_onnxruntime/ch_ppocr_rec/__init__.py b/python/rapidocr_onnxruntime/ch_ppocr_rec/__init__.py
index 46477ba..37eafdc 100644
--- a/python/rapidocr_onnxruntime/ch_ppocr_rec/__init__.py
+++ b/python/rapidocr_onnxruntime/ch_ppocr_rec/__init__.py
@@ -1,5 +1,4 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from .main import TextRecognizer
-from .utils import TextRecognizerOutput
+from .text_recognize import TextRecognizer
diff --git a/python/rapidocr_onnxruntime/ch_ppocr_rec/text_recognize.py b/python/rapidocr_onnxruntime/ch_ppocr_rec/text_recognize.py
new file mode 100644
index 0000000..e823ea6
--- /dev/null
+++ b/python/rapidocr_onnxruntime/ch_ppocr_rec/text_recognize.py
@@ -0,0 +1,130 @@
+# 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 typing import Any, Dict, List, Tuple, Union
+
+import cv2
+import numpy as np
+
+from rapidocr_onnxruntime.utils import OrtInferSession, read_yaml
+
+from .utils import CTCLabelDecode
+
+
+class TextRecognizer:
+ def __init__(self, config: Dict[str, Any]):
+ self.session = OrtInferSession(config)
+
+ character = None
+ if self.session.have_key():
+ character = self.session.get_character_list()
+
+ character_path = config.get("rec_keys_path", None)
+ self.postprocess_op = CTCLabelDecode(
+ character=character, character_path=character_path
+ )
+
+ self.rec_batch_num = config["rec_batch_num"]
+ self.rec_image_shape = config["rec_img_shape"]
+
+ def __call__(
+ self,
+ img_list: Union[np.ndarray, List[np.ndarray]],
+ return_word_box: bool = False,
+ ) -> Tuple[List[Tuple[str, float]], float]:
+ 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)
+
+ # Parameter Alignment for PaddleOCR
+ imgC, imgH, imgW = self.rec_image_shape[:3]
+ max_wh_ratio = imgW / imgH
+ wh_ratio_list = []
+ 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)
+ wh_ratio_list.append(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()
+ preds = self.session(norm_img_batch)[0]
+ rec_result = self.postprocess_op(
+ preds,
+ return_word_box,
+ wh_ratio_list=wh_ratio_list,
+ max_wh_ratio=max_wh_ratio,
+ )
+
+ for rno, one_res in enumerate(rec_result):
+ rec_res[indices[beg_img_no + rno]] = one_res
+ elapse += time.time() - starttime
+ return rec_res, elapse
+
+ def resize_norm_img(self, img: np.ndarray, max_wh_ratio: float) -> np.ndarray:
+ img_channel, img_height, img_width = self.rec_image_shape
+ assert img_channel == img.shape[2]
+
+ img_width = int(img_height * max_wh_ratio)
+
+ 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
+
+
+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 result: {rec_res}\t cost: {predict_time}s")
diff --git a/python/rapidocr_onnxruntime/ch_ppocr_rec/utils.py b/python/rapidocr_onnxruntime/ch_ppocr_rec/utils.py
index 9837c90..224b2f8 100644
--- a/python/rapidocr_onnxruntime/ch_ppocr_rec/utils.py
+++ b/python/rapidocr_onnxruntime/ch_ppocr_rec/utils.py
@@ -1,43 +1,12 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
-from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional, Tuple, Union
import numpy as np
-@dataclass
-class TextRecognizerConfig:
- intra_op_num_threads: int = -1
- inter_op_num_threads: int = -1
- use_cuda: bool = False
- use_dml: bool = False
- model_path: Union[str, Path, None] = None
-
- rec_batch_num: int = 6
- rec_img_shape: Tuple[int, int, int] = (3, 48, 320)
- rec_keys_path: Union[str, Path, None] = None
-
-
-@dataclass
-class TextRecognizerInput:
- img_list: Union[np.ndarray, List[np.ndarray]] = field(init=False)
- return_word_box: bool = False
-
- def __pose_init__(self):
- if isinstance(self.img_list, np.ndarray):
- self.img_list = [self.img_list]
-
-
-@dataclass
-class TextRecognizerOutput:
- line_results: Optional[Tuple[List]] = None
- word_results: Optional[List[List]] = None
- elapse: Optional[float] = None
-
-
class CTCLabelDecode:
def __init__(
self,
@@ -49,18 +18,18 @@ class CTCLabelDecode:
def __call__(
self, preds: np.ndarray, return_word_box: bool = False, **kwargs
- ) -> Tuple[List[Tuple[str, float]], List[List]]:
+ ) -> List[Tuple[str, float]]:
preds_idx = preds.argmax(axis=2)
preds_prob = preds.max(axis=2)
- line_results, word_results = self.decode(
+ text = self.decode(
preds_idx, preds_prob, return_word_box, is_remove_duplicate=True
)
if return_word_box:
- for rec_idx, rec in enumerate(word_results):
+ for rec_idx, rec in enumerate(text):
wh_ratio = kwargs["wh_ratio_list"][rec_idx]
max_wh_ratio = kwargs["max_wh_ratio"]
- rec[0] *= wh_ratio / max_wh_ratio
- return line_results, word_results
+ rec[2][0] = rec[2][0] * (wh_ratio / max_wh_ratio)
+ return text
def get_character(
self,
@@ -111,7 +80,7 @@ class CTCLabelDecode:
is_remove_duplicate: bool = False,
) -> List[Tuple[str, float]]:
"""convert text-index into text-label."""
- result_list, result_words_list = [], []
+ result_list = []
ignored_tokens = self.get_ignored_tokens()
batch_size = len(text_index)
for batch_idx in range(batch_size):
@@ -124,7 +93,6 @@ class CTCLabelDecode:
if text_prob is not None:
conf_list = np.array(text_prob[batch_idx][selection]).tolist()
- conf_list = [round(conf, 5) for conf in conf_list]
else:
conf_list = [1] * len(selection)
@@ -135,23 +103,26 @@ class CTCLabelDecode:
self.character[text_id] for text_id in text_index[batch_idx][selection]
]
text = "".join(char_list)
-
- result_list.append([text, np.mean(conf_list).round(5).tolist()])
-
if return_word_box:
word_list, word_col_list, state_list = self.get_word_info(
text, selection
)
- result_words_list.append(
- [
- len(text_index[batch_idx]),
- word_list,
- word_col_list,
- state_list,
- conf_list,
- ]
+ result_list.append(
+ (
+ text,
+ np.mean(conf_list).tolist(),
+ [
+ len(text_index[batch_idx]),
+ word_list,
+ word_col_list,
+ state_list,
+ conf_list,
+ ],
+ )
)
- return result_list, result_words_list
+ else:
+ result_list.append((text, np.mean(conf_list).tolist()))
+ return result_list
@staticmethod
def get_word_info(
diff --git a/python/rapidocr_onnxruntime/main.py b/python/rapidocr_onnxruntime/main.py
index d529fb4..330651d 100644
--- a/python/rapidocr_onnxruntime/main.py
+++ b/python/rapidocr_onnxruntime/main.py
@@ -11,7 +11,7 @@ import numpy as np
from .cal_rec_boxes import CalRecBoxes
from .ch_ppocr_cls import TextClassifier
from .ch_ppocr_det import TextDetector
-from .ch_ppocr_rec import TextRecognizer, TextRecognizerOutput
+from .ch_ppocr_rec import TextRecognizer
from .utils import (
LoadImage,
UpdateParameters,
@@ -106,18 +106,14 @@ class RapidOCR:
img, cls_res, cls_elapse = self.text_cls(img)
if use_rec:
- rec_res = self.text_rec(img, return_word_box)
+ rec_res, rec_elapse = self.text_rec(img, return_word_box)
- if (
- return_word_box
- and dt_boxes is not None
- and rec_res.word_results is not None
- ):
+ if dt_boxes is not None and rec_res is not None and return_word_box:
rec_res = self.cal_rec_boxes(img, dt_boxes, rec_res)
- for rec_res_i in rec_res.word_results:
+ for rec_res_i in rec_res:
if rec_res_i[2]:
rec_res_i[2] = (
- self._get_origin_points([rec_res_i[2]], op_record, raw_h, raw_w)
+ self._get_origin_points(rec_res_i[2], op_record, raw_h, raw_w)
.astype(np.int32)
.tolist()
)
@@ -126,12 +122,7 @@ class RapidOCR:
dt_boxes = self._get_origin_points(dt_boxes, op_record, raw_h, raw_w)
ocr_res = self.get_final_res(
- # dt_boxes, cls_res, rec_res, det_elapse, cls_elapse, rec_elapse
- dt_boxes,
- cls_res,
- rec_res,
- det_elapse,
- cls_elapse,
+ dt_boxes, cls_res, rec_res, det_elapse, cls_elapse, rec_elapse
)
return ocr_res
@@ -285,9 +276,10 @@ class RapidOCR:
self,
dt_boxes: Optional[List[np.ndarray]],
cls_res: Optional[List[List[Union[str, float]]]],
- rec_res: TextRecognizerOutput,
+ rec_res: Optional[List[Tuple[str, float, List[Union[str, float]]]]],
det_elapse: float,
cls_elapse: float,
+ rec_elapse: float,
) -> Tuple[Optional[List[List[Union[Any, str]]]], Optional[List[float]]]:
if dt_boxes is None and rec_res is None and cls_res is not None:
return cls_res, [cls_elapse]
@@ -296,7 +288,7 @@ class RapidOCR:
return None, None
if dt_boxes is None and rec_res is not None:
- return [[v[0], v[1]] for v in rec_res.line_results], [rec_res.elapse]
+ return [[res[0], res[1]] for res in rec_res], [rec_elapse]
if dt_boxes is not None and rec_res is None:
return [box.tolist() for box in dt_boxes], [det_elapse]
@@ -305,12 +297,10 @@ class RapidOCR:
if not dt_boxes or not rec_res or len(dt_boxes) <= 0:
return None, None
- ocr_res = [
- [box.tolist(), *res] for box, res in zip(dt_boxes, rec_res.line_results)
- ], [
+ ocr_res = [[box.tolist(), *res] for box, res in zip(dt_boxes, rec_res)], [
det_elapse,
cls_elapse,
- rec_res.elapse,
+ rec_elapse,
]
return ocr_res
@@ -318,19 +308,18 @@ class RapidOCR:
self,
dt_boxes: Optional[List[np.ndarray]],
rec_res: Optional[List[Tuple[str, float]]],
- ) -> Tuple[Optional[List[np.ndarray]], TextRecognizerOutput]:
+ ) -> Tuple[Optional[List[np.ndarray]], Optional[List[Tuple[str, float]]]]:
if dt_boxes is None or rec_res is None:
return None, None
filter_boxes, filter_rec_res = [], []
- for box, rec_reuslt in zip(dt_boxes, rec_res.line_results):
+ for box, rec_reuslt in zip(dt_boxes, rec_res):
text, score = rec_reuslt[0], rec_reuslt[1]
if float(score) >= self.text_score:
filter_boxes.append(box)
filter_rec_res.append(rec_reuslt)
- rec_res.line_results = filter_rec_res
- return filter_boxes, rec_res
+ return filter_boxes, filter_rec_res
def main():
diff --git a/python/tests/test_main.py b/python/tests/test_main.py
new file mode 100644
index 0000000..b2fc534
--- /dev/null
+++ b/python/tests/test_main.py
@@ -0,0 +1,249 @@
+# -*- encoding: utf-8 -*-
+# @Author: SWHL
+# @Contact: [email protected]
+import logging
+import sys
+from pathlib import Path
+from typing import List
+
+import cv2
+import numpy as np
+import pytest
+
+root_dir = Path(__file__).resolve().parent.parent
+sys.path.append(str(root_dir))
+
+from rapidocr import LoadImageError, RapidOCR
+
+from .base_module import download_file
+
+engine = RapidOCR()
+tests_dir = root_dir / "tests" / "test_files"
+img_path = tests_dir / "ch_en_num.jpg"
+package_name = "rapidocr_onnxruntime"
+
+
+def test_long_img():
+ img_url = "https://github.com/RapidAI/RapidOCR/releases/download/v1.1.0/long.jpeg"
+ img_path = tests_dir / "long.jpeg"
+ download_file(img_url, save_path=img_path)
+ result, _ = engine(img_path)
+
+ assert result is not None
+ assert len(result) >= 53
+
+ img_path.unlink()
+
+
+def test_ort_cuda_warning(caplog):
+ engine = RapidOCR(det_use_cuda=True)
+ caplog.set_level(logging.WARNING)
+
+ assert caplog.records[0].levelname == "WARNING"
+ assert "CUDAExecutionProvider" in caplog.records[0].message
+
+
+def test_ort_dml_warning(caplog):
+ engine = RapidOCR(det_use_dml=True)
+ caplog.set_level(logging.WARNING)
+
+ assert caplog.records[0].levelname == "WARNING"
+ assert "DirectML" in caplog.records[0].message
+
+
+def test_mode_one_img():
+ img_path = tests_dir / "issue_170.png"
+ result, _ = engine(img_path)
+ assert result[0][1] == "TEST"
+
+
+ "img_name,gt",
+ [
+ (
+ "black_font_color_transparent.png",
+ "我是中国人",
+ ),
+ (
+ "white_font_color_transparent.png",
+ "我是中国人",
+ ),
+ ],
+)
+def test_transparent_img(img_name: str, gt: str):
+ img_path = tests_dir / img_name
+ result, _ = engine(img_path)
+ assert result[0][1] == gt
+
+
+ "img_name,gt_len,gt_first_len",
+ [
+ (
+ "test_letterbox_like.jpg",
+ 2,
+ "A::取决于所使用的执行提供者,它可能没有完全支持模型中的所有操作。回落到CPU操作可能会导致性能速度的下降。此外,即使一个操作是由CUDAeXecution",
+ ),
+ ("test_without_det.jpg", 1, "在中国作家协会第三届儿童文学"),
+ ],
+)
+def test_letterbox_like(img_name, gt_len, gt_first_len):
+ img_path = tests_dir / img_name
+ result, _ = engine(img_path)
+
+ assert len(result) == gt_len
+ assert result[0][1].lower() == gt_first_len.lower()
+
+
+def test_only_det():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=False)
+
+ assert len(result) == 18
+
+
+def test_only_cls():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=False)
+ assert len(result) == 1
+ assert result[0][0] == "0"
+
+
+def test_only_rec():
+ img_path = tests_dir / "text_rec.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=False, use_rec=True)
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_rec():
+ result, _ = engine(img_path, use_det=True, use_cls=False, use_rec=True)
+ assert result[0][1] == "正品促销"
+ assert len(result) == 18
+
+
+def test_cls_rec():
+ img_path = tests_dir / "text_cls.jpg"
+ result, _ = engine(img_path, use_det=False, use_cls=True, use_rec=True)
+
+ assert result is not None
+ assert len(result) == 1
+ assert result[0][0] == "韩国小馆"
+
+
+def test_det_cls_rec():
+ img = cv2.imread(str(img_path))
+
+ result, _ = engine(img)
+ assert result is not None
+ assert result[0][1] == "正品促销"
+ assert len(result) == 18
+
+
+def test_empty():
+ img = None
+ with pytest.raises(LoadImageError) as exc_info:
+ engine(img)
+ raise LoadImageError
+ assert exc_info.type is LoadImageError
+
+
+def test_zeros():
+ img = np.zeros([640, 640, 3], np.uint8)
+ result, _ = engine(img)
+ assert result is None
+
+
+def test_input_str():
+ result, _ = engine(str(img_path))
+ assert result[0][1] == "正品促销"
+ assert len(result) == 18
+
+
+def test_input_bytes():
+ with open(img_path, "rb") as f:
+ result, _ = engine(f.read())
+ assert result[0][1] == "正品促销"
+ assert len(result) == 18
+
+
+def test_input_path():
+ result, _ = engine(img_path)
+ assert result[0][1] == "正品促销"
+ assert len(result) == 18
+
+
+def test_input_parameters():
+ img_path = tests_dir / "ch_en_num.jpg"
+ engine = RapidOCR(text_score=1)
+ result, _ = engine(img_path)
+
+ assert result is None
+
+
+def test_input_det_parameters():
+ with pytest.raises(FileNotFoundError) as exc_info:
+ engine = RapidOCR(det_model_path="1.onnx")
+ result, _ = engine(img_path)
+ raise FileNotFoundError()
+ assert exc_info.type is FileNotFoundError
+
+
+def test_input_cls_parameters():
+ with pytest.raises(FileNotFoundError) as exc_info:
+ engine = RapidOCR(cls_model_path="1.onnx")
+ result, _ = engine(img_path)
+ raise FileNotFoundError()
+ assert exc_info.type is FileNotFoundError
+
+
+def test_input_rec_parameters():
+ with pytest.raises(FileNotFoundError) as exc_info:
+ engine = RapidOCR(rec_model_path="1.onnx")
+ result, _ = engine(img_path)
+ raise FileNotFoundError()
+ assert exc_info.type is FileNotFoundError
+
+
+def test_input_three_ndim_two_channel():
+ img_npy = tests_dir / "two_dim_image.npy"
+ image_array = np.load(str(img_npy))
+ result, _ = engine(image_array)
+
+ assert result is not None
+ assert len(result) == 1
+ assert result[0][1] == "TREND PLOT REPORT"
+
+
+def test_input_three_ndim_one_channel():
+ img = cv2.imread(str(img_path))
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
+ img = img[:, :, 0]
+ img = img[..., None] # (H, W, 1)
+
+ result, _ = engine(img)
+
+ assert len(result) >= 17
+
+
[email protected](reason="no way of currently testing this")
+ "img_name,words",
+ [
+ (
+ "black_font_color_transparent.png",
+ ["我", "是", "中", "国", "人"],
+ ),
+ (
+ "text_vertical_words.png",
+ ["已", "取", "之", "時", "不", "參", "一", "人", "見", "而"],
+ ),
+ (
+ "issue_170.png",
+ ["T", "E", "S", "T"],
+ ),
+ ],
+)
+def test_word_ocr(img_name: str, words: List[str]):
+ img_path = tests_dir / img_name
+ result, _ = engine(img_path, return_word_box=True)
+ assert result[0][4] == words