predict_rec.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. import paddle
  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 TextRecognizer(object):
  32. def __init__(self, args):
  33. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  34. self.character_type = args.rec_char_type
  35. self.rec_batch_num = args.rec_batch_num
  36. self.rec_algorithm = args.rec_algorithm
  37. postprocess_params = {
  38. 'name': 'CTCLabelDecode',
  39. "character_type": args.rec_char_type,
  40. "character_dict_path": args.rec_char_dict_path,
  41. "use_space_char": args.use_space_char
  42. }
  43. if self.rec_algorithm == "SRN":
  44. postprocess_params = {
  45. 'name': 'SRNLabelDecode',
  46. "character_type": args.rec_char_type,
  47. "character_dict_path": args.rec_char_dict_path,
  48. "use_space_char": args.use_space_char
  49. }
  50. elif self.rec_algorithm == "RARE":
  51. postprocess_params = {
  52. 'name': 'AttnLabelDecode',
  53. "character_type": args.rec_char_type,
  54. "character_dict_path": args.rec_char_dict_path,
  55. "use_space_char": args.use_space_char
  56. }
  57. self.postprocess_op = build_post_process(postprocess_params)
  58. self.predictor, self.input_tensor, self.output_tensors = \
  59. utility.create_predictor(args, 'rec', logger)
  60. def resize_norm_img(self, img, max_wh_ratio):
  61. imgC, imgH, imgW = self.rec_image_shape
  62. assert imgC == img.shape[2]
  63. if self.character_type == "ch":
  64. imgW = int((32 * max_wh_ratio))
  65. h, w = img.shape[:2]
  66. ratio = w / float(h)
  67. if math.ceil(imgH * ratio) > imgW:
  68. resized_w = imgW
  69. else:
  70. resized_w = int(math.ceil(imgH * ratio))
  71. resized_image = cv2.resize(img, (resized_w, imgH))
  72. resized_image = resized_image.astype('float32')
  73. resized_image = resized_image.transpose((2, 0, 1)) / 255
  74. resized_image -= 0.5
  75. resized_image /= 0.5
  76. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  77. padding_im[:, :, 0:resized_w] = resized_image
  78. return padding_im
  79. def resize_norm_img_srn(self, img, image_shape):
  80. imgC, imgH, imgW = image_shape
  81. img_black = np.zeros((imgH, imgW))
  82. im_hei = img.shape[0]
  83. im_wid = img.shape[1]
  84. if im_wid <= im_hei * 1:
  85. img_new = cv2.resize(img, (imgH * 1, imgH))
  86. elif im_wid <= im_hei * 2:
  87. img_new = cv2.resize(img, (imgH * 2, imgH))
  88. elif im_wid <= im_hei * 3:
  89. img_new = cv2.resize(img, (imgH * 3, imgH))
  90. else:
  91. img_new = cv2.resize(img, (imgW, imgH))
  92. img_np = np.asarray(img_new)
  93. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  94. img_black[:, 0:img_np.shape[1]] = img_np
  95. img_black = img_black[:, :, np.newaxis]
  96. row, col, c = img_black.shape
  97. c = 1
  98. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  99. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  100. imgC, imgH, imgW = image_shape
  101. feature_dim = int((imgH / 8) * (imgW / 8))
  102. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  103. (feature_dim, 1)).astype('int64')
  104. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  105. (max_text_length, 1)).astype('int64')
  106. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  107. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  108. [-1, 1, max_text_length, max_text_length])
  109. gsrm_slf_attn_bias1 = np.tile(
  110. gsrm_slf_attn_bias1,
  111. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  112. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  113. [-1, 1, max_text_length, max_text_length])
  114. gsrm_slf_attn_bias2 = np.tile(
  115. gsrm_slf_attn_bias2,
  116. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  117. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  118. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  119. return [
  120. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  121. gsrm_slf_attn_bias2
  122. ]
  123. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  124. norm_img = self.resize_norm_img_srn(img, image_shape)
  125. norm_img = norm_img[np.newaxis, :]
  126. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  127. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  128. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  129. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  130. encoder_word_pos = encoder_word_pos.astype(np.int64)
  131. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  132. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  133. gsrm_slf_attn_bias2)
  134. def __call__(self, img_list):
  135. img_num = len(img_list)
  136. # Calculate the aspect ratio of all text bars
  137. width_list = []
  138. for img in img_list:
  139. width_list.append(img.shape[1] / float(img.shape[0]))
  140. # Sorting can speed up the recognition process
  141. indices = np.argsort(np.array(width_list))
  142. # rec_res = []
  143. rec_res = [['', 0.0]] * img_num
  144. batch_num = self.rec_batch_num
  145. elapse = 0
  146. for beg_img_no in range(0, img_num, batch_num):
  147. end_img_no = min(img_num, beg_img_no + batch_num)
  148. norm_img_batch = []
  149. max_wh_ratio = 0
  150. for ino in range(beg_img_no, end_img_no):
  151. # h, w = img_list[ino].shape[0:2]
  152. h, w = img_list[indices[ino]].shape[0:2]
  153. wh_ratio = w * 1.0 / h
  154. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  155. for ino in range(beg_img_no, end_img_no):
  156. if self.rec_algorithm != "SRN":
  157. norm_img = self.resize_norm_img(img_list[indices[ino]],
  158. max_wh_ratio)
  159. norm_img = norm_img[np.newaxis, :]
  160. norm_img_batch.append(norm_img)
  161. else:
  162. norm_img = self.process_image_srn(
  163. img_list[indices[ino]], self.rec_image_shape, 8, 25)
  164. encoder_word_pos_list = []
  165. gsrm_word_pos_list = []
  166. gsrm_slf_attn_bias1_list = []
  167. gsrm_slf_attn_bias2_list = []
  168. encoder_word_pos_list.append(norm_img[1])
  169. gsrm_word_pos_list.append(norm_img[2])
  170. gsrm_slf_attn_bias1_list.append(norm_img[3])
  171. gsrm_slf_attn_bias2_list.append(norm_img[4])
  172. norm_img_batch.append(norm_img[0])
  173. norm_img_batch = np.concatenate(norm_img_batch)
  174. norm_img_batch = norm_img_batch.copy()
  175. if self.rec_algorithm == "SRN":
  176. starttime = time.time()
  177. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  178. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  179. gsrm_slf_attn_bias1_list = np.concatenate(
  180. gsrm_slf_attn_bias1_list)
  181. gsrm_slf_attn_bias2_list = np.concatenate(
  182. gsrm_slf_attn_bias2_list)
  183. inputs = [
  184. norm_img_batch,
  185. encoder_word_pos_list,
  186. gsrm_word_pos_list,
  187. gsrm_slf_attn_bias1_list,
  188. gsrm_slf_attn_bias2_list,
  189. ]
  190. input_names = self.predictor.get_input_names()
  191. for i in range(len(input_names)):
  192. input_tensor = self.predictor.get_input_handle(input_names[
  193. i])
  194. input_tensor.copy_from_cpu(inputs[i])
  195. self.predictor.run()
  196. outputs = []
  197. for output_tensor in self.output_tensors:
  198. output = output_tensor.copy_to_cpu()
  199. outputs.append(output)
  200. preds = {"predict": outputs[2]}
  201. else:
  202. starttime = time.time()
  203. self.input_tensor.copy_from_cpu(norm_img_batch)
  204. self.predictor.run()
  205. outputs = []
  206. for output_tensor in self.output_tensors:
  207. output = output_tensor.copy_to_cpu()
  208. outputs.append(output)
  209. preds = outputs[0]
  210. rec_result = self.postprocess_op(preds)
  211. for rno in range(len(rec_result)):
  212. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  213. elapse += time.time() - starttime
  214. return rec_res, elapse
  215. def main(args):
  216. image_file_list = get_image_file_list(args.image_dir)
  217. text_recognizer = TextRecognizer(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. rec_res, predict_time = text_recognizer(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. rec_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())