predict_cls.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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 os
  15. import sys
  16. __dir__ = os.path.dirname(os.path.abspath(__file__))
  17. sys.path.append(__dir__)
  18. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "../..")))
  19. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  20. import cv2
  21. import copy
  22. import numpy as np
  23. import math
  24. import time
  25. import traceback
  26. import tools.infer.utility as utility
  27. from ppocr.postprocess import build_post_process
  28. from ppocr.utils.logging import get_logger
  29. from ppocr.utils.utility import get_image_file_list, check_and_read
  30. logger = get_logger()
  31. class TextClassifier(object):
  32. def __init__(self, args):
  33. if os.path.exists(f"{args.cls_model_dir}/inference.yml"):
  34. model_config = utility.load_config(f"{args.cls_model_dir}/inference.yml")
  35. model_name = model_config.get("Global", {}).get("model_name", "")
  36. if model_name and model_name not in [
  37. "PP-LCNet_x1_0_textline_ori",
  38. "PP-LCNet_x0_25_textline_ori",
  39. ]:
  40. raise ValueError(
  41. f"{model_name} is not supported. Please check if the model is supported by the PaddleOCR wheel."
  42. )
  43. self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]
  44. self.cls_batch_num = args.cls_batch_num
  45. self.cls_thresh = args.cls_thresh
  46. postprocess_params = {
  47. "name": "ClsPostProcess",
  48. "label_list": args.label_list,
  49. }
  50. self.postprocess_op = build_post_process(postprocess_params)
  51. (
  52. self.predictor,
  53. self.input_tensor,
  54. self.output_tensors,
  55. _,
  56. ) = utility.create_predictor(args, "cls", logger)
  57. self.use_onnx = args.use_onnx
  58. def resize_norm_img(self, img):
  59. imgC, imgH, imgW = self.cls_image_shape
  60. h = img.shape[0]
  61. w = img.shape[1]
  62. ratio = w / float(h)
  63. if math.ceil(imgH * ratio) > imgW:
  64. resized_w = imgW
  65. else:
  66. resized_w = int(math.ceil(imgH * ratio))
  67. resized_image = cv2.resize(img, (resized_w, imgH))
  68. resized_image = resized_image.astype("float32")
  69. if self.cls_image_shape[0] == 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. resized_image -= 0.5
  75. resized_image /= 0.5
  76. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  77. padding_im[:, :, 0:resized_w] = resized_image
  78. return padding_im
  79. def __call__(self, img_list):
  80. img_list = copy.deepcopy(img_list)
  81. img_num = len(img_list)
  82. # Calculate the aspect ratio of all text bars
  83. width_list = []
  84. for img in img_list:
  85. width_list.append(img.shape[1] / float(img.shape[0]))
  86. # Sorting can speed up the cls process
  87. indices = np.argsort(np.array(width_list))
  88. cls_res = [["", 0.0]] * img_num
  89. batch_num = self.cls_batch_num
  90. elapse = 0
  91. for beg_img_no in range(0, img_num, batch_num):
  92. end_img_no = min(img_num, beg_img_no + batch_num)
  93. norm_img_batch = []
  94. max_wh_ratio = 0
  95. starttime = time.time()
  96. for ino in range(beg_img_no, end_img_no):
  97. h, w = img_list[indices[ino]].shape[0:2]
  98. wh_ratio = w * 1.0 / h
  99. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  100. for ino in range(beg_img_no, end_img_no):
  101. norm_img = self.resize_norm_img(img_list[indices[ino]])
  102. norm_img = norm_img[np.newaxis, :]
  103. norm_img_batch.append(norm_img)
  104. norm_img_batch = np.concatenate(norm_img_batch)
  105. norm_img_batch = norm_img_batch.copy()
  106. if self.use_onnx:
  107. input_dict = {}
  108. input_dict[self.input_tensor.name] = norm_img_batch
  109. outputs = self.predictor.run(self.output_tensors, input_dict)
  110. prob_out = outputs[0]
  111. else:
  112. self.input_tensor.copy_from_cpu(norm_img_batch)
  113. self.predictor.run()
  114. prob_out = self.output_tensors[0].copy_to_cpu()
  115. self.predictor.try_shrink_memory()
  116. cls_result = self.postprocess_op(prob_out)
  117. elapse += time.time() - starttime
  118. for rno in range(len(cls_result)):
  119. label, score = cls_result[rno]
  120. cls_res[indices[beg_img_no + rno]] = [label, score]
  121. if "180" in label and score > self.cls_thresh:
  122. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  123. img_list[indices[beg_img_no + rno]], 1
  124. )
  125. return img_list, cls_res, elapse
  126. def main(args):
  127. image_file_list = get_image_file_list(args.image_dir)
  128. text_classifier = TextClassifier(args)
  129. valid_image_file_list = []
  130. img_list = []
  131. for image_file in image_file_list:
  132. img, flag, _ = check_and_read(image_file)
  133. if not flag:
  134. img = cv2.imread(image_file)
  135. if img is None:
  136. logger.info("error in loading image:{}".format(image_file))
  137. continue
  138. valid_image_file_list.append(image_file)
  139. img_list.append(img)
  140. try:
  141. img_list, cls_res, predict_time = text_classifier(img_list)
  142. except Exception as E:
  143. logger.info(traceback.format_exc())
  144. logger.info(E)
  145. exit()
  146. for ino in range(len(img_list)):
  147. logger.info(
  148. "Predicts of {}:{}".format(valid_image_file_list[ino], cls_res[ino])
  149. )
  150. if __name__ == "__main__":
  151. main(utility.parse_args())