predict_cls.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  27. import ocr.tools.infer.utility as utility
  28. from ocr.ppocr.postprocess import build_post_process
  29. from ocr.ppocr.utils.logging import get_logger
  30. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  31. logger = get_logger()
  32. class TextClassifier(object):
  33. shrink_memory_count = 0
  34. def __init__(self, args):
  35. self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]
  36. self.cls_batch_num = args.cls_batch_num
  37. self.cls_thresh = args.cls_thresh
  38. postprocess_params = {
  39. 'name': 'ClsPostProcess',
  40. "label_list": args.label_list,
  41. }
  42. self.postprocess_op = build_post_process(postprocess_params)
  43. self.predictor, self.input_tensor, self.output_tensors = \
  44. utility.create_predictor(args, 'cls', logger)
  45. def resize_norm_img(self, img):
  46. imgC, imgH, imgW = self.cls_image_shape
  47. h = img.shape[0]
  48. w = img.shape[1]
  49. ratio = w / float(h)
  50. if math.ceil(imgH * ratio) > imgW:
  51. resized_w = imgW
  52. else:
  53. resized_w = int(math.ceil(imgH * ratio))
  54. resized_image = cv2.resize(img, (resized_w, imgH))
  55. resized_image = resized_image.astype('float32')
  56. if self.cls_image_shape[0] == 1:
  57. resized_image = resized_image / 255
  58. resized_image = resized_image[np.newaxis, :]
  59. else:
  60. resized_image = resized_image.transpose((2, 0, 1)) / 255
  61. resized_image -= 0.5
  62. resized_image /= 0.5
  63. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  64. padding_im[:, :, 0:resized_w] = resized_image
  65. return padding_im
  66. def __call__(self, img_list):
  67. img_list = copy.deepcopy(img_list)
  68. img_num = len(img_list)
  69. # Calculate the aspect ratio of all text bars
  70. width_list = []
  71. for img in img_list:
  72. width_list.append(img.shape[1] / float(img.shape[0]))
  73. # Sorting can speed up the cls process
  74. indices = np.argsort(np.array(width_list))
  75. cls_res = [['', 0.0]] * img_num
  76. batch_num = self.cls_batch_num
  77. elapse = 0
  78. for beg_img_no in range(0, img_num, batch_num):
  79. end_img_no = min(img_num, beg_img_no + batch_num)
  80. norm_img_batch = []
  81. max_wh_ratio = 0
  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. starttime = time.time()
  93. self.input_tensor.copy_from_cpu(norm_img_batch)
  94. self.predictor.run()
  95. prob_out = self.output_tensors[0].copy_to_cpu()
  96. cls_result = self.postprocess_op(prob_out)
  97. elapse += time.time() - starttime
  98. for rno in range(len(cls_result)):
  99. label, score = cls_result[rno]
  100. cls_res[indices[beg_img_no + rno]] = [label, score]
  101. if '180' in label and score > self.cls_thresh:
  102. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  103. img_list[indices[beg_img_no + rno]], 1)
  104. # 释放内存
  105. # print("TextClassifier", self.predictor)
  106. # if TextClassifier.shrink_memory_count % 100 == 0:
  107. # print("TextClassifier shrink memory")
  108. self.predictor.clear_intermediate_tensor()
  109. self.predictor.try_shrink_memory()
  110. # TextClassifier.shrink_memory_count += 1
  111. return img_list, cls_res, elapse
  112. def main(args):
  113. image_file_list = get_image_file_list(args.image_dir)
  114. text_classifier = TextClassifier(args)
  115. valid_image_file_list = []
  116. img_list = []
  117. for image_file in image_file_list:
  118. img, flag = check_and_read_gif(image_file)
  119. if not flag:
  120. img = cv2.imread(image_file)
  121. if img is None:
  122. logger.info("error in loading image:{}".format(image_file))
  123. continue
  124. valid_image_file_list.append(image_file)
  125. img_list.append(img)
  126. try:
  127. img_list, cls_res, predict_time = text_classifier(img_list)
  128. except:
  129. logger.info(traceback.format_exc())
  130. logger.info(
  131. "ERROR!!!! \n"
  132. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  133. "If your model has tps module: "
  134. "TPS does not support variable shape.\n"
  135. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  136. exit()
  137. for ino in range(len(img_list)):
  138. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  139. cls_res[ino]))
  140. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  141. len(img_list), predict_time))
  142. if __name__ == "__main__":
  143. main(utility.parse_args())