📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
feat(return_word_box): support word box of English and number text (#423)
SWHL5776a55e8f53
diff --git a/python/demo.py b/python/demo.pyindex af1ef62..eae54aa 100644--- a/python/demo.py+++ b/python/demo.py@@ -1,12 +1,21 @@# -*- encoding: utf-8 -*-# @Author: SWHL# @Contact: [email protected]+from pathlib import Path+from rapidocr import RapidOCR-engine = RapidOCR(params={"Global.with_torch": True})+engine = RapidOCR()++# img_url = "https://img1.baidu.com/it/u=3619974146,1266987475&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=516"++# img_paths = ["tmp/en.jpg", "tmp/ch.jpg", "tmp/ch_en.jpg"]-img_url = "https://img1.baidu.com/it/u=3619974146,1266987475&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=516"-result = engine(img_url)-print(result)+# for img_path in img_paths:+# result = engine(img_path, return_word_box=True)+# # print(result)-result.vis("vis_result.jpg")+# result.vis(f"tmp/vis_{Path(img_path).stem}.jpg")+img_path = "tmp/ch.jpg"+result = engine(img_path, return_word_box=True)+result.vis(f"tmp/vis_{Path(img_path).stem}.jpg")diff --git a/python/rapidocr/cal_rec_boxes/main.py b/python/rapidocr/cal_rec_boxes/main.pyindex dc37119..31c8176 100644--- a/python/rapidocr/cal_rec_boxes/main.py+++ b/python/rapidocr/cal_rec_boxes/main.py@@ -3,40 +3,40 @@# @Contact: [email protected]import copyimport math-from typing import List, Optional, Tuple+from enum import Enum+from typing import List, Tupleimport cv2import numpy as np-from ..ch_ppocr_rec.utils import TextRecOutput+from ..ch_ppocr_rec.typings import TextRecOutput, WordInfo, WordType+from ..utils.utils import quads_to_rect_bbox+++class Direction(Enum):+ HORIZONTAL = "horizontal_direct" # 水平+ VERTICAL = "vertical_direct" # 垂直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: TextRecOutput,+ self, imgs: List[np.ndarray], dt_boxes: List[np.ndarray], rec_res: TextRecOutput) -> TextRecOutput:word_results = []for idx, (img, box) in enumerate(zip(imgs, dt_boxes)):- direction = self.get_box_direction(box)-- rec_txt = rec_res.txts[idx]- rec_word_info = rec_res.word_results[idx]+ if rec_res.txts is None:+ continueh, 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+ rec_res.txts[idx], img_box, rec_res.word_results[idx])word_box_list = self.adjust_box_overlap(copy.deepcopy(word_box_list))+ direction = self.get_box_direction(box)word_box_list = self.reverse_rotate_crop_image(copy.deepcopy(box), word_box_list, direction)@@ -48,97 +48,128 @@ class CalRecBoxes: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+ def get_box_direction(box: np.ndarray) -> Direction:+ edge_lengths = [+ float(np.linalg.norm(box[0] - box[1])), # 上边+ float(np.linalg.norm(box[1] - box[2])), # 右边+ float(np.linalg.norm(box[2] - box[3])), # 下边+ float(np.linalg.norm(box[3] - box[0])), # 左边+ ]++ # 宽和高取对边的最大距离+ width = max(edge_lengths[0], edge_lengths[2])+ height = max(edge_lengths[1], edge_lengths[3])++ if width < 1e-6:+ return Direction.VERTICAL++ aspect_ratio = round(height / width, 2)+ return Direction.VERTICAL if aspect_ratio >= 1.5 else Direction.HORIZONTAL- @staticmethoddef 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]]:+ self, rec_txt: str, bbox: np.ndarray, word_info: WordInfo+ ) -> Tuple[List[str], List[List[List[float]]], List[float]]:"""Calculate the detection frame for each word based on the results of recognition and detection of ocr汉字坐标是单字的英语坐标是单词级别的+ 三种情况:+ 1. 全是汉字+ 2. 全是英文+ 3. 中英混合"""+ bbox_points = quads_to_rect_bbox(bbox[None, ...])+ avg_col_width = (bbox_points[2] - bbox_points[0]) / word_info.line_txt_len- 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+ is_all_en_num = all(v is WordType.EN_NUM for v in word_info.word_types)++ line_cols, char_widths, word_contents = [], [], []+ for word, word_col in zip(word_info.words, word_info.word_cols):+ if is_all_en_num:+ line_cols.append(word_col)+ word_contents.append("".join(word))else:- cal_char_width(en_width_list, word_col)- en_col_list += word_col- word_box_content_list += word+ line_cols.extend(word_col)+ word_contents.extend(word)++ if len(word_col) == 1:+ continue- 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+ avg_width = self.calc_avg_char_width(word_col, avg_col_width)+ char_widths.append(avg_width)++ avg_char_width = self.calc_all_char_avg_width(+ char_widths, bbox_points[0], bbox_points[2], len(rec_txt)+ )++ if is_all_en_num:+ word_boxes = self.calc_en_num_box(+ line_cols, avg_char_width, avg_col_width, bbox_points+ )+ else:+ word_boxes = self.calc_box(+ line_cols, avg_char_width, avg_col_width, bbox_points+ )+ return word_contents, word_boxes, word_info.confs++ def calc_en_num_box(+ self,+ line_cols: List[List[int]],+ avg_char_width: float,+ avg_col_width: float,+ bbox_points: Tuple[float, float, float, float],+ ) -> List[List[List[float]]]:+ results = []+ for one_col in line_cols:+ cur_word_cell = self.calc_box(+ one_col, avg_char_width, avg_col_width, bbox_points+ )+ x0, y0, x1, y1 = quads_to_rect_bbox(np.array(cur_word_cell))+ results.append([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])+ return results++ @staticmethod+ def calc_box(+ line_cols: List[int],+ avg_char_width: float,+ avg_col_width: float,+ bbox_points: Tuple[float, float, float, float],+ ) -> List[List[List[float]]]:+ x0, y0, x1, y1 = bbox_points++ results = []+ for col_idx in line_cols:+ # 将中心点定位在列的中间位置+ center_x = (col_idx + 0.5) * avg_col_width++ # 计算字符单元格的左右边界+ char_x0 = max(int(center_x - avg_char_width / 2), 0) + x0+ char_x1 = min(int(center_x + avg_char_width / 2), x1 - x0) + x0+ cell = [+ [char_x0, y0],+ [char_x1, y0],+ [char_x1, y1],+ [char_x0, y1],+ ]+ results.append(cell)+ return sorted(results, key=lambda x: x[0][0])++ @staticmethod+ def calc_avg_char_width(word_col: List[int], each_col_width: float) -> float:+ char_total_length = (word_col[-1] - word_col[0]) * each_col_width+ return char_total_length / (len(word_col) - 1)++ @staticmethod+ def calc_all_char_avg_width(+ width_list: List[float], bbox_x0: float, bbox_x1: float, txt_len: int+ ) -> float:+ if len(width_list) > 0:+ return sum(width_list) / len(width_list)+ return (bbox_x1 - bbox_x0) / txt_len@staticmethoddef adjust_box_overlap(- word_box_list: List[List[List[int]]],- ) -> List[List[List[int]]]:+ word_box_list: List[List[List[float]]],+ ) -> List[List[List[float]]]:# 调整bbox有重叠的地方for i in range(len(word_box_list) - 1):cur, nxt = word_box_list[i], word_box_list[i + 1]@@ -153,8 +184,8 @@ class CalRecBoxes:def reverse_rotate_crop_image(self,bbox_points: np.ndarray,- word_points_list: List[List[List[int]]],- direction: str = "w",+ word_points_list: List[List[List[float]]],+ direction: Direction,) -> List[List[List[int]]]:"""get_rotate_crop_image的逆操作@@ -163,8 +194,6 @@ class CalRecBoxes: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@@ -189,13 +218,13 @@ class CalRecBoxes:new_word_points = []for point in word_points:new_point = point- if direction == "h":+ if direction == Direction.VERTICAL: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])+ p = np.array(new_point + [1])x, y, z = np.dot(IM, p)new_point = [x / z, y / z]@@ -225,18 +254,18 @@ class CalRecBoxes:return [sRotatex, sRotatey]@staticmethod- def order_points(box: List[List[int]]) -> List[List[int]]:+ def order_points(ori_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):++ if p.shape == (1, 2):return p- else:- return p[:1, :]+ return p[:1, :]- box = np.array(box).reshape((-1, 2))+ box = np.array(ori_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_ydiff --git a/python/rapidocr/ch_ppocr_rec/__init__.py b/python/rapidocr/ch_ppocr_rec/__init__.pyindex 867d812..c1f1347 100644--- a/python/rapidocr/ch_ppocr_rec/__init__.py+++ b/python/rapidocr/ch_ppocr_rec/__init__.py@@ -2,4 +2,4 @@# @Author: SWHL# @Contact: [email protected]from .main import TextRecognizer-from .utils import TextRecInput, TextRecOutput+from .typings import TextRecInput, TextRecOutputdiff --git a/python/rapidocr/ch_ppocr_rec/main.py b/python/rapidocr/ch_ppocr_rec/main.pyindex 227f313..43a255c 100644--- a/python/rapidocr/ch_ppocr_rec/main.py+++ b/python/rapidocr/ch_ppocr_rec/main.py@@ -23,7 +23,8 @@ from rapidocr.inference_engine.base import get_enginefrom ..utils import Loggerfrom ..utils.download_file import DownloadFile, DownloadFileInput-from .utils import CTCLabelDecode, TextRecInput, TextRecOutput+from .utils import CTCLabelDecode+from .typings import TextRecInput, TextRecOutputDEFAULT_DICT_PATH = Path(__file__).parent.parent / "models" / "ppocr_keys_v1.txt"DEFAULT_DICT_URL = "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v2.0.7/paddle/PP-OCRv4/rec/ch_PP-OCRv4_rec_infer/ppocr_keys_v1.txt"diff --git a/python/rapidocr/ch_ppocr_rec/typings.py b/python/rapidocr/ch_ppocr_rec/typings.pynew file mode 100644index 0000000..b9ff580--- /dev/null+++ b/python/rapidocr/ch_ppocr_rec/typings.py@@ -0,0 +1,82 @@+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+from dataclasses import dataclass, field+from enum import Enum+from pathlib import Path+from typing import List, Optional, Tuple, Union++import numpy as np++from ..utils.logger import Logger+from ..utils.utils import save_img+from ..utils.vis_res import VisRes++logger = Logger(logger_name=__name__).get_log()+++@dataclass+class TextRecConfig:+ 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 TextRecInput:+ img: Union[np.ndarray, List[np.ndarray], None] = None+ return_word_box: bool = False+++@dataclass+class TextRecOutput:+ imgs: Optional[List[np.ndarray]] = None+ txts: Optional[Tuple[str]] = None+ scores: Tuple[float] = (1.0,)+ word_results: Tuple[Tuple[str, float, Optional[List[List[int]]]]] = (+ ("", 1.0, None),+ )+ elapse: Optional[float] = None+ lang_rec: Optional[str] = None++ def __len__(self):+ if self.txts is None:+ return 0+ return len(self.txts)++ def vis(self, save_path: Optional[Union[str, Path]] = None) -> Optional[np.ndarray]:+ if self.imgs is None or self.txts is None:+ logger.warning("No image or txts to visualize.")+ return None++ vis = VisRes()+ vis_img = vis.draw_rec_res(+ self.imgs, self.txts, self.scores, lang_rec=self.lang_rec+ )++ if save_path is not None:+ save_img(save_path, vis_img)+ logger.info("Visualization saved as %s", save_path)+ return vis_img+++class WordType(Enum):+ CN = "cn"+ EN = "en"+ NUM = "num"+ EN_NUM = "en&num"+++@dataclass+class WordInfo:+ words: List[List[str]] = field(default_factory=list)+ word_cols: List[List[int]] = field(default_factory=list)+ word_types: List[WordType] = field(default_factory=list)+ line_txt_len: float = 0.0+ confs: List[float] = field(default_factory=list)diff --git a/python/rapidocr/ch_ppocr_rec/utils.py b/python/rapidocr/ch_ppocr_rec/utils.pyindex 4b4ec15..0f8ba15 100644--- a/python/rapidocr/ch_ppocr_rec/utils.py+++ b/python/rapidocr/ch_ppocr_rec/utils.py@@ -1,68 +1,13 @@# -*- encoding: utf-8 -*-# @Author: SWHL# @Contact: [email protected]-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, List, Optional, Tuple, Unionimport numpy as np-from ..utils.logger import Logger-from ..utils.utils import save_img-from ..utils.vis_res import VisRes--logger = Logger(logger_name=__name__).get_log()---@dataclass-class TextRecConfig:- 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 TextRecInput:- img: Union[np.ndarray, List[np.ndarray], None] = None- return_word_box: bool = False---@dataclass-class TextRecOutput:- imgs: Optional[List[np.ndarray]] = None- txts: Optional[Tuple[str]] = None- scores: Tuple[float] = (1.0,)- word_results: Tuple[Tuple[str, float, Optional[List[List[int]]]]] = (- ("", 1.0, None),- )- elapse: Optional[float] = None- lang_rec: Optional[str] = None-- def __len__(self):- if self.txts is None:- return 0- return len(self.txts)-- def vis(self, save_path: Optional[Union[str, Path]] = None) -> Optional[np.ndarray]:- if self.imgs is None or self.txts is None:- logger.warning("No image or txts to visualize.")- return None-- vis = VisRes()- vis_img = vis.draw_rec_res(- self.imgs, self.txts, self.scores, lang_rec=self.lang_rec- )-- if save_path is not None:- save_img(save_path, vis_img)- logger.info("Visualization saved as %s", save_path)- return vis_img+from ..utils.utils import has_chinese_char+from .typings import WordInfo, WordTypeclass CTCLabelDecode:@@ -89,7 +34,7 @@ class CTCLabelDecode:return_word_box,wh_ratio_list,max_wh_ratio,- is_remove_duplicate=True,+ remove_duplicate=True,)return line_results, word_results@@ -141,18 +86,20 @@ class CTCLabelDecode:return_word_box: bool = False,wh_ratio_list: Tuple[float] = (1.0,),max_wh_ratio: float = 1.0,- is_remove_duplicate: bool = False,- ) -> Tuple[List[Tuple[str, float]], List[Tuple[Any]]]:+ remove_duplicate: bool = False,+ ) -> Tuple[List[Tuple[str, float]], List[WordInfo]]: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]+ token_indices = text_index[batch_idx]++ selection = np.ones(len(token_indices), dtype=bool)+ if remove_duplicate:+ selection[1:] = token_indices[1:] != token_indices[:-1]for ignored_token in ignored_tokens:- selection &= text_index[batch_idx] != ignored_token+ selection &= token_indices != ignored_tokenif text_prob is not None:conf_list = np.array(text_prob[batch_idx][selection]).tolist()@@ -164,67 +111,58 @@ class CTCLabelDecode:conf_list = [0]char_list = [- self.character[text_id] for text_id in text_index[batch_idx][selection]+ self.character[text_id] for text_id in token_indices[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- )-- word_len = len(text_index[batch_idx])- word_len *= wh_ratio_list[batch_idx] / max_wh_ratio-- result_words_list.append(- (word_len, word_list, word_col_list, state_list, conf_list)+ rec_word_info = self.get_word_info(text, selection)+ rec_word_info.line_txt_len = (+ len(token_indices) * wh_ratio_list[batch_idx] / max_wh_ratio)+ rec_word_info.confs = conf_list+ result_words_list.append(rec_word_info)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]]:+ def get_word_info(text: str, selection: np.ndarray) -> WordInfo:"""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 = []++ word_content = []+ word_col_content = []+valid_col = np.where(selection)[0]+ if len(valid_col) <= 0:+ return WordInfo()+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])- )+ col_width[1:] = valid_col[1:] - valid_col[:-1]+ col_width[0] = min(3 if has_chinese_char(text[0]) else 2, int(valid_col[0]))+ state = Nonefor c_i, char in enumerate(text):- if "\u4e00" <= char <= "\u9fff":- c_state = "cn"- else:- c_state = "en&num"+ if char.isspace():+ if word_content:+ word_list.append(word_content)+ word_col_list.append(word_col_content)+ state_list.append(state)+ word_content = []+ word_col_content = []+ continue+ c_state = WordType.CN if has_chinese_char(char) else WordType.EN_NUMif state is None:state = c_state- if state != c_state or col_width[c_i] > 4:+ if state != c_state or col_width[c_i] > 5:if len(word_content) != 0:word_list.append(word_content)word_col_list.append(word_col_content)@@ -241,7 +179,7 @@ class CTCLabelDecode:word_col_list.append(word_col_content)state_list.append(state)- return word_list, word_col_list, state_list+ return WordInfo(words=word_list, word_cols=word_col_list, word_types=state_list)@staticmethoddef get_ignored_tokens() -> List[int]:diff --git a/python/rapidocr/inference_engine/base.py b/python/rapidocr/inference_engine/base.pyindex 8e161a7..80a3e5a 100644--- a/python/rapidocr/inference_engine/base.py+++ b/python/rapidocr/inference_engine/base.py@@ -19,7 +19,7 @@ MODEL_URL_PATH = cur_dir / "default_models.yaml"logger = Logger(logger_name=__name__).get_log()-class Engine(Enum):+class EngineType(Enum):ONNXRUNTIME = "onnxruntime"OPENVINO = "openvino"PADDLE = "paddle"@@ -28,8 +28,8 @@ class Engine(Enum):def get_installed_engine() -> List[str]:installed_engine = []- for v in Engine.__members__:- engine_name = Engine[v].value+ for v in EngineType:+ engine_name = v.valueif import_package(engine_name) is None:continue@@ -40,7 +40,8 @@ def get_installed_engine() -> List[str]:def get_engine(engine_name: str):logger.info("Using engine_name: %s", engine_name)- if engine_name == Engine.ONNXRUNTIME.value:+ engine_type = EngineType(engine_name)+ if engine_type == EngineType.ONNXRUNTIME:if not import_package("onnxruntime"):raise ImportError("onnxruntime is not installed.")@@ -48,7 +49,7 @@ def get_engine(engine_name: str):return OrtInferSession- if engine_name == Engine.OPENVINO.value:+ if engine_type == EngineType.OPENVINO:if not import_package("openvino"):raise ImportError("openvino is not installed")@@ -56,7 +57,7 @@ def get_engine(engine_name: str):return OpenVINOInferSession- if engine_name == Engine.PADDLE.value:+ if engine_type == EngineType.PADDLE:if not import_package("paddle"):raise ImportError("paddleopaddle is not installed")@@ -64,7 +65,7 @@ def get_engine(engine_name: str):return PaddleInferSession- if engine_name == Engine.TORCH.value:+ if engine_type == EngineType.TORCH:if not import_package("torch"):raise ImportError("torch is not installed")@@ -82,18 +83,18 @@ def get_engine_name(config: DictConfig) -> str:with_torch = config.Global.with_torchif with_onnx:- return Engine.ONNXRUNTIME.value+ return EngineType.ONNXRUNTIME.valueif with_openvino:- return Engine.OPENVINO.value+ return EngineType.OPENVINO.valueif with_paddle:- return Engine.PADDLE.value+ return EngineType.PADDLE.valueif with_torch:- return Engine.TORCH.value+ return EngineType.TORCH.value- return Engine.ONNXRUNTIME.value+ return EngineType.ONNXRUNTIME.valueclass InferSession(abc.ABC):diff --git a/python/rapidocr/utils/utils.py b/python/rapidocr/utils/utils.pyindex dd2ee3e..842fa78 100644--- a/python/rapidocr/utils/utils.py+++ b/python/rapidocr/utils/utils.py@@ -3,15 +3,31 @@# @Contact: [email protected]import hashlibimport importlib-import sysfrom pathlib import Path-from typing import Union+from typing import Tuple, Unionfrom urllib.parse import urlparseimport cv2import numpy as np+def quads_to_rect_bbox(bbox: np.ndarray) -> Tuple[float, float, float, float]:+ if bbox.ndim != 3:+ raise ValueError("bbox shape must be 3")++ if bbox.shape[1] != 4 and bbox.shape[2] != 2:+ raise ValueError("bbox shape must be (N, 4, 2)")++ all_x, all_y = (bbox[:, :, 0].flatten(), bbox[:, :, 1].flatten())+ x_min, y_min = np.min(all_x), np.min(all_y)+ x_max, y_max = np.max(all_x), np.max(all_y)+ return float(x_min), float(y_min), float(x_max), float(y_max)+++def has_chinese_char(text: str) -> bool:+ return any("\u4e00" <= ch <= "\u9fff" for ch in text)++def get_file_sha256(file_path: Union[str, Path], chunk_size: int = 65536) -> str:with open(file_path, "rb") as file:sha_signature = hashlib.sha256()diff --git a/python/tests/test_main.py b/python/tests/test_main.pyindex d25c736..6347a4c 100644--- a/python/tests/test_main.py+++ b/python/tests/test_main.py@@ -370,14 +370,21 @@ def test_input_three_ndim_one_channel(engine):"也",),),- (- "issue_170.png",- ("T", "E", "S", "T"),- ),],)-def test_word_ocr(engine, img_name: str, words: List[str]):+def test_cn_word_ocr(engine, img_name: str, words: List[str]):img_path = tests_dir / img_nameresult = engine(img_path, return_word_box=True)txts, _, _ = list(zip(*result.word_results))assert txts == words+++ "img_name,words",+ [("issue_170.png", "TEST")],+)+def test_en_word_ocr(engine, img_name: str, words: str):+ img_path = tests_dir / img_name+ result = engine(img_path, return_word_box=True)+ txts, _, _ = list(zip(*result.word_results))+ assert txts[0] == words