predict_cls.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]
  34. self.cls_batch_num = args.cls_batch_num
  35. self.cls_thresh = args.cls_thresh
  36. postprocess_params = {
  37. 'name': 'ClsPostProcess',
  38. "label_list": args.label_list,
  39. }
  40. self.postprocess_op = build_post_process(postprocess_params)
  41. self.predictor, self.input_tensor, self.output_tensors, _ = \
  42. utility.create_predictor(args, 'cls', logger)
  43. self.use_onnx = args.use_onnx
  44. def resize_norm_img(self, img):
  45. imgC, imgH, imgW = self.cls_image_shape
  46. h = img.shape[0]
  47. w = img.shape[1]
  48. ratio = w / float(h)
  49. if math.ceil(imgH * ratio) > imgW:
  50. resized_w = imgW
  51. else:
  52. resized_w = int(math.ceil(imgH * ratio))
  53. resized_image = cv2.resize(img, (resized_w, imgH))
  54. resized_image = resized_image.astype('float32')
  55. if self.cls_image_shape[0] == 1:
  56. resized_image = resized_image / 255
  57. resized_image = resized_image[np.newaxis, :]
  58. else:
  59. resized_image = resized_image.transpose((2, 0, 1)) / 255
  60. resized_image -= 0.5
  61. resized_image /= 0.5
  62. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  63. padding_im[:, :, 0:resized_w] = resized_image
  64. return padding_im
  65. def __call__(self, img_list):
  66. img_list = copy.deepcopy(img_list)
  67. img_num = len(img_list)
  68. # Calculate the aspect ratio of all text bars
  69. width_list = []
  70. for img in img_list:
  71. width_list.append(img.shape[1] / float(img.shape[0]))
  72. # Sorting can speed up the cls process
  73. indices = np.argsort(np.array(width_list))
  74. cls_res = [['', 0.0]] * img_num
  75. batch_num = self.cls_batch_num
  76. elapse = 0
  77. for beg_img_no in range(0, img_num, batch_num):
  78. end_img_no = min(img_num, beg_img_no + batch_num)
  79. norm_img_batch = []
  80. max_wh_ratio = 0
  81. starttime = time.time()
  82. for ino in range(beg_img_no, end_img_no):
  83. h, w = img_list[indices[ino]].shape[0:2]
  84. wh_ratio = w * 1.0 / h
  85. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  86. for ino in range(beg_img_no, end_img_no):
  87. norm_img = self.resize_norm_img(img_list[indices[ino]])
  88. norm_img = norm_img[np.newaxis, :]
  89. norm_img_batch.append(norm_img)
  90. norm_img_batch = np.concatenate(norm_img_batch)
  91. norm_img_batch = norm_img_batch.copy()
  92. if self.use_onnx:
  93. input_dict = {}
  94. input_dict[self.input_tensor.name] = norm_img_batch
  95. outputs = self.predictor.run(self.output_tensors, input_dict)
  96. prob_out = outputs[0]
  97. else:
  98. self.input_tensor.copy_from_cpu(norm_img_batch)
  99. self.predictor.run()
  100. prob_out = self.output_tensors[0].copy_to_cpu()
  101. self.predictor.try_shrink_memory()
  102. cls_result = self.postprocess_op(prob_out)
  103. elapse += time.time() - starttime
  104. for rno in range(len(cls_result)):
  105. label, score = cls_result[rno]
  106. cls_res[indices[beg_img_no + rno]] = [label, score]
  107. if '180' in label and score > self.cls_thresh:
  108. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  109. img_list[indices[beg_img_no + rno]], 1)
  110. return img_list, cls_res, elapse
  111. def main(args):
  112. image_file_list = get_image_file_list(args.image_dir)
  113. text_classifier = TextClassifier(args)
  114. valid_image_file_list = []
  115. img_list = []
  116. for image_file in image_file_list:
  117. img, flag, _ = check_and_read(image_file)
  118. if not flag:
  119. img = cv2.imread(image_file)
  120. if img is None:
  121. logger.info("error in loading image:{}".format(image_file))
  122. continue
  123. valid_image_file_list.append(image_file)
  124. img_list.append(img)
  125. try:
  126. img_list, cls_res, predict_time = text_classifier(img_list)
  127. except Exception as E:
  128. logger.info(traceback.format_exc())
  129. logger.info(E)
  130. exit()
  131. for ino in range(len(img_list)):
  132. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  133. cls_res[ino]))
  134. if __name__ == "__main__":
  135. main(utility.parse_args())