predict_cls.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # encoding=utf8
  2. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import io
  16. import logging
  17. import os
  18. import sys
  19. # __dir__ = os.path.dirname(os.path.abspath(__file__))
  20. import zlib
  21. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../../")
  22. import requests
  23. from format_convert import _global
  24. from format_convert.utils import judge_error_code, log
  25. # sys.path.append(__dir__)
  26. # sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))
  27. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  28. import cv2
  29. import copy
  30. import numpy as np
  31. import math
  32. import time
  33. import traceback
  34. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  35. import ocr.tools.infer.utility as utility
  36. from ocr.ppocr.postprocess import build_post_process
  37. from ocr.ppocr.utils.logging import get_logger
  38. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  39. logger = get_logger()
  40. class TextClassifier(object):
  41. shrink_memory_count = 0
  42. def __init__(self, args):
  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. self.predictor, self.input_tensor, self.output_tensors = \
  52. utility.create_predictor(args, 'cls', logger)
  53. def resize_norm_img(self, img):
  54. imgC, imgH, imgW = self.cls_image_shape
  55. h = img.shape[0]
  56. w = img.shape[1]
  57. ratio = w / float(h)
  58. if math.ceil(imgH * ratio) > imgW:
  59. resized_w = imgW
  60. else:
  61. resized_w = int(math.ceil(imgH * ratio))
  62. resized_image = cv2.resize(img, (resized_w, imgH))
  63. resized_image = resized_image.astype('float32')
  64. if self.cls_image_shape[0] == 1:
  65. resized_image = resized_image / 255
  66. resized_image = resized_image[np.newaxis, :]
  67. else:
  68. resized_image = resized_image.transpose((2, 0, 1)) / 255
  69. resized_image -= 0.5
  70. resized_image /= 0.5
  71. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  72. padding_im[:, :, 0:resized_w] = resized_image
  73. return padding_im
  74. def __call__(self, img_list):
  75. img_list = copy.deepcopy(img_list)
  76. img_num = len(img_list)
  77. # Calculate the aspect ratio of all text bars
  78. width_list = []
  79. for img in img_list:
  80. width_list.append(img.shape[1] / float(img.shape[0]))
  81. # Sorting can speed up the cls process
  82. indices = np.argsort(np.array(width_list))
  83. cls_res = [['', 0.0]] * img_num
  84. batch_num = self.cls_batch_num
  85. elapse = 0
  86. for beg_img_no in range(0, img_num, batch_num):
  87. end_img_no = min(img_num, beg_img_no + batch_num)
  88. norm_img_batch = []
  89. max_wh_ratio = 0
  90. for ino in range(beg_img_no, end_img_no):
  91. h, w = img_list[indices[ino]].shape[0:2]
  92. wh_ratio = w * 1.0 / h
  93. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  94. for ino in range(beg_img_no, end_img_no):
  95. norm_img = self.resize_norm_img(img_list[indices[ino]])
  96. norm_img = norm_img[np.newaxis, :]
  97. norm_img_batch.append(norm_img)
  98. norm_img_batch = np.concatenate(norm_img_batch)
  99. norm_img_batch = norm_img_batch.copy()
  100. starttime = time.time()
  101. self.input_tensor.copy_from_cpu(norm_img_batch)
  102. self.predictor.run()
  103. prob_out = self.output_tensors[0].copy_to_cpu()
  104. cls_result = self.postprocess_op(prob_out)
  105. elapse += time.time() - starttime
  106. for rno in range(len(cls_result)):
  107. label, score = cls_result[rno]
  108. cls_res[indices[beg_img_no + rno]] = [label, score]
  109. if '180' in label and score > self.cls_thresh:
  110. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  111. img_list[indices[beg_img_no + rno]], 1)
  112. # 释放内存
  113. # print("TextClassifier", self.predictor)
  114. # if TextClassifier.shrink_memory_count % 100 == 0:
  115. # print("TextClassifier shrink memory")
  116. self.predictor.clear_intermediate_tensor()
  117. self.predictor.try_shrink_memory()
  118. # TextClassifier.shrink_memory_count += 1
  119. return img_list, cls_res, elapse
  120. class TextClassifier2(object):
  121. shrink_memory_count = 0
  122. def __init__(self, args):
  123. self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]
  124. self.cls_batch_num = args.cls_batch_num
  125. self.cls_thresh = args.cls_thresh
  126. postprocess_params = {
  127. 'name': 'ClsPostProcess',
  128. "label_list": args.label_list,
  129. }
  130. self.postprocess_op = build_post_process(postprocess_params)
  131. self.args = args
  132. def resize_norm_img(self, img):
  133. imgC, imgH, imgW = self.cls_image_shape
  134. h = img.shape[0]
  135. w = img.shape[1]
  136. ratio = w / float(h)
  137. if math.ceil(imgH * ratio) > imgW:
  138. resized_w = imgW
  139. else:
  140. resized_w = int(math.ceil(imgH * ratio))
  141. resized_image = cv2.resize(img, (resized_w, imgH))
  142. resized_image = resized_image.astype('float32')
  143. if self.cls_image_shape[0] == 1:
  144. resized_image = resized_image / 255
  145. resized_image = resized_image[np.newaxis, :]
  146. else:
  147. resized_image = resized_image.transpose((2, 0, 1)) / 255
  148. resized_image -= 0.5
  149. resized_image /= 0.5
  150. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  151. padding_im[:, :, 0:resized_w] = resized_image
  152. return padding_im
  153. def __call__(self, img_list):
  154. from format_convert.convert_need_interface import from_gpu_interface_redis
  155. img_list = copy.deepcopy(img_list)
  156. img_num = len(img_list)
  157. # Calculate the aspect ratio of all text bars
  158. width_list = []
  159. for img in img_list:
  160. width_list.append(img.shape[1] / float(img.shape[0]))
  161. # Sorting can speed up the cls process
  162. indices = np.argsort(np.array(width_list))
  163. cls_res = [['', 0.0]] * img_num
  164. batch_num = self.cls_batch_num
  165. elapse = 0
  166. all_gpu_time = 0
  167. for beg_img_no in range(0, img_num, batch_num):
  168. # 预处理
  169. end_img_no = min(img_num, beg_img_no + batch_num)
  170. norm_img_batch = []
  171. max_wh_ratio = 0
  172. for ino in range(beg_img_no, end_img_no):
  173. h, w = img_list[indices[ino]].shape[0:2]
  174. wh_ratio = w * 1.0 / h
  175. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  176. for ino in range(beg_img_no, end_img_no):
  177. norm_img = self.resize_norm_img(img_list[indices[ino]])
  178. norm_img = norm_img[np.newaxis, :]
  179. norm_img_batch.append(norm_img)
  180. norm_img_batch = np.concatenate(norm_img_batch)
  181. norm_img_batch = norm_img_batch.copy()
  182. starttime = time.time()
  183. # # 压缩numpy
  184. # compressed_array = io.BytesIO()
  185. # np.savez_compressed(compressed_array, norm_img_batch)
  186. # compressed_array.seek(0)
  187. # norm_img_batch = compressed_array.read()
  188. # 调用GPU接口
  189. _dict = {"inputs": norm_img_batch, "args": self.args, "md5": _global.get("md5")}
  190. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="cls")
  191. if judge_error_code(result):
  192. logging.error("from_gpu_interface failed! " + str(result))
  193. raise requests.exceptions.RequestException
  194. preds = result.get("preds")
  195. gpu_time = result.get("gpu_time")
  196. all_gpu_time += round(gpu_time, 2)
  197. # # 解压numpy
  198. # decompressed_array = io.BytesIO()
  199. # decompressed_array.write(preds)
  200. # decompressed_array.seek(0)
  201. # preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  202. # log("inputs.shape" + str(preds.shape))
  203. # 后处理
  204. prob_out = preds
  205. cls_result = self.postprocess_op(prob_out)
  206. elapse += time.time() - starttime
  207. for rno in range(len(cls_result)):
  208. label, score = cls_result[rno]
  209. cls_res[indices[beg_img_no + rno]] = [label, score]
  210. if '180' in label and score > self.cls_thresh:
  211. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  212. img_list[indices[beg_img_no + rno]], 1)
  213. log("ocr model predict time - cls - time " + str(all_gpu_time) + " - num " + str(img_num))
  214. return img_list, cls_res, elapse
  215. def main(args):
  216. image_file_list = get_image_file_list(args.image_dir)
  217. text_classifier = TextClassifier(args)
  218. valid_image_file_list = []
  219. img_list = []
  220. for image_file in image_file_list:
  221. img, flag = check_and_read_gif(image_file)
  222. if not flag:
  223. img = cv2.imread(image_file)
  224. if img is None:
  225. logger.info("error in loading image:{}".format(image_file))
  226. continue
  227. valid_image_file_list.append(image_file)
  228. img_list.append(img)
  229. try:
  230. img_list, cls_res, predict_time = text_classifier(img_list)
  231. except:
  232. logger.info(traceback.format_exc())
  233. logger.info(
  234. "ERROR!!!! \n"
  235. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  236. "If your model has tps module: "
  237. "TPS does not support variable shape.\n"
  238. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  239. exit()
  240. for ino in range(len(img_list)):
  241. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  242. cls_res[ino]))
  243. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  244. len(img_list), predict_time))
  245. if __name__ == "__main__":
  246. main(utility.parse_args())