predict_cls.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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.append(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_gif
  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. def resize_norm_img(self, img):
  44. imgC, imgH, imgW = self.cls_image_shape
  45. h = img.shape[0]
  46. w = img.shape[1]
  47. ratio = w / float(h)
  48. if math.ceil(imgH * ratio) > imgW:
  49. resized_w = imgW
  50. else:
  51. resized_w = int(math.ceil(imgH * ratio))
  52. resized_image = cv2.resize(img, (resized_w, imgH))
  53. resized_image = resized_image.astype('float32')
  54. if self.cls_image_shape[0] == 1:
  55. resized_image = resized_image / 255
  56. resized_image = resized_image[np.newaxis, :]
  57. else:
  58. resized_image = resized_image.transpose((2, 0, 1)) / 255
  59. resized_image -= 0.5
  60. resized_image /= 0.5
  61. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  62. padding_im[:, :, 0:resized_w] = resized_image
  63. return padding_im
  64. def __call__(self, img_list):
  65. img_list = copy.deepcopy(img_list)
  66. img_num = len(img_list)
  67. # Calculate the aspect ratio of all text bars
  68. width_list = []
  69. for img in img_list:
  70. width_list.append(img.shape[1] / float(img.shape[0]))
  71. # Sorting can speed up the cls process
  72. indices = np.argsort(np.array(width_list))
  73. cls_res = [['', 0.0]] * img_num
  74. batch_num = self.cls_batch_num
  75. elapse = 0
  76. for beg_img_no in range(0, img_num, batch_num):
  77. end_img_no = min(img_num, beg_img_no + batch_num)
  78. norm_img_batch = []
  79. max_wh_ratio = 0
  80. for ino in range(beg_img_no, end_img_no):
  81. h, w = img_list[indices[ino]].shape[0:2]
  82. wh_ratio = w * 1.0 / h
  83. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  84. for ino in range(beg_img_no, end_img_no):
  85. norm_img = self.resize_norm_img(img_list[indices[ino]])
  86. norm_img = norm_img[np.newaxis, :]
  87. norm_img_batch.append(norm_img)
  88. norm_img_batch = np.concatenate(norm_img_batch)
  89. norm_img_batch = norm_img_batch.copy()
  90. starttime = time.time()
  91. self.input_tensor.copy_from_cpu(norm_img_batch)
  92. self.predictor.run()
  93. prob_out = self.output_tensors[0].copy_to_cpu()
  94. cls_result = self.postprocess_op(prob_out)
  95. elapse += time.time() - starttime
  96. for rno in range(len(cls_result)):
  97. label, score = cls_result[rno]
  98. cls_res[indices[beg_img_no + rno]] = [label, score]
  99. if '180' in label and score > self.cls_thresh:
  100. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  101. img_list[indices[beg_img_no + rno]], 1)
  102. return img_list, cls_res, elapse
  103. def main(args):
  104. image_file_list = get_image_file_list(args.image_dir)
  105. text_classifier = TextClassifier(args)
  106. valid_image_file_list = []
  107. img_list = []
  108. for image_file in image_file_list:
  109. img, flag = check_and_read_gif(image_file)
  110. if not flag:
  111. img = cv2.imread(image_file)
  112. if img is None:
  113. logger.info("error in loading image:{}".format(image_file))
  114. continue
  115. valid_image_file_list.append(image_file)
  116. img_list.append(img)
  117. try:
  118. img_list, cls_res, predict_time = text_classifier(img_list)
  119. except:
  120. logger.info(traceback.format_exc())
  121. logger.info(
  122. "ERROR!!!! \n"
  123. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  124. "If your model has tps module: "
  125. "TPS does not support variable shape.\n"
  126. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  127. exit()
  128. for ino in range(len(img_list)):
  129. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  130. cls_res[ino]))
  131. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  132. len(img_list), predict_time))
  133. if __name__ == "__main__":
  134. main(utility.parse_args())