|
| 1 | +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import copy |
| 15 | +import math |
| 16 | +import json |
| 17 | +from typing import List |
| 18 | + |
| 19 | +import cv2 |
| 20 | +import numpy as np |
| 21 | +from utils.utils import OrtInferSession |
| 22 | + |
| 23 | + |
| 24 | +class ClsPostProcess: |
| 25 | + """Convert between text-label and text-index""" |
| 26 | + |
| 27 | + def __init__(self, label_list): |
| 28 | + super(ClsPostProcess, self).__init__() |
| 29 | + self.label_list = label_list |
| 30 | + |
| 31 | + def __call__(self, preds, label=None): |
| 32 | + pred_idxs = preds.argmax(axis=1) |
| 33 | + decode_out = [ |
| 34 | + (self.label_list[idx], preds[i, idx]) for i, idx in enumerate(pred_idxs) |
| 35 | + ] |
| 36 | + if label is None: |
| 37 | + return decode_out |
| 38 | + |
| 39 | + label = [(self.label_list[idx], 1.0) for idx in label] |
| 40 | + return decode_out, label |
| 41 | + |
| 42 | + |
| 43 | +class TextClassifier: |
| 44 | + def __init__(self, path, config): |
| 45 | + self.cls_batch_num = config["batch_size"] |
| 46 | + self.cls_thresh = config["score_thresh"] |
| 47 | + |
| 48 | + session_instance = OrtInferSession(path) |
| 49 | + self.session = session_instance.session |
| 50 | + metamap = self.session.get_modelmeta().custom_metadata_map |
| 51 | + |
| 52 | + self.cls_image_shape = json.loads(metamap["shape"]) |
| 53 | + |
| 54 | + labels = json.loads(metamap["labels"]) |
| 55 | + self.postprocess_op = ClsPostProcess(labels) |
| 56 | + self.input_name = session_instance.get_input_name() |
| 57 | + |
| 58 | + def resize_norm_img(self, img): |
| 59 | + img_c, img_h, img_w = self.cls_image_shape |
| 60 | + h, w = img.shape[:2] |
| 61 | + ratio = w / float(h) |
| 62 | + if math.ceil(img_h * ratio) > img_w: |
| 63 | + resized_w = img_w |
| 64 | + else: |
| 65 | + resized_w = int(math.ceil(img_h * ratio)) |
| 66 | + |
| 67 | + resized_image = cv2.resize(img, (resized_w, img_h)) |
| 68 | + resized_image = resized_image.astype("float32") |
| 69 | + if img_c == 1: |
| 70 | + resized_image = resized_image / 255 |
| 71 | + resized_image = resized_image[np.newaxis, :] |
| 72 | + else: |
| 73 | + resized_image = resized_image.transpose((2, 0, 1)) / 255 |
| 74 | + |
| 75 | + resized_image -= 0.5 |
| 76 | + resized_image /= 0.5 |
| 77 | + padding_im = np.zeros((img_c, img_h, img_w), dtype=np.float32) |
| 78 | + padding_im[:, :, :resized_w] = resized_image |
| 79 | + return padding_im |
| 80 | + |
| 81 | + def __call__(self, img_list: List[np.ndarray]): |
| 82 | + if isinstance(img_list, np.ndarray): |
| 83 | + img_list = [img_list] |
| 84 | + |
| 85 | + img_list = copy.deepcopy(img_list) |
| 86 | + |
| 87 | + # Calculate the aspect ratio of all text bars |
| 88 | + width_list = [img.shape[1] / float(img.shape[0]) for img in img_list] |
| 89 | + |
| 90 | + # Sorting can speed up the cls process |
| 91 | + indices = np.argsort(np.array(width_list)) |
| 92 | + |
| 93 | + img_num = len(img_list) |
| 94 | + cls_res = [["", 0.0]] * img_num |
| 95 | + batch_num = self.cls_batch_num |
| 96 | + for beg_img_no in range(0, img_num, batch_num): |
| 97 | + end_img_no = min(img_num, beg_img_no + batch_num) |
| 98 | + max_wh_ratio = 0 |
| 99 | + for ino in range(beg_img_no, end_img_no): |
| 100 | + h, w = img_list[indices[ino]].shape[0:2] |
| 101 | + wh_ratio = w * 1.0 / h |
| 102 | + max_wh_ratio = max(max_wh_ratio, wh_ratio) |
| 103 | + |
| 104 | + norm_img_batch = [] |
| 105 | + for ino in range(beg_img_no, end_img_no): |
| 106 | + norm_img = self.resize_norm_img(img_list[indices[ino]]) |
| 107 | + norm_img = norm_img[np.newaxis, :] |
| 108 | + norm_img_batch.append(norm_img) |
| 109 | + norm_img_batch = np.concatenate(norm_img_batch).astype(np.float32) |
| 110 | + |
| 111 | + onnx_inputs = {self.input_name: norm_img_batch} |
| 112 | + prob_out = self.session.run(None, onnx_inputs)[0] |
| 113 | + cls_result = self.postprocess_op(prob_out) |
| 114 | + |
| 115 | + for rno in range(len(cls_result)): |
| 116 | + label, score = cls_result[rno] |
| 117 | + cls_res[indices[beg_img_no + rno]] = [label, score] |
| 118 | + if label == "180" and score > self.cls_thresh: |
| 119 | + img_list[indices[beg_img_no + rno]] = cv2.rotate( |
| 120 | + img_list[indices[beg_img_no + rno]], 1 |
| 121 | + ) |
| 122 | + return img_list, cls_res |
0 commit comments