📄 Awesome OCR multiple programing languages toolkits based on ONNX Runtime, OpenVINO, MNN, PaddlePaddle, TensorRT and PyTorch.
Add auto generate sdk scripts
SWHLfb49ff079fd1
diff --git a/release/python_sdk/_gen_sdk/auto_deploy.sh b/release/python_sdk/_gen_sdk/auto_deploy.shnew file mode 100644index 0000000..bef558d--- /dev/null+++ b/release/python_sdk/_gen_sdk/auto_deploy.sh@@ -0,0 +1,21 @@+#! /bin/bash++sdk_dir="sdk_rapidocr_v1.0.0"++echo ">>>>>>打包现有的"+python setup.py bdist_wheel+mv dist/*.whl ${sdk_dir}/+rm -r build+rm -r dist+rm -r *.egg-info++echo ">>>>>>安装在当前环境下"+pip install ${sdk_dir}/*.whl++echo ">>>>>>覆盖README.md"+cp "requirements.txt" "${sdk_dir}/"++echo ">>>>>>测试whl是否有误"++cd ${sdk_dir}+python test_demo.pydiff --git a/release/python_sdk/_gen_sdk/rapidocr/__init__.py b/release/python_sdk/_gen_sdk/rapidocr/__init__.pynew file mode 100644index 0000000..54a9b6c--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/__init__.py@@ -0,0 +1,5 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+# @File: __init__.py+# @Author: Max+from .rapidocr import TextSystemdiff --git a/release/python_sdk/_gen_sdk/rapidocr/rapidocr.py b/release/python_sdk/_gen_sdk/rapidocr/rapidocr.pynew file mode 100644index 0000000..76da6b0--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/rapidocr.py@@ -0,0 +1,398 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+import argparse+import copy+import imghdr+import math+import random+from pathlib import Path++import cv2+import numpy as np+from PIL import Image, ImageDraw, ImageFont++try:+ from .text_cls import TextDirectionClassifier+ from .text_detect import TextDetector+ from .text_recognize import TextRecognizer+except:+ from text_cls import TextDirectionClassifier+ from text_detect import TextDetector+ from text_recognize import TextRecognizer++drop_score = 0.5+++def get_image_file_list(img_file):+ if img_file is None or not Path(img_file).exists():+ raise FileExistsError(f"not found any img file in {img_file}")++ imgs_lists = []+ img_end = ['jpg', 'JPG', 'bmp', 'BMP', 'png', 'PNG', 'jpeg', 'JPEG',+ 'rgb', 'tif', 'tiff', 'gif', 'GIF']++ def _get_img_path(img_file):+ # 真实后缀+ real_img_suffix = imghdr.what(img_file)++ # 现在后缀+ now_img_suffix = img_file.suffix[1:]+ if real_img_suffix in img_end:+ # 真实后缀与现有后缀不一致+ if now_img_suffix in img_end:+ return img_file+ else:+ # 按照真实后缀重命名+ new_img_file = img_file.with_suffix(f'.{real_img_suffix}')+ img_file.rename(new_img_file)+ return new_img_file+ else:+ return None++ img_file = Path(img_file)+ if img_file.is_file():+ tmp_img_path = _get_img_path(img_file)+ if tmp_img_path is not None:+ imgs_lists.append(str(tmp_img_path))++ elif img_file.is_dir():+ for img_path in img_file.iterdir():+ tmp_file_path = _get_img_path(img_path)+ if tmp_file_path is not None:+ imgs_lists.append(str(tmp_file_path))+ else:+ raise ValueError(f"The {img_file}'s format is not support!")++ if len(imgs_lists) == 0:+ raise FileExistsError(f"not found any img file in {img_file}")++ return imgs_lists+++def check_and_read_gif(img_path):+ if Path(img_path).name[-3:] in ['gif', 'GIF']:+ gif = cv2.VideoCapture(img_path)+ ret, frame = gif.read()+ if not ret:+ print("Cannot read {}. This gif image maybe corrupted.")+ return None, False+ if len(frame.shape) == 2 or frame.shape[-1] == 1:+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)+ imgvalue = frame[:, :, ::-1]+ return imgvalue, True+ return None, False+++def draw_text_det_res(dt_boxes, raw_im):+ src_im = copy.deepcopy(raw_im)+ for i, box in enumerate(dt_boxes):+ box = np.array(box).astype(np.int32).reshape(-1, 2)+ cv2.polylines(src_im, [box], True,+ color=(0, 0, 255),+ thickness=1)+ cv2.putText(src_im, str(i), (int(box[0][0]), int(box[0][1])),+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)+ return src_im+++def draw_ocr_box_txt(image, boxes, txts,+ scores=None, drop_score=0.5,+ font_path="../assets/simsun.ttf"):+ h, w = image.height, image.width+ 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(boxes, txts)):+ if scores is not None and scores[idx] < drop_score:+ continue+ color = (random.randint(0, 255), random.randint(0, 255),+ random.randint(0, 255))+ draw_left.polygon(box, fill=color)+ draw_right.polygon(+ [+ box[0][0], box[0][1], box[1][0], box[1][1], box[2][0],+ box[2][1], box[3][0], box[3][1]+ ],+ outline=color)+ box_height = math.sqrt((box[0][0] - box[3][0])**2 + (box[0][1] - box[3][+ 1])**2)+ box_width = math.sqrt((box[0][0] - box[1][0])**2 + (box[0][1] - box[1][+ 1])**2)+ 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:+ char_size = font.getsize(c)+ draw_right.text(+ (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)+ cur_y += char_size[1]+ 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)+++def draw_box_txt(image, boxes, txts,+ scores=None, drop_score=0.5,+ font_path="assets/simsun.ttf"):+ h, w = image.height, image.width+ img_left = image.copy()+ img_right_width = int(w * 0.3)+ img_right = Image.new('RGB', (img_right_width, h), (255, 255, 255))++ random.seed(0)+ draw_left = ImageDraw.Draw(img_left)+ draw_right = ImageDraw.Draw(img_right)+ cur_y = 0+ for idx, (box, txt) in enumerate(zip(boxes, txts)):+ if scores is not None and scores[idx] < drop_score:+ continue+ color = (random.randint(0, 255), random.randint(0, 255),+ random.randint(0, 255))+ draw_left.polygon(box, fill=color)+ box_height = math.sqrt((box[0][0] - box[3][0])**2+ + (box[0][1] - box[3][1])**2)+ box_width = math.sqrt((box[0][0] - box[1][0])**2+ + (box[0][1] - box[1][1])**2)+ 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 = 0+ for c in txt:+ char_size = font.getsize(c)+ draw_right.text(+ (box[0][0] + 3, cur_y), c, fill=(0, 0, 0), font=font)+ cur_y += char_size[1]+ else:+ font_size = max(int(box_height * 0.8), 10)+ font = ImageFont.truetype(font_path, font_size, encoding="utf-8")+ font_w, font_h = font.getsize(txt)+ draw_right.text([10, cur_y],+ txt,+ fill=(0, 0, 0),+ font=font)+ cur_y += font_h++ img_left = Image.blend(image, img_left, 0.5)+ img_show = Image.new('RGB', (img_right_width + w, h), (255, 255, 255))+ img_show.paste(img_left, (0, 0, w, h))+ img_show.paste(img_right, (w, 0, img_right_width + w, h))+ return np.array(img_show)+++def visualize(image_path, boxes, rec_res):+ image, flag = check_and_read_gif(image_path)+ if not flag:+ image = cv2.imread(image_path)+ txts = [rec_res[i][0] for i in range(len(rec_res))]+ scores = [rec_res[i][1] for i in range(len(rec_res))]++ tmp_img = draw_text_det_res(boxes, np.array(image))+ draw_img = draw_ocr_box_txt(Image.fromarray(tmp_img), boxes,+ txts, scores,+ drop_score=0.5)++ img_directory = Path(image_path).parent.name+ draw_img_save = Path("./test_images/inference_results") / img_directory+ if not draw_img_save.exists():+ draw_img_save.mkdir(parents=True,+ exist_ok=True)+ image_save = str(draw_img_save / f'infer_{Path(image_path).name}.jpg')++ cv2.imwrite(image_save, draw_img[:, :, ::-1])+ for value in txts:+ print(value)+ write_txt(str(draw_img_save / f'{Path(image_path).stem}.txt'), txts)+ print(f'结果保存: {image_save}')+++def write_txt(save_path: str, content: list, mode='w'):+ """+ 将list内容写入txt中+ @param+ content: list格式内容+ save_path: 绝对路径str+ @return:None+ """+ with open(save_path, mode, encoding='utf-8') as f:+ for value in content:+ f.write(value + '\n')+++class TextSystem(object):+ def __init__(self,+ det_model_path,+ rec_model_path,+ direct_cls_model_path,+ dict_path,+ is_crop_image=True,+ limit_char_nums=100,+ is_filter_letter=True) -> None:+ super(TextSystem).__init__()++ # 验证模型是否存在+ self.verify_exist(det_model_path)+ self.verify_exist(rec_model_path)+ self.verify_exist(direct_cls_model_path)+ self.verify_exist(dict_path)++ self.text_detector = TextDetector(det_model_path)+ self.text_recognizer = TextRecognizer(rec_model_path, dict_path)+ self.text_classifier = TextDirectionClassifier(direct_cls_model_path)++ @staticmethod+ def verify_exist(model_path):+ if not isinstance(model_path, Path):+ model_path = Path(model_path)++ if not model_path.exists():+ raise FileNotFoundError(f'{model_path} does not exist!')++ if not model_path.is_file():+ raise FileExistsError(f'{model_path} must be a file')++ def get_rotate_crop_image(self, img, points):+ '''+ img_height, img_width = img.shape[0:2]+ left = int(np.min(points[:, 0]))+ right = int(np.max(points[:, 0]))+ top = int(np.min(points[:, 1]))+ bottom = int(np.max(points[:, 1]))+ img_crop = img[top:bottom, left:right, :].copy()+ points[:, 0] = points[:, 0] - left+ points[:, 1] = points[:, 1] - top+ '''+ img_crop_width = int(+ max(+ np.linalg.norm(points[0] - points[1]),+ np.linalg.norm(points[2] - points[3])))+ img_crop_height = int(+ max(+ np.linalg.norm(points[0] - points[3]),+ np.linalg.norm(points[1] - points[2])))+ pts_std = np.float32([[0, 0], [img_crop_width, 0],+ [img_crop_width, img_crop_height],+ [0, img_crop_height]])+ points = points.astype(pts_std.dtype)+ M = cv2.getPerspectiveTransform(points, pts_std)+ dst_img = cv2.warpPerspective(+ img,+ M, (img_crop_width, img_crop_height),+ borderMode=cv2.BORDER_REPLICATE,+ flags=cv2.INTER_CUBIC)+ dst_img_height, dst_img_width = dst_img.shape[0:2]+ if dst_img_height * 1.0 / dst_img_width >= 1.5:+ dst_img = np.rot90(dst_img)+ return dst_img++ @staticmethod+ def sorted_boxes(dt_boxes):+ """+ Sort text boxes in order from top to bottom, left to right+ args:+ dt_boxes(array):detected text boxes with shape [4, 2]+ return:+ sorted boxes(array) with shape [4, 2]+ """+ num_boxes = dt_boxes.shape[0]+ sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))+ _boxes = list(sorted_boxes)++ for i in range(num_boxes - 1):+ if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \+ (_boxes[i + 1][0][0] < _boxes[i][0][0]):+ tmp = _boxes[i]+ _boxes[i] = _boxes[i + 1]+ _boxes[i + 1] = tmp+ return _boxes++ @staticmethod+ def load_image(image_path):+ img, flag = check_and_read_gif(image_path)+ if not flag:+ img = cv2.imread(image_path)+ if img is None:+ raise ValueError(f"error in loading image:{image_path}")+ return img++ def __call__(self, img):+ if not isinstance(img, np.ndarray):+ raise ValueError("The format of the img is not ndarray")++ dt_boxes, elapse = self.text_detector(img)+ if dt_boxes is None or len(dt_boxes) < 1:+ return None, None+ img_crop_list = []++ # 检测框排序+ dt_boxes = self.sorted_boxes(dt_boxes)+ for bno in range(len(dt_boxes)):+ tmp_box = copy.deepcopy(dt_boxes[bno])+ img_crop = self.get_rotate_crop_image(img, tmp_box)+ img_crop_list.append(img_crop)++ img_crop_list, _, elapse = self.text_classifier(img_crop_list)++ rec_res, elapse = self.text_recognizer(img_crop_list)++ filter_boxes, filter_rec_res = [], []+ for box, rec_result in zip(dt_boxes, rec_res):+ text, score = rec_result+ if score >= drop_score:+ filter_boxes.append(box)+ filter_rec_res.append(rec_result)+ return filter_boxes, filter_rec_res+++if __name__ == '__main__':+ parser = argparse.ArgumentParser()++ parser.add_argument('--det_model_path', type=str,+ default='models/general_mobile_v1_det_infer.onnx')++ parser.add_argument('--direct_cls_model_path', type=str,+ default='models/ch_ppocr_mobile_v2.0_cls_infer.onnx')++ parser.add_argument('--rec_model_path', type=str,+ default='models/mobile_korean_rec_infer.onnx')++ parser.add_argument('--image_dir', type=str,+ default='test_images/korean/det_rec/2021-03-01_15-29-50.png')++ args = parser.parse_args()++ if args.det_model_path is None:+ raise FileNotFoundError(f'{args.det_model_path} is not found!')++ if args.direct_cls_model_path is None:+ raise FileNotFoundError(f'{args.direct_cls_model_path} is not found!')++ if args.rec_model_path is None:+ raise FileNotFoundError(f'{args.rec_model_path} is not found!')++ text_sys = TextSystem(args.det_model_path,+ args.rec_model_path,+ use_direct_cls=True,+ direct_cls_model_path=args.direct_cls_model_path)+ img_file_list = get_image_file_list(args.image_dir)+ for image_path in img_file_list:+ try:+ dt_boxes, rec_res = text_sys(image_path)+ if dt_boxes is not None:+ visualize(image_path, dt_boxes, rec_res)+ except ValueError:+ continuediff --git a/release/python_sdk/_gen_sdk/rapidocr/text_cls.py b/release/python_sdk/_gen_sdk/rapidocr/text_cls.pynew file mode 100644index 0000000..a023de7--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/text_cls.py@@ -0,0 +1,139 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import argparse+import copy+import math+import time++import cv2+import numpy as np+import onnxruntime as ort++try:+ from .utils_cls import (ClsPostProcess, check_and_read_gif,+ get_image_file_list)+except:+ from utils_cls import (ClsPostProcess, check_and_read_gif,+ get_image_file_list)+++class TextDirectionClassifier(object):+ def __init__(self, cls_model_path):+ self.cls_image_shape = [3, 48, 192]+ self.cls_batch_num = 6+ self.cls_thresh = 0.9+ self.postprocess_op = ClsPostProcess(label_list=['0', '180'])+ self.session = ort.InferenceSession(cls_model_path)++ def resize_norm_img(self, img):+ imgC, imgH, imgW = self.cls_image_shape+ h = img.shape[0]+ w = img.shape[1]+ if w / h > 6.4:+ # 按照训练集图像来截取+ new_width = int(6.4 * h)+ img = img[:, :new_width, :]++ ratio = w / float(h)+ if math.ceil(imgH * ratio) > imgW:+ resized_w = imgW+ else:+ resized_w = int(math.ceil(imgH * ratio))+ resized_image = cv2.resize(img, (resized_w, imgH))+ resized_image = resized_image.astype('float32')+ if self.cls_image_shape[0] == 1:+ resized_image = resized_image / 255+ resized_image = resized_image[np.newaxis, :]+ else:+ resized_image = resized_image.transpose((2, 0, 1)) / 255+ resized_image -= 0.5+ resized_image /= 0.5+ padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)+ padding_im[:, :, 0:resized_w] = resized_image+ return padding_im++ def load_image(self, image_dir):+ image_file_list = get_image_file_list(image_dir)+ valid_image_file_list = []+ img_list = []+ for image_file in image_file_list:+ img, flag = check_and_read_gif(image_file)+ if not flag:+ img = cv2.imread(image_file)+ if img is None:+ print(f"error in loading image:{image_file}")+ continue+ valid_image_file_list.append(image_file)+ img_list.append(img)+ return img_list++ def __call__(self, image_dir):+ if isinstance(image_dir[0], (list, str)):+ img_list = self.load_image(image_dir)+ else:+ img_list = image_dir++ img_list = copy.deepcopy(img_list)+ img_num = len(img_list)+ # Calculate the aspect ratio of all text bars+ width_list = []+ for img in img_list:+ width_list.append(img.shape[1] / float(img.shape[0]))+ # Sorting can speed up the cls process+ indices = np.argsort(np.array(width_list))++ cls_res = [['', 0.0]] * img_num+ batch_num = self.cls_batch_num+ elapse = 0+ for beg_img_no in range(0, img_num, batch_num):+ end_img_no = min(img_num, beg_img_no + batch_num)+ norm_img_batch = []+ max_wh_ratio = 0+ for ino in range(beg_img_no, end_img_no):+ h, w = img_list[indices[ino]].shape[0: 2]+ wh_ratio = w * 1.0 / h+ max_wh_ratio = max(max_wh_ratio, wh_ratio)+ for ino in range(beg_img_no, end_img_no):+ norm_img = self.resize_norm_img(img_list[indices[ino]])+ norm_img = norm_img[np.newaxis, :]+ norm_img_batch.append(norm_img)+ norm_img_batch = np.concatenate(norm_img_batch)+ onnx_inputs = {self.session.get_inputs()[0].name: norm_img_batch}++ starttime = time.time()+ prob_out = self.session.run(None, onnx_inputs)[0]++ cls_result = self.postprocess_op(prob_out)+ elapse += time.time() - starttime++ for rno in range(len(cls_result)):+ label, score = cls_result[rno]+ cls_res[indices[beg_img_no + rno]] = [label, score]+ if '180' in label and score > self.cls_thresh:+ img_list[indices[beg_img_no + rno]] = cv2.rotate(+ img_list[indices[beg_img_no + rno]], 1)+ return img_list, cls_res, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('--image_path', type=str, help='image_dir|image_path')+ parser.add_argument('--model_path', type=str, help='cls_model_dir')+ args = parser.parse_args()++ text_classifier = TextDirectionClassifier(args.model_path)++ img_list, cls_res, predict_time = text_classifier(args.image_path)+ for ino in range(len(img_list)):+ print(f"分类结果:{cls_res[ino]}")diff --git a/release/python_sdk/_gen_sdk/rapidocr/text_detect.py b/release/python_sdk/_gen_sdk/rapidocr/text_detect.pynew file mode 100644index 0000000..36cdf76--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/text_detect.py@@ -0,0 +1,158 @@+# 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.+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+import argparse+import time++import cv2+import numpy as np+import onnxruntime++try:+ from .utils_det import (DBPostProcess, check_and_read_gif,+ create_operators, draw_text_det_res, transform)+except:+ from utils_det import (DBPostProcess, check_and_read_gif, create_operators,+ draw_text_det_res, transform)+++class TextDetector(object):+ def __init__(self, det_model_path):+ pre_process_list = [{+ 'DetResizeForTest': {+ 'limit_side_len': 736,+ 'limit_type': 'min'+ }+ }, {+ 'NormalizeImage': {+ 'std': [0.229, 0.224, 0.225],+ 'mean': [0.485, 0.456, 0.406],+ 'scale': '1./255.',+ 'order': 'hwc'+ }+ }, {+ 'ToCHWImage': None+ }, {+ 'KeepKeys': {+ 'keep_keys': ['image', 'shape']+ }+ }]++ self.preprocess_op = create_operators(pre_process_list)+ self.postprocess_op = DBPostProcess(thresh=0.3,+ box_thresh=0.4,+ max_candidates=1000,+ unclip_ratio=1.8,+ use_dilation=True)+ self.session = onnxruntime.InferenceSession(det_model_path)+ self.input_name = self.session.get_inputs()[0].name+ self.output_name = self.session.get_outputs()[0].name++ def order_points_clockwise(self, pts):+ """+ reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py+ # sort the points based on their x-coordinates+ """+ xSorted = pts[np.argsort(pts[:, 0]), :]++ # grab the left-most and right-most points from the sorted+ # x-roodinate points+ leftMost = xSorted[:2, :]+ rightMost = xSorted[2:, :]++ # now, sort the left-most coordinates according to their+ # y-coordinates so we can grab the top-left and bottom-left+ # points, respectively+ leftMost = leftMost[np.argsort(leftMost[:, 1]), :]+ (tl, bl) = leftMost++ rightMost = rightMost[np.argsort(rightMost[:, 1]), :]+ (tr, br) = rightMost++ rect = np.array([tl, tr, br, bl], dtype="float32")+ return rect++ def clip_det_res(self, points, img_height, img_width):+ for pno in range(points.shape[0]):+ points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))+ points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))+ return points++ def filter_tag_det_res(self, dt_boxes, image_shape):+ img_height, img_width = image_shape[0:2]+ dt_boxes_new = []+ for box in dt_boxes:+ box = self.order_points_clockwise(box)+ box = self.clip_det_res(box, img_height, img_width)+ rect_width = int(np.linalg.norm(box[0] - box[1]))+ rect_height = int(np.linalg.norm(box[0] - box[3]))+ if rect_width <= 3 or rect_height <= 3:+ continue+ dt_boxes_new.append(box)+ dt_boxes = np.array(dt_boxes_new)+ return dt_boxes++ def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):+ img_height, img_width = image_shape[0:2]+ dt_boxes_new = []+ for box in dt_boxes:+ box = self.clip_det_res(box, img_height, img_width)+ dt_boxes_new.append(box)+ dt_boxes = np.array(dt_boxes_new)+ return dt_boxes++ def __call__(self, img):+ ori_im = img.copy()+ data = {'image': img}+ data = transform(data, self.preprocess_op)+ img, shape_list = data+ if img is None:+ return None, 0+ img = np.expand_dims(img, axis=0)+ img = img.astype(np.float32)+ shape_list = np.expand_dims(shape_list, axis=0)++ starttime = time.time()+ preds = self.session.run([self.output_name],+ {self.input_name: img})++ post_result = self.postprocess_op(preds[0], shape_list)+ dt_boxes = post_result[0]['points']+ dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)+ elapse = time.time() - starttime+ return dt_boxes, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('--image_path', type=str, default=None,+ help='image_path|image_dir')+ parser.add_argument('--model_path', type=str, default=None,+ help='model_path')+ args = parser.parse_args()++ text_detector = TextDetector(args.model_path)++ img, flag = check_and_read_gif(args.image_path)+ if not flag:+ img = cv2.imread(args.image_path)+ if img is None:+ raise ValueError(f"error in loading image:{args.image_path}")++ dt_boxes, elapse = text_detector(img)++ src_im = draw_text_det_res(dt_boxes, args.image_path)+ cv2.imwrite('det_results.jpg', src_im)+ print('图像已经保存为det_results.jpg了')diff --git a/release/python_sdk/_gen_sdk/rapidocr/text_recognize.py b/release/python_sdk/_gen_sdk/rapidocr/text_recognize.pynew file mode 100644index 0000000..52b8147--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/text_recognize.py@@ -0,0 +1,138 @@+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+import argparse+import math+import time+from pathlib import Path++import cv2+import numpy as np+import onnxruntime++try:+ from .utils_rec import (CTCLabelDecode, check_and_read_gif,+ get_image_file_list)+except:+ from utils_rec import (CTCLabelDecode, check_and_read_gif,+ get_image_file_list)+++root_path = Path(__file__).parent+++class TextRecognizer(object):+ def __init__(self, rec_model_path, dict_path):+ self.rec_image_shape = [3, 32, 320]+ self.character_type = 'ch'+ self.rec_batch_num = 6++ self.character_dict_path = dict_path+ self.use_space_char = True+ self.postprocess_op = CTCLabelDecode(self.character_dict_path,+ self.character_type,+ self.use_space_char)+ self.session = onnxruntime.InferenceSession(rec_model_path)++ def resize_norm_img(self, img, max_wh_ratio):+ img_channel, img_height, img_width = self.rec_image_shape+ assert img_channel == img.shape[2]+ if self.character_type == "ch":+ img_width = int((32 * max_wh_ratio))+ max_wh_ratio = 1+ h, w = img.shape[:2]+ ratio = w / float(h)+ if math.ceil(img_height * ratio) > img_width:+ resized_w = img_width+ else:+ resized_w = int(math.ceil(img_height * ratio))+ resized_image = cv2.resize(img, (resized_w, img_height))+ resized_image = resized_image.astype('float32')+ resized_image = resized_image.transpose((2, 0, 1)) / 255+ resized_image -= 0.5+ resized_image /= 0.5+ padding_im = np.zeros((img_channel, img_height, img_width),+ dtype=np.float32)+ padding_im[:, :, 0:resized_w] = resized_image+ return padding_im++ @staticmethod+ def load_image(image_dir):+ image_file_list = get_image_file_list(image_dir)+ valid_image_file_list = []+ img_list = []+ for image_file in image_file_list:+ img, flag = check_and_read_gif(image_file)+ if not flag:+ img = cv2.imread(image_file)+ if img is None:+ print(f"error in loading image:{image_file}")+ continue+ valid_image_file_list.append(image_file)+ img_list.append(img)+ return img_list++ def __call__(self, image_dir):+ if not isinstance(image_dir, list):+ img_list = self.load_image(image_dir)+ else:+ img_list = image_dir+ img_num = len(img_list)+ # Calculate the aspect ratio of all text bars+ width_list = []+ for img in img_list:+ width_list.append(img.shape[1] / float(img.shape[0]))++ indices = np.argsort(np.array(width_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)+ norm_img_batch = []+ max_wh_ratio = 0+ for ino in range(beg_img_no, end_img_no):+ h, w = img_list[indices[ino]].shape[0:2]+ wh_ratio = w * 1.0 / h+ max_wh_ratio = max(max_wh_ratio, wh_ratio)+ for ino in range(beg_img_no, end_img_no):+ norm_img = self.resize_norm_img(img_list[indices[ino]],+ max_wh_ratio)+ norm_img = norm_img[np.newaxis, :]+ norm_img_batch.append(norm_img)+ norm_img_batch = np.concatenate(norm_img_batch)+ norm_img_batch = norm_img_batch.astype(np.float32)++ # onnx模型推理+ starttime = time.time()+ onnx_inputs = {self.session.get_inputs()[0].name: norm_img_batch}+ preds = self.session.run(None, onnx_inputs)[0]++ rec_result = self.postprocess_op(preds)+ for rno in range(len(rec_result)):+ rec_res[indices[beg_img_no + rno]] = rec_result[rno]+ elapse += time.time() - starttime++ return rec_res, elapse+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument('image_dir', type=str, help='image_dir|image_path')+ parser.add_argument('model_path', type=str, help='rec_model_path')+ args = parser.parse_args()++ text_recognizer = TextRecognizer(args.model_path)+ rec_res, predict_time = text_recognizer(args.image_dir)+ print(f'识别结果: {rec_res}\t cost: {predict_time}s')diff --git a/release/python_sdk/_gen_sdk/rapidocr/utils_cls.py b/release/python_sdk/_gen_sdk/rapidocr/utils_cls.pynew file mode 100644index 0000000..2ce0551--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/utils_cls.py@@ -0,0 +1,66 @@+# 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 imghdr+import os++import cv2+++def get_image_file_list(img_file):+ imgs_lists = []+ if img_file is None or not os.path.exists(img_file):+ raise ValueError("not found any img file in {}".format(img_file))++ img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}+ if os.path.isfile(img_file) and imghdr.what(img_file) in img_end:+ imgs_lists.append(img_file)+ elif os.path.isdir(img_file):+ for single_file in os.listdir(img_file):+ file_path = os.path.join(img_file, single_file)+ if os.path.isfile(file_path) and imghdr.what(file_path) in img_end:+ imgs_lists.append(file_path)+ if len(imgs_lists) == 0:+ raise ValueError("not found any img file in {}".format(img_file))+ return imgs_lists+++def check_and_read_gif(img_path):+ if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:+ gif = cv2.VideoCapture(img_path)+ ret, frame = gif.read()+ if not ret:+ print("Cannot read {}. This gif image maybe corrupted.")+ return None, False+ if len(frame.shape) == 2 or frame.shape[-1] == 1:+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)+ imgvalue = frame[:, :, ::-1]+ return imgvalue, True+ return None, False+++class ClsPostProcess(object):+ """ Convert between text-label and text-index """++ def __init__(self, label_list, **kwargs):+ super(ClsPostProcess, self).__init__()+ self.label_list = label_list++ def __call__(self, preds, label=None, *args, **kwargs):+ pred_idxs = preds.argmax(axis=1)+ decode_out = [(self.label_list[idx], preds[i, idx])+ for i, idx in enumerate(pred_idxs)]+ if label is None:+ return decode_out+ label = [(self.label_list[idx], 1.0) for idx in label]+ return decode_out, labeldiff --git a/release/python_sdk/_gen_sdk/rapidocr/utils_det.py b/release/python_sdk/_gen_sdk/rapidocr/utils_det.pynew file mode 100644index 0000000..0d8ad68--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/utils_det.py@@ -0,0 +1,413 @@+"""+# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+"""+# coding:utf-8+from __future__ import (absolute_import, division, print_function,+ unicode_literals)++import os+import sys++import cv2+import numpy as np+import pyclipper+import six+from shapely.geometry import Polygon+++class DecodeImage(object):+ """ decode image """++ def __init__(self, img_mode='RGB', channel_first=False, **kwargs):+ self.img_mode = img_mode+ self.channel_first = channel_first++ def __call__(self, data):+ img = data['image']+ if six.PY2:+ assert type(img) is str and len(+ img) > 0, "invalid input 'img' in DecodeImage"+ else:+ assert type(img) is bytes and len(+ img) > 0, "invalid input 'img' in DecodeImage"+ img = np.frombuffer(img, dtype='uint8')+ img = cv2.imdecode(img, 1)+ if img is None:+ return None+ if self.img_mode == 'GRAY':+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)+ elif self.img_mode == 'RGB':+ assert img.shape[2] == 3, 'invalid shape of image[%s]' % (+ img.shape)+ img = img[:, :, ::-1]++ if self.channel_first:+ img = img.transpose((2, 0, 1))++ data['image'] = img+ return data+++class NormalizeImage(object):+ """ normalize image such as substract mean, divide std+ """++ def __init__(self, scale=None, mean=None, std=None, order='chw', **kwargs):+ if isinstance(scale, str):+ scale = eval(scale)+ self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)+ mean = mean if mean is not None else [0.485, 0.456, 0.406]+ std = std if std is not None else [0.229, 0.224, 0.225]++ shape = (3, 1, 1) if order == 'chw' else (1, 1, 3)+ self.mean = np.array(mean).reshape(shape).astype('float32')+ self.std = np.array(std).reshape(shape).astype('float32')++ def __call__(self, data):+ img = data['image']+ from PIL import Image+ if isinstance(img, Image.Image):+ img = np.array(img)++ assert isinstance(img,+ np.ndarray), "invalid input 'img' in NormalizeImage"+ data['image'] = (+ img.astype('float32') * self.scale - self.mean) / self.std+ return data+++class ToCHWImage(object):+ """ convert hwc image to chw image+ """++ def __init__(self, **kwargs):+ pass++ def __call__(self, data):+ img = data['image']+ from PIL import Image+ if isinstance(img, Image.Image):+ img = np.array(img)+ data['image'] = img.transpose((2, 0, 1))+ return data+++class KeepKeys(object):+ def __init__(self, keep_keys, **kwargs):+ self.keep_keys = keep_keys++ def __call__(self, data):+ data_list = []+ for key in self.keep_keys:+ data_list.append(data[key])+ return data_list+++class DetResizeForTest(object):+ def __init__(self, **kwargs):+ super(DetResizeForTest, self).__init__()+ self.resize_type = 0+ if 'image_shape' in kwargs:+ self.image_shape = kwargs['image_shape']+ self.resize_type = 1+ elif 'limit_side_len' in kwargs:+ self.limit_side_len = kwargs['limit_side_len']+ self.limit_type = kwargs.get('limit_type', 'min')++ if 'resize_long' in kwargs:+ self.resize_type = 2+ self.resize_long = kwargs.get('resize_long', 960)+ else:+ self.limit_side_len = 736+ self.limit_type = 'min'++ def __call__(self, data):+ img = data['image']+ src_h, src_w, _ = img.shape++ if self.resize_type == 0:+ # img, shape = self.resize_image_type0(img)+ img, [ratio_h, ratio_w] = self.resize_image_type0(img)+ elif self.resize_type == 2:+ img, [ratio_h, ratio_w] = self.resize_image_type2(img)+ else:+ # img, shape = self.resize_image_type1(img)+ img, [ratio_h, ratio_w] = self.resize_image_type1(img)+ data['image'] = img+ data['shape'] = np.array([src_h, src_w, ratio_h, ratio_w])+ return data++ def resize_image_type1(self, img):+ resize_h, resize_w = self.image_shape+ ori_h, ori_w = img.shape[:2] # (h, w, c)+ ratio_h = float(resize_h) / ori_h+ ratio_w = float(resize_w) / ori_w+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ # return img, np.array([ori_h, ori_w])+ return img, [ratio_h, ratio_w]++ def resize_image_type0(self, img):+ """+ resize image to a size multiple of 32 which is required by the network+ args:+ img(array): array with shape [h, w, c]+ return(tuple):+ img, (ratio_h, ratio_w)+ """+ limit_side_len = self.limit_side_len+ h, w, _ = img.shape++ # limit the max side+ if self.limit_type == 'max':+ if max(h, w) > limit_side_len:+ if h > w:+ ratio = float(limit_side_len) / h+ else:+ ratio = float(limit_side_len) / w+ else:+ ratio = 1.+ else:+ if min(h, w) < limit_side_len:+ if h < w:+ ratio = float(limit_side_len) / h+ else:+ ratio = float(limit_side_len) / w+ else:+ ratio = 1.+ resize_h = int(h * ratio)+ resize_w = int(w * ratio)++ resize_h = int(round(resize_h / 32) * 32)+ resize_w = int(round(resize_w / 32) * 32)++ try:+ if int(resize_w) <= 0 or int(resize_h) <= 0:+ return None, (None, None)+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ except:+ print(img.shape, resize_w, resize_h)+ sys.exit(0)+ ratio_h = resize_h / float(h)+ ratio_w = resize_w / float(w)+ return img, [ratio_h, ratio_w]++ def resize_image_type2(self, img):+ h, w, _ = img.shape++ resize_w = w+ resize_h = h++ # Fix the longer side+ if resize_h > resize_w:+ ratio = float(self.resize_long) / resize_h+ else:+ ratio = float(self.resize_long) / resize_w++ resize_h = int(resize_h * ratio)+ resize_w = int(resize_w * ratio)++ max_stride = 128+ resize_h = (resize_h + max_stride - 1) // max_stride * max_stride+ resize_w = (resize_w + max_stride - 1) // max_stride * max_stride+ img = cv2.resize(img, (int(resize_w), int(resize_h)))+ ratio_h = resize_h / float(h)+ ratio_w = resize_w / float(w)++ return img, [ratio_h, ratio_w]+++def transform(data, ops=None):+ """ transform """+ if ops is None:+ ops = []+ for op in ops:+ data = op(data)+ if data is None:+ return None+ return data+++def check_and_read_gif(img_path):+ if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:+ gif = cv2.VideoCapture(img_path)+ ret, frame = gif.read()+ if not ret:+ print("Cannot read {}. This gif image maybe corrupted.")+ return None, False+ if len(frame.shape) == 2 or frame.shape[-1] == 1:+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)+ imgvalue = frame[:, :, ::-1]+ return imgvalue, True+ return None, False+++def create_operators(op_param_list, global_config=None):+ """+ create operators based on the config++ Args:+ params(list): a dict list, used to create some operators+ """+ assert isinstance(+ op_param_list, list), ('operator config should be a list')+ ops = []+ for operator in op_param_list:+ assert isinstance(operator,+ dict) and len(operator) == 1, "yaml format error"+ op_name = list(operator)[0]+ param = {} if operator[op_name] is None else operator[op_name]+ if global_config is not None:+ param.update(global_config)+ op = eval(op_name)(**param)+ ops.append(op)+ return ops+++def draw_text_det_res(dt_boxes, img_path):+ src_im = cv2.imread(img_path)+ for box in dt_boxes:+ box = np.array(box).astype(np.int32).reshape(-1, 2)+ cv2.polylines(src_im, [box], True,+ color=(255, 255, 0), thickness=2)+ return src_im+++class DBPostProcess(object):+ """+ The post process for Differentiable Binarization (DB).+ """++ def __init__(self,+ thresh=0.3,+ box_thresh=0.7,+ max_candidates=1000,+ unclip_ratio=2.0,+ use_dilation=False,+ **kwargs):+ self.thresh = thresh+ self.box_thresh = box_thresh+ self.max_candidates = max_candidates+ self.unclip_ratio = unclip_ratio+ self.min_size = 3+ self.dilation_kernel = None if not use_dilation else np.array(+ [[1, 1], [1, 1]])++ def boxes_from_bitmap(self, pred, _bitmap, dest_width, dest_height):+ '''+ _bitmap: single map with shape (1, H, W),+ whose values are binarized as {0, 1}+ '''++ bitmap = _bitmap+ height, width = bitmap.shape++ outs = cv2.findContours((bitmap * 255).astype(np.uint8), cv2.RETR_LIST,+ cv2.CHAIN_APPROX_SIMPLE)+ if len(outs) == 3:+ img, contours, _ = outs[0], outs[1], outs[2]+ elif len(outs) == 2:+ contours, _ = outs[0], outs[1]++ num_contours = min(len(contours), self.max_candidates)++ boxes = []+ scores = []+ for index in range(num_contours):+ contour = contours[index]+ points, sside = self.get_mini_boxes(contour)+ if sside < self.min_size:+ continue+ points = np.array(points)+ score = self.box_score_fast(pred, points.reshape(-1, 2))+ if self.box_thresh > score:+ continue++ box = self.unclip(points).reshape(-1, 1, 2)+ box, sside = self.get_mini_boxes(box)+ if sside < self.min_size + 2:+ continue+ box = np.array(box)++ box[:, 0] = np.clip(+ np.round(box[:, 0] / width * dest_width), 0, dest_width)+ box[:, 1] = np.clip(+ np.round(box[:, 1] / height * dest_height), 0, dest_height)+ boxes.append(box.astype(np.int16))+ scores.append(score)+ return np.array(boxes, dtype=np.int16), scores++ def unclip(self, box):+ unclip_ratio = self.unclip_ratio+ poly = Polygon(box)+ distance = poly.area * unclip_ratio / poly.length+ offset = pyclipper.PyclipperOffset()+ offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)+ expanded = np.array(offset.Execute(distance))+ return expanded++ def get_mini_boxes(self, contour):+ bounding_box = cv2.minAreaRect(contour)+ points = sorted(list(cv2.boxPoints(bounding_box)), key=lambda x: x[0])++ index_1, index_2, index_3, index_4 = 0, 1, 2, 3+ if points[1][1] > points[0][1]:+ index_1 = 0+ index_4 = 1+ else:+ index_1 = 1+ index_4 = 0+ if points[3][1] > points[2][1]:+ index_2 = 2+ index_3 = 3+ else:+ index_2 = 3+ index_3 = 2++ box = [+ points[index_1], points[index_2], points[index_3], points[index_4]+ ]+ return box, min(bounding_box[1])++ def box_score_fast(self, bitmap, _box):+ h, w = bitmap.shape[:2]+ box = _box.copy()+ xmin = np.clip(np.floor(box[:, 0].min()).astype(np.int), 0, w - 1)+ xmax = np.clip(np.ceil(box[:, 0].max()).astype(np.int), 0, w - 1)+ ymin = np.clip(np.floor(box[:, 1].min()).astype(np.int), 0, h - 1)+ ymax = np.clip(np.ceil(box[:, 1].max()).astype(np.int), 0, h - 1)++ mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)+ box[:, 0] = box[:, 0] - xmin+ box[:, 1] = box[:, 1] - ymin+ cv2.fillPoly(mask, box.reshape(1, -1, 2).astype(np.int32), 1)+ return cv2.mean(bitmap[ymin:ymax + 1, xmin:xmax + 1], mask)[0]++ def __call__(self, pred, shape_list):+ pred = pred[:, 0, :, :]+ segmentation = pred > self.thresh++ boxes_batch = []+ for batch_index in range(pred.shape[0]):+ src_h, src_w, ratio_h, ratio_w = shape_list[batch_index]+ if self.dilation_kernel is not None:+ mask = cv2.dilate(+ np.array(segmentation[batch_index]).astype(np.uint8),+ self.dilation_kernel)+ else:+ mask = segmentation[batch_index]+ boxes, scores = self.boxes_from_bitmap(pred[batch_index], mask,+ src_w, src_h)+ boxes_batch.append({'points': boxes})+ return boxes_batchdiff --git a/release/python_sdk/_gen_sdk/rapidocr/utils_rec.py b/release/python_sdk/_gen_sdk/rapidocr/utils_rec.pynew file mode 100644index 0000000..b2a6a57--- /dev/null+++ b/release/python_sdk/_gen_sdk/rapidocr/utils_rec.py@@ -0,0 +1,124 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+# @File: PostProcess.py+# @Author: Max+import imghdr+import os++import cv2+import numpy as np+++class BaseRecLabelDecode(object):+ """ Convert between text-label and text-index """++ def __init__(self,+ character_dict_path=None,+ character_type='ch',+ use_space_char=False):+ self.character_str = ""+ assert character_dict_path is not None, "character_dict_path should not be None when character_type is ch"+ with open(character_dict_path, "rb") as fin:+ lines = fin.readlines()+ for line in lines:+ line = line.decode('utf-8').strip("\n").strip("\r\n")+ self.character_str += line+ if use_space_char:+ self.character_str += " "+ dict_character = list(self.character_str)++ self.character_type = character_type+ dict_character = self.add_special_char(dict_character)+ self.dict = {}+ for i, char in enumerate(dict_character):+ self.dict[char] = i+ self.character = dict_character++ def add_special_char(self, dict_character):+ return dict_character++ def decode(self, text_index, text_prob=None, is_remove_duplicate=True):+ """ convert text-index into text-label. """+ result_list = []+ ignored_tokens = self.get_ignored_tokens()+ batch_size = len(text_index)+ for batch_idx in range(batch_size):+ char_list = []+ conf_list = []+ for idx in range(len(text_index[batch_idx])):+ if text_index[batch_idx][idx] in ignored_tokens:+ continue+ if is_remove_duplicate:+ # only for predict+ if idx > 0 and text_index[batch_idx][idx - 1] == text_index[+ batch_idx][idx]:+ continue+ char_list.append(self.character[int(text_index[batch_idx][+ idx])])+ if text_prob is not None:+ conf_list.append(text_prob[batch_idx][idx])+ else:+ conf_list.append(1)+ text = ''.join(char_list)+ result_list.append((text, np.mean(conf_list)))+ return result_list++ def get_ignored_tokens(self):+ return [0] # for ctc blank+++class CTCLabelDecode(BaseRecLabelDecode):+ """ Convert between text-label and text-index """++ def __init__(self,+ character_dict_path=None,+ character_type='ch',+ use_space_char=False,+ **kwargs):+ super(CTCLabelDecode, self).__init__(character_dict_path,+ character_type, use_space_char)++ def __call__(self, preds, label=None, *args, **kwargs):+ preds_idx = preds.argmax(axis=2)+ preds_prob = preds.max(axis=2)+ text = self.decode(preds_idx, preds_prob)+ if label is None:+ return text+ label = self.decode(label, is_remove_duplicate=False)+ return text, label++ def add_special_char(self, dict_character):+ dict_character = ['blank'] + dict_character+ return dict_character+++def get_image_file_list(img_file):+ imgs_lists = []+ if img_file is None or not os.path.exists(img_file):+ raise Exception("not found any img file in {}".format(img_file))++ img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'GIF'}+ if os.path.isfile(img_file) and imghdr.what(img_file) in img_end:+ imgs_lists.append(img_file)+ elif os.path.isdir(img_file):+ for single_file in os.listdir(img_file):+ file_path = os.path.join(img_file, single_file)+ if imghdr.what(file_path) in img_end:+ imgs_lists.append(file_path)+ if len(imgs_lists) == 0:+ raise Exception("not found any img file in {}".format(img_file))+ return imgs_lists+++def check_and_read_gif(img_path):+ if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:+ gif = cv2.VideoCapture(img_path)+ ret, frame = gif.read()+ if not ret:+ print("Cannot read {}. This gif image maybe corrupted.")+ return None, False+ if len(frame.shape) == 2 or frame.shape[-1] == 1:+ frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)+ imgvalue = frame[:, :, ::-1]+ return imgvalue, True+ return None, Falsediff --git a/release/python_sdk/_gen_sdk/requirements.txt b/release/python_sdk/_gen_sdk/requirements.txtnew file mode 100644index 0000000..7c08b5d--- /dev/null+++ b/release/python_sdk/_gen_sdk/requirements.txt@@ -0,0 +1,6 @@+opencv_python==4.5.1.48+pyclipper==1.2.1+onnxruntime==1.7.0+six==1.15.0+Shapely==1.7.1+numpy==1.19.5diff --git a/release/python_sdk/_gen_sdk/setup.py b/release/python_sdk/_gen_sdk/setup.pynew file mode 100644index 0000000..ea73f6b--- /dev/null+++ b/release/python_sdk/_gen_sdk/setup.py@@ -0,0 +1,24 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+# @File: setup.py+# @Time: 2021/05/07 16:47:05+# @Author: Max++import setuptools++setuptools.setup(+ name="rapidocr",+ version="1.0.0",+ platforms="Windows & Linux",+ description="RapidOCR",+ author="SWHL",+ author_email="[email protected]",+ url="https://github.com/RapidAI/RapidOCR",+ license='Apache-2.0',+ py_modules="rapidocr",+ include_package_data=True,+ install_requires=["pyclipper==1.2.1", "onnxruntime==1.7.0",+ "opencv_python==4.5.1.48", "numpy==1.19.5",+ "six==1.15.0", "Shapely==1.7.1"],+ packages=setuptools.find_packages()+)diff --git a/release/python_sdk/_gen_sdk/test_demo.py b/release/python_sdk/_gen_sdk/test_demo.pynew file mode 100644index 0000000..dfb5cf8--- /dev/null+++ b/release/python_sdk/_gen_sdk/test_demo.py@@ -0,0 +1,39 @@+# !/usr/bin/env python+# -*- encoding: utf-8 -*-+# @Author: SWHL+# @Contact: [email protected]+import os+import time++import cv2++from rapidocr import TextSystem+++root_path = "sdk_rapidocr_v1.0.0/"+det_model_path = "resources/models/ch_PP-OCRv2_det_infer.onnx"+cls_model_path = "resources/models/ch_ppocr_mobile_v2.0_cls_infer.onnx"+rec_model_path = "resources/models/ch_mobile_v2.0_rec_infer.onnx"+dict_path = "resources/ppocr_keys_v1.txt"++det_model_path = root_path + det_model_path+rec_model_path = root_path + rec_model_path+cls_model_path = root_path + cls_model_path+dict_path = root_path + dict_path++text_sys = TextSystem(det_model_path,+ rec_model_path,+ cls_model_path,+ dict_path)++image_path = 'sdk_rapidocr_v1.0.0/images/1.jpg'+img = cv2.imread(image_path)++# rec_res:识别结果(结果,置信度)+# dt_boxes:对应文本框坐标+start_time = time.time()+dt_boxes, rec_res = text_sys(img)+txts = [rec_res[i][0] for i in range(len(rec_res))]++for txt in txts:+ print(txt)