predict_cls.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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, namespace_to_dict
  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. all_gpu_time = 0
  87. for beg_img_no in range(0, img_num, batch_num):
  88. end_img_no = min(img_num, beg_img_no + batch_num)
  89. norm_img_batch = []
  90. max_wh_ratio = 0
  91. for ino in range(beg_img_no, end_img_no):
  92. h, w = img_list[indices[ino]].shape[0:2]
  93. wh_ratio = w * 1.0 / h
  94. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  95. for ino in range(beg_img_no, end_img_no):
  96. norm_img = self.resize_norm_img(img_list[indices[ino]])
  97. norm_img = norm_img[np.newaxis, :]
  98. norm_img_batch.append(norm_img)
  99. norm_img_batch = np.concatenate(norm_img_batch)
  100. norm_img_batch = norm_img_batch.copy()
  101. starttime = time.time()
  102. _time = time.time()
  103. self.input_tensor.copy_from_cpu(norm_img_batch)
  104. self.predictor.run()
  105. prob_out = self.output_tensors[0].copy_to_cpu()
  106. gpu_time = time.time()-_time
  107. cls_result = self.postprocess_op(prob_out)
  108. elapse += time.time() - starttime
  109. for rno in range(len(cls_result)):
  110. label, score = cls_result[rno]
  111. cls_res[indices[beg_img_no + rno]] = [label, score]
  112. if '180' in label and score > self.cls_thresh:
  113. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  114. img_list[indices[beg_img_no + rno]], 1)
  115. # 释放内存
  116. # print("TextClassifier", self.predictor)
  117. # if TextClassifier.shrink_memory_count % 100 == 0:
  118. # print("TextClassifier shrink memory")
  119. self.predictor.clear_intermediate_tensor()
  120. self.predictor.try_shrink_memory()
  121. # TextClassifier.shrink_memory_count += 1
  122. log("ocr model predict time - cls - time " + str(all_gpu_time) + " - num " + str(img_num))
  123. return img_list, cls_res, elapse
  124. class TextClassifier2(object):
  125. shrink_memory_count = 0
  126. def __init__(self, args):
  127. self.cls_image_shape = [int(v) for v in args.cls_image_shape.split(",")]
  128. self.cls_batch_num = args.cls_batch_num
  129. self.cls_thresh = args.cls_thresh
  130. postprocess_params = {
  131. 'name': 'ClsPostProcess',
  132. "label_list": args.label_list,
  133. }
  134. self.postprocess_op = build_post_process(postprocess_params)
  135. self.args = args
  136. def resize_norm_img(self, img):
  137. imgC, imgH, imgW = self.cls_image_shape
  138. h = img.shape[0]
  139. w = img.shape[1]
  140. ratio = w / float(h)
  141. if math.ceil(imgH * ratio) > imgW:
  142. resized_w = imgW
  143. else:
  144. resized_w = int(math.ceil(imgH * ratio))
  145. resized_image = cv2.resize(img, (resized_w, imgH))
  146. resized_image = resized_image.astype('float32')
  147. if self.cls_image_shape[0] == 1:
  148. resized_image = resized_image / 255
  149. resized_image = resized_image[np.newaxis, :]
  150. else:
  151. resized_image = resized_image.transpose((2, 0, 1)) / 255
  152. resized_image -= 0.5
  153. resized_image /= 0.5
  154. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  155. padding_im[:, :, 0:resized_w] = resized_image
  156. return padding_im
  157. def __call__(self, img_list):
  158. from format_convert.convert_need_interface import from_gpu_interface_redis
  159. img_list = copy.deepcopy(img_list)
  160. img_num = len(img_list)
  161. # Calculate the aspect ratio of all text bars
  162. width_list = []
  163. for img in img_list:
  164. width_list.append(img.shape[1] / float(img.shape[0]))
  165. # Sorting can speed up the cls process
  166. indices = np.argsort(np.array(width_list))
  167. cls_res = [['', 0.0]] * img_num
  168. batch_num = self.cls_batch_num
  169. elapse = 0
  170. all_gpu_time = 0
  171. for beg_img_no in range(0, img_num, batch_num):
  172. # 预处理
  173. end_img_no = min(img_num, beg_img_no + batch_num)
  174. norm_img_batch = []
  175. max_wh_ratio = 0
  176. for ino in range(beg_img_no, end_img_no):
  177. h, w = img_list[indices[ino]].shape[0:2]
  178. wh_ratio = w * 1.0 / h
  179. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  180. for ino in range(beg_img_no, end_img_no):
  181. norm_img = self.resize_norm_img(img_list[indices[ino]])
  182. norm_img = norm_img[np.newaxis, :]
  183. norm_img_batch.append(norm_img)
  184. norm_img_batch = np.concatenate(norm_img_batch)
  185. norm_img_batch = norm_img_batch.copy()
  186. starttime = time.time()
  187. # # 压缩numpy
  188. # compressed_array = io.BytesIO()
  189. # np.savez_compressed(compressed_array, norm_img_batch)
  190. # compressed_array.seek(0)
  191. # norm_img_batch = compressed_array.read()
  192. # 调用GPU接口
  193. _dict = {"inputs": norm_img_batch, "args": str(namespace_to_dict(self.args)), "md5": _global.get("md5")}
  194. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="cls")
  195. if judge_error_code(result):
  196. logging.error("from_gpu_interface failed! " + str(result))
  197. raise requests.exceptions.RequestException
  198. preds = result.get("preds")
  199. gpu_time = result.get("gpu_time")
  200. all_gpu_time += round(gpu_time, 2)
  201. # # 解压numpy
  202. # decompressed_array = io.BytesIO()
  203. # decompressed_array.write(preds)
  204. # decompressed_array.seek(0)
  205. # preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  206. # log("inputs.shape" + str(preds.shape))
  207. # 后处理
  208. prob_out = preds
  209. cls_result = self.postprocess_op(prob_out)
  210. elapse += time.time() - starttime
  211. for rno in range(len(cls_result)):
  212. label, score = cls_result[rno]
  213. cls_res[indices[beg_img_no + rno]] = [label, score]
  214. if '180' in label and score > self.cls_thresh:
  215. img_list[indices[beg_img_no + rno]] = cv2.rotate(
  216. img_list[indices[beg_img_no + rno]], 1)
  217. log("ocr model predict time - cls - time " + str(all_gpu_time) + " - num " + str(img_num))
  218. return img_list, cls_res, elapse
  219. def main(args):
  220. image_file_list = get_image_file_list(args.image_dir)
  221. text_classifier = TextClassifier(args)
  222. valid_image_file_list = []
  223. img_list = []
  224. for image_file in image_file_list:
  225. img, flag = check_and_read_gif(image_file)
  226. if not flag:
  227. img = cv2.imread(image_file)
  228. if img is None:
  229. logger.info("error in loading image:{}".format(image_file))
  230. continue
  231. valid_image_file_list.append(image_file)
  232. img_list.append(img)
  233. try:
  234. img_list, cls_res, predict_time = text_classifier(img_list)
  235. except:
  236. logger.info(traceback.format_exc())
  237. logger.info(
  238. "ERROR!!!! \n"
  239. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  240. "If your model has tps module: "
  241. "TPS does not support variable shape.\n"
  242. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  243. exit()
  244. for ino in range(len(img_list)):
  245. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  246. cls_res[ino]))
  247. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  248. len(img_list), predict_time))
  249. if __name__ == "__main__":
  250. main(utility.parse_args())