predict_rec.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 numpy as np
  22. import math
  23. import time
  24. import traceback
  25. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  26. import paddle
  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 TextRecognizer(object):
  33. shrink_memory_count = 0
  34. def __init__(self, args):
  35. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  36. self.character_type = args.rec_char_type
  37. self.rec_batch_num = args.rec_batch_num
  38. self.rec_algorithm = args.rec_algorithm
  39. postprocess_params = {
  40. 'name': 'CTCLabelDecode',
  41. "character_type": args.rec_char_type,
  42. "character_dict_path": args.rec_char_dict_path,
  43. "use_space_char": args.use_space_char
  44. }
  45. if self.rec_algorithm == "SRN":
  46. postprocess_params = {
  47. 'name': 'SRNLabelDecode',
  48. "character_type": args.rec_char_type,
  49. "character_dict_path": args.rec_char_dict_path,
  50. "use_space_char": args.use_space_char
  51. }
  52. elif self.rec_algorithm == "RARE":
  53. postprocess_params = {
  54. 'name': 'AttnLabelDecode',
  55. "character_type": args.rec_char_type,
  56. "character_dict_path": args.rec_char_dict_path,
  57. "use_space_char": args.use_space_char
  58. }
  59. self.postprocess_op = build_post_process(postprocess_params)
  60. self.predictor, self.input_tensor, self.output_tensors = \
  61. utility.create_predictor(args, 'rec', logger)
  62. def resize_norm_img(self, img, max_wh_ratio):
  63. imgC, imgH, imgW = self.rec_image_shape
  64. assert imgC == img.shape[2]
  65. if self.character_type == "ch":
  66. imgW = int((32 * max_wh_ratio))
  67. h, w = img.shape[:2]
  68. ratio = w / float(h)
  69. if math.ceil(imgH * ratio) > imgW:
  70. resized_w = imgW
  71. else:
  72. resized_w = int(math.ceil(imgH * ratio))
  73. # print("predict_rec.py resize_norm_img resize shape", (resized_w, imgH))
  74. resized_image = cv2.resize(img, (resized_w, imgH))
  75. resized_image = resized_image.astype('float32')
  76. resized_image = resized_image.transpose((2, 0, 1)) / 255
  77. resized_image -= 0.5
  78. resized_image /= 0.5
  79. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  80. padding_im[:, :, 0:resized_w] = resized_image
  81. return padding_im
  82. def resize_norm_img_srn(self, img, image_shape):
  83. imgC, imgH, imgW = image_shape
  84. img_black = np.zeros((imgH, imgW))
  85. im_hei = img.shape[0]
  86. im_wid = img.shape[1]
  87. if im_wid <= im_hei * 1:
  88. img_new = cv2.resize(img, (imgH * 1, imgH))
  89. elif im_wid <= im_hei * 2:
  90. img_new = cv2.resize(img, (imgH * 2, imgH))
  91. elif im_wid <= im_hei * 3:
  92. img_new = cv2.resize(img, (imgH * 3, imgH))
  93. else:
  94. img_new = cv2.resize(img, (imgW, imgH))
  95. img_np = np.asarray(img_new)
  96. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  97. img_black[:, 0:img_np.shape[1]] = img_np
  98. img_black = img_black[:, :, np.newaxis]
  99. row, col, c = img_black.shape
  100. c = 1
  101. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  102. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  103. imgC, imgH, imgW = image_shape
  104. feature_dim = int((imgH / 8) * (imgW / 8))
  105. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  106. (feature_dim, 1)).astype('int64')
  107. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  108. (max_text_length, 1)).astype('int64')
  109. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  110. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  111. [-1, 1, max_text_length, max_text_length])
  112. gsrm_slf_attn_bias1 = np.tile(
  113. gsrm_slf_attn_bias1,
  114. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  115. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  116. [-1, 1, max_text_length, max_text_length])
  117. gsrm_slf_attn_bias2 = np.tile(
  118. gsrm_slf_attn_bias2,
  119. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  120. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  121. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  122. return [
  123. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  124. gsrm_slf_attn_bias2
  125. ]
  126. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  127. norm_img = self.resize_norm_img_srn(img, image_shape)
  128. norm_img = norm_img[np.newaxis, :]
  129. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  130. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  131. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  132. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  133. encoder_word_pos = encoder_word_pos.astype(np.int64)
  134. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  135. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  136. gsrm_slf_attn_bias2)
  137. def __call__(self, img_list):
  138. img_num = len(img_list)
  139. # Calculate the aspect ratio of all text bars
  140. width_list = []
  141. for img in img_list:
  142. width_list.append(img.shape[1] / float(img.shape[0]))
  143. # Sorting can speed up the recognition process
  144. indices = np.argsort(np.array(width_list))
  145. # rec_res = []
  146. rec_res = [['', 0.0]] * img_num
  147. batch_num = self.rec_batch_num
  148. elapse = 0
  149. for beg_img_no in range(0, img_num, batch_num):
  150. end_img_no = min(img_num, beg_img_no + batch_num)
  151. norm_img_batch = []
  152. max_wh_ratio = 0
  153. for ino in range(beg_img_no, end_img_no):
  154. # h, w = img_list[ino].shape[0:2]
  155. h, w = img_list[indices[ino]].shape[0:2]
  156. wh_ratio = w * 1.0 / h
  157. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  158. for ino in range(beg_img_no, end_img_no):
  159. if self.rec_algorithm != "SRN":
  160. norm_img = self.resize_norm_img(img_list[indices[ino]],
  161. max_wh_ratio)
  162. norm_img = norm_img[np.newaxis, :]
  163. norm_img_batch.append(norm_img)
  164. else:
  165. norm_img = self.process_image_srn(
  166. img_list[indices[ino]], self.rec_image_shape, 8, 25)
  167. encoder_word_pos_list = []
  168. gsrm_word_pos_list = []
  169. gsrm_slf_attn_bias1_list = []
  170. gsrm_slf_attn_bias2_list = []
  171. encoder_word_pos_list.append(norm_img[1])
  172. gsrm_word_pos_list.append(norm_img[2])
  173. gsrm_slf_attn_bias1_list.append(norm_img[3])
  174. gsrm_slf_attn_bias2_list.append(norm_img[4])
  175. norm_img_batch.append(norm_img[0])
  176. norm_img_batch = np.concatenate(norm_img_batch)
  177. norm_img_batch = norm_img_batch.copy()
  178. if self.rec_algorithm == "SRN":
  179. starttime = time.time()
  180. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  181. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  182. gsrm_slf_attn_bias1_list = np.concatenate(
  183. gsrm_slf_attn_bias1_list)
  184. gsrm_slf_attn_bias2_list = np.concatenate(
  185. gsrm_slf_attn_bias2_list)
  186. inputs = [
  187. norm_img_batch,
  188. encoder_word_pos_list,
  189. gsrm_word_pos_list,
  190. gsrm_slf_attn_bias1_list,
  191. gsrm_slf_attn_bias2_list,
  192. ]
  193. input_names = self.predictor.get_input_names()
  194. for i in range(len(input_names)):
  195. input_tensor = self.predictor.get_input_handle(input_names[
  196. i])
  197. input_tensor.copy_from_cpu(inputs[i])
  198. self.predictor.run()
  199. outputs = []
  200. for output_tensor in self.output_tensors:
  201. output = output_tensor.copy_to_cpu()
  202. outputs.append(output)
  203. preds = {"predict": outputs[2]}
  204. else:
  205. starttime = time.time()
  206. self.input_tensor.copy_from_cpu(norm_img_batch)
  207. self.predictor.run()
  208. outputs = []
  209. for output_tensor in self.output_tensors:
  210. output = output_tensor.copy_to_cpu()
  211. outputs.append(output)
  212. preds = outputs[0]
  213. # print("tools/infer/predict_rec preds", preds)
  214. rec_result = self.postprocess_op(preds)
  215. for rno in range(len(rec_result)):
  216. # print("predict_rec", img_num, batch_num, beg_img_no,
  217. # indices[beg_img_no + rno], len(rec_res))
  218. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  219. elapse += time.time() - starttime
  220. # 释放内存
  221. self.predictor.clear_intermediate_tensor()
  222. self.predictor.try_shrink_memory()
  223. return rec_res, elapse
  224. def main(args):
  225. image_file_list = get_image_file_list(args.image_dir)
  226. text_recognizer = TextRecognizer(args)
  227. valid_image_file_list = []
  228. img_list = []
  229. for image_file in image_file_list:
  230. img, flag = check_and_read_gif(image_file)
  231. if not flag:
  232. img = cv2.imread(image_file)
  233. if img is None:
  234. logger.info("error in loading image:{}".format(image_file))
  235. continue
  236. valid_image_file_list.append(image_file)
  237. img_list.append(img)
  238. try:
  239. rec_res, predict_time = text_recognizer(img_list)
  240. except:
  241. logger.info(traceback.format_exc())
  242. logger.info(
  243. "ERROR!!!! \n"
  244. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  245. "If your model has tps module: "
  246. "TPS does not support variable shape.\n"
  247. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  248. exit()
  249. for ino in range(len(img_list)):
  250. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  251. rec_res[ino]))
  252. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  253. len(img_list), predict_time))
  254. if __name__ == "__main__":
  255. main(utility.parse_args())