predict_rec.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. import requests
  22. # sys.path.append(__dir__)
  23. # sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))
  24. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../../")
  25. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  26. import cv2
  27. import numpy as np
  28. import math
  29. import time
  30. import traceback
  31. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  32. import paddle
  33. import ocr.tools.infer.utility as utility
  34. from ocr.ppocr.postprocess import build_post_process
  35. from ocr.ppocr.utils.logging import get_logger
  36. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  37. from format_convert.utils import judge_error_code, log, namespace_to_dict
  38. from format_convert import _global
  39. logger = get_logger()
  40. class TextRecognizer(object):
  41. shrink_memory_count = 0
  42. def __init__(self, args):
  43. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  44. self.character_type = args.rec_char_type
  45. self.rec_batch_num = args.rec_batch_num
  46. self.rec_algorithm = args.rec_algorithm
  47. postprocess_params = {
  48. 'name': 'CTCLabelDecode',
  49. "character_type": args.rec_char_type,
  50. "character_dict_path": args.rec_char_dict_path,
  51. "use_space_char": args.use_space_char
  52. }
  53. if self.rec_algorithm == "SRN":
  54. postprocess_params = {
  55. 'name': 'SRNLabelDecode',
  56. "character_type": args.rec_char_type,
  57. "character_dict_path": args.rec_char_dict_path,
  58. "use_space_char": args.use_space_char
  59. }
  60. elif self.rec_algorithm == "RARE":
  61. postprocess_params = {
  62. 'name': 'AttnLabelDecode',
  63. "character_type": args.rec_char_type,
  64. "character_dict_path": args.rec_char_dict_path,
  65. "use_space_char": args.use_space_char
  66. }
  67. self.postprocess_op = build_post_process(postprocess_params)
  68. self.predictor, self.input_tensor, self.output_tensors = \
  69. utility.create_predictor(args, 'rec', logger)
  70. def resize_norm_img(self, img, max_wh_ratio):
  71. imgC, imgH, imgW = self.rec_image_shape
  72. assert imgC == img.shape[2]
  73. if self.character_type == "ch":
  74. imgW = int((32 * max_wh_ratio))
  75. h, w = img.shape[:2]
  76. ratio = w / float(h)
  77. if math.ceil(imgH * ratio) > imgW:
  78. resized_w = imgW
  79. else:
  80. resized_w = int(math.ceil(imgH * ratio))
  81. # print("predict_rec.py resize_norm_img resize shape", (resized_w, imgH))
  82. resized_image = cv2.resize(img, (resized_w, imgH))
  83. resized_image = resized_image.astype('float32')
  84. resized_image = resized_image.transpose((2, 0, 1)) / 255
  85. resized_image -= 0.5
  86. resized_image /= 0.5
  87. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  88. padding_im[:, :, 0:resized_w] = resized_image
  89. return padding_im
  90. def resize_norm_img_srn(self, img, image_shape):
  91. imgC, imgH, imgW = image_shape
  92. img_black = np.zeros((imgH, imgW))
  93. im_hei = img.shape[0]
  94. im_wid = img.shape[1]
  95. if im_wid <= im_hei * 1:
  96. img_new = cv2.resize(img, (imgH * 1, imgH))
  97. elif im_wid <= im_hei * 2:
  98. img_new = cv2.resize(img, (imgH * 2, imgH))
  99. elif im_wid <= im_hei * 3:
  100. img_new = cv2.resize(img, (imgH * 3, imgH))
  101. else:
  102. img_new = cv2.resize(img, (imgW, imgH))
  103. img_np = np.asarray(img_new)
  104. img_np = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
  105. img_black[:, 0:img_np.shape[1]] = img_np
  106. img_black = img_black[:, :, np.newaxis]
  107. row, col, c = img_black.shape
  108. c = 1
  109. return np.reshape(img_black, (c, row, col)).astype(np.float32)
  110. def srn_other_inputs(self, image_shape, num_heads, max_text_length):
  111. imgC, imgH, imgW = image_shape
  112. feature_dim = int((imgH / 8) * (imgW / 8))
  113. encoder_word_pos = np.array(range(0, feature_dim)).reshape(
  114. (feature_dim, 1)).astype('int64')
  115. gsrm_word_pos = np.array(range(0, max_text_length)).reshape(
  116. (max_text_length, 1)).astype('int64')
  117. gsrm_attn_bias_data = np.ones((1, max_text_length, max_text_length))
  118. gsrm_slf_attn_bias1 = np.triu(gsrm_attn_bias_data, 1).reshape(
  119. [-1, 1, max_text_length, max_text_length])
  120. gsrm_slf_attn_bias1 = np.tile(
  121. gsrm_slf_attn_bias1,
  122. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  123. gsrm_slf_attn_bias2 = np.tril(gsrm_attn_bias_data, -1).reshape(
  124. [-1, 1, max_text_length, max_text_length])
  125. gsrm_slf_attn_bias2 = np.tile(
  126. gsrm_slf_attn_bias2,
  127. [1, num_heads, 1, 1]).astype('float32') * [-1e9]
  128. encoder_word_pos = encoder_word_pos[np.newaxis, :]
  129. gsrm_word_pos = gsrm_word_pos[np.newaxis, :]
  130. return [
  131. encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  132. gsrm_slf_attn_bias2
  133. ]
  134. def process_image_srn(self, img, image_shape, num_heads, max_text_length):
  135. norm_img = self.resize_norm_img_srn(img, image_shape)
  136. norm_img = norm_img[np.newaxis, :]
  137. [encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2] = \
  138. self.srn_other_inputs(image_shape, num_heads, max_text_length)
  139. gsrm_slf_attn_bias1 = gsrm_slf_attn_bias1.astype(np.float32)
  140. gsrm_slf_attn_bias2 = gsrm_slf_attn_bias2.astype(np.float32)
  141. encoder_word_pos = encoder_word_pos.astype(np.int64)
  142. gsrm_word_pos = gsrm_word_pos.astype(np.int64)
  143. return (norm_img, encoder_word_pos, gsrm_word_pos, gsrm_slf_attn_bias1,
  144. gsrm_slf_attn_bias2)
  145. def __call__(self, img_list):
  146. img_num = len(img_list)
  147. # Calculate the aspect ratio of all text bars
  148. width_list = []
  149. for img in img_list:
  150. width_list.append(img.shape[1] / float(img.shape[0]))
  151. # Sorting can speed up the recognition process
  152. indices = np.argsort(np.array(width_list))
  153. # rec_res = []
  154. rec_res = [['', 0.0]] * img_num
  155. batch_num = self.rec_batch_num
  156. elapse = 0
  157. for beg_img_no in range(0, img_num, batch_num):
  158. end_img_no = min(img_num, beg_img_no + batch_num)
  159. norm_img_batch = []
  160. max_wh_ratio = 0
  161. for ino in range(beg_img_no, end_img_no):
  162. # h, w = img_list[ino].shape[0:2]
  163. h, w = img_list[indices[ino]].shape[0:2]
  164. wh_ratio = w * 1.0 / h
  165. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  166. for ino in range(beg_img_no, end_img_no):
  167. if self.rec_algorithm != "SRN":
  168. norm_img = self.resize_norm_img(img_list[indices[ino]],
  169. max_wh_ratio)
  170. norm_img = norm_img[np.newaxis, :]
  171. norm_img_batch.append(norm_img)
  172. else:
  173. norm_img = self.process_image_srn(
  174. img_list[indices[ino]], self.rec_image_shape, 8, 25)
  175. encoder_word_pos_list = []
  176. gsrm_word_pos_list = []
  177. gsrm_slf_attn_bias1_list = []
  178. gsrm_slf_attn_bias2_list = []
  179. encoder_word_pos_list.append(norm_img[1])
  180. gsrm_word_pos_list.append(norm_img[2])
  181. gsrm_slf_attn_bias1_list.append(norm_img[3])
  182. gsrm_slf_attn_bias2_list.append(norm_img[4])
  183. norm_img_batch.append(norm_img[0])
  184. norm_img_batch = np.concatenate(norm_img_batch)
  185. norm_img_batch = norm_img_batch.copy()
  186. if self.rec_algorithm == "SRN":
  187. starttime = time.time()
  188. encoder_word_pos_list = np.concatenate(encoder_word_pos_list)
  189. gsrm_word_pos_list = np.concatenate(gsrm_word_pos_list)
  190. gsrm_slf_attn_bias1_list = np.concatenate(
  191. gsrm_slf_attn_bias1_list)
  192. gsrm_slf_attn_bias2_list = np.concatenate(
  193. gsrm_slf_attn_bias2_list)
  194. inputs = [
  195. norm_img_batch,
  196. encoder_word_pos_list,
  197. gsrm_word_pos_list,
  198. gsrm_slf_attn_bias1_list,
  199. gsrm_slf_attn_bias2_list,
  200. ]
  201. input_names = self.predictor.get_input_names()
  202. for i in range(len(input_names)):
  203. input_tensor = self.predictor.get_input_handle(input_names[
  204. i])
  205. input_tensor.copy_from_cpu(inputs[i])
  206. self.predictor.run()
  207. outputs = []
  208. for output_tensor in self.output_tensors:
  209. output = output_tensor.copy_to_cpu()
  210. outputs.append(output)
  211. preds = {"predict": outputs[2]}
  212. else:
  213. starttime = time.time()
  214. self.input_tensor.copy_from_cpu(norm_img_batch)
  215. start_time = time.time()
  216. self.predictor.run()
  217. logging.info("ocr model predict time - rec" + str(time.time()-start_time))
  218. outputs = []
  219. for output_tensor in self.output_tensors:
  220. output = output_tensor.copy_to_cpu()
  221. outputs.append(output)
  222. preds = outputs[0]
  223. # print("tools/infer/predict_rec preds", preds)
  224. rec_result = self.postprocess_op(preds)
  225. for rno in range(len(rec_result)):
  226. # print("predict_rec", img_num, batch_num, beg_img_no,
  227. # indices[beg_img_no + rno], len(rec_res))
  228. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  229. elapse += time.time() - starttime
  230. # 释放内存
  231. self.predictor.clear_intermediate_tensor()
  232. self.predictor.try_shrink_memory()
  233. return rec_res, elapse
  234. class TextRecognizer2(object):
  235. shrink_memory_count = 0
  236. def __init__(self, args):
  237. self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")]
  238. self.character_type = args.rec_char_type
  239. self.rec_batch_num = args.rec_batch_num
  240. self.rec_algorithm = args.rec_algorithm
  241. postprocess_params = {
  242. 'name': 'CTCLabelDecode',
  243. "character_type": args.rec_char_type,
  244. "character_dict_path": args.rec_char_dict_path,
  245. "use_space_char": args.use_space_char
  246. }
  247. self.postprocess_op = build_post_process(postprocess_params)
  248. self.args = args
  249. # self.predictor, self.input_tensor, self.output_tensors = \
  250. # utility.create_predictor(args, 'rec', logger)
  251. def resize_norm_img(self, img, max_wh_ratio):
  252. imgC, imgH, imgW = self.rec_image_shape
  253. assert imgC == img.shape[2]
  254. if self.character_type == "ch":
  255. imgW = int((32 * max_wh_ratio))
  256. h, w = img.shape[:2]
  257. ratio = w / float(h)
  258. if math.ceil(imgH * ratio) > imgW:
  259. resized_w = imgW
  260. else:
  261. resized_w = int(math.ceil(imgH * ratio))
  262. # print("predict_rec.py resize_norm_img resize shape", (resized_w, imgH))
  263. resized_image = cv2.resize(img, (resized_w, imgH))
  264. resized_image = resized_image.astype('float32')
  265. resized_image = resized_image.transpose((2, 0, 1)) / 255
  266. resized_image -= 0.5
  267. resized_image /= 0.5
  268. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  269. padding_im[:, :, 0:resized_w] = resized_image
  270. return padding_im
  271. def __call__(self, img_list):
  272. from format_convert.convert_need_interface import from_gpu_interface_redis
  273. img_num = len(img_list)
  274. # Calculate the aspect ratio of all text bars
  275. width_list = []
  276. for img in img_list:
  277. width_list.append(img.shape[1] / float(img.shape[0]))
  278. # Sorting can speed up the recognition process
  279. indices = np.argsort(np.array(width_list))
  280. rec_res = [['', 0.0]] * img_num
  281. batch_num = self.rec_batch_num
  282. elapse = 0
  283. all_gpu_time = 0
  284. for beg_img_no in range(0, img_num, batch_num):
  285. # 预处理
  286. end_img_no = min(img_num, beg_img_no + batch_num)
  287. norm_img_batch = []
  288. max_wh_ratio = 0
  289. for ino in range(beg_img_no, end_img_no):
  290. h, w = img_list[indices[ino]].shape[0:2]
  291. wh_ratio = w * 1.0 / h
  292. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  293. for ino in range(beg_img_no, end_img_no):
  294. norm_img = self.resize_norm_img(img_list[indices[ino]],
  295. max_wh_ratio)
  296. norm_img = norm_img[np.newaxis, :]
  297. norm_img_batch.append(norm_img)
  298. norm_img_batch = np.concatenate(norm_img_batch)
  299. norm_img_batch = norm_img_batch.copy()
  300. starttime = time.time()
  301. # # 压缩numpy
  302. # compressed_array = io.BytesIO()
  303. # np.savez_compressed(compressed_array, norm_img_batch)
  304. # compressed_array.seek(0)
  305. # norm_img_batch = compressed_array.read()
  306. # 调用GPU接口
  307. _dict = {"inputs": norm_img_batch, "args": str(namespace_to_dict(self.args)), "md5": _global.get("md5")}
  308. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="rec")
  309. if judge_error_code(result):
  310. logging.error("from_gpu_interface failed! " + str(result))
  311. raise requests.exceptions.RequestException
  312. preds = result.get("preds")
  313. gpu_time = result.get("gpu_time")
  314. all_gpu_time += round(gpu_time, 2)
  315. # # 解压numpy
  316. # decompressed_array = io.BytesIO()
  317. # decompressed_array.write(preds)
  318. # decompressed_array.seek(0)
  319. # preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  320. # log("inputs.shape" + str(preds.shape))
  321. # 后处理
  322. rec_result = self.postprocess_op(preds)
  323. for rno in range(len(rec_result)):
  324. rec_res[indices[beg_img_no + rno]] = rec_result[rno]
  325. elapse += time.time() - starttime
  326. log("ocr model predict time - rec - time " + str(all_gpu_time) + " - num " + str(img_num))
  327. return rec_res, elapse
  328. def main(args):
  329. image_file_list = get_image_file_list(args.image_dir)
  330. text_recognizer = TextRecognizer(args)
  331. valid_image_file_list = []
  332. img_list = []
  333. for image_file in image_file_list:
  334. img, flag = check_and_read_gif(image_file)
  335. if not flag:
  336. img = cv2.imread(image_file)
  337. if img is None:
  338. logger.info("error in loading image:{}".format(image_file))
  339. continue
  340. valid_image_file_list.append(image_file)
  341. img_list.append(img)
  342. try:
  343. rec_res, predict_time = text_recognizer(img_list)
  344. except:
  345. logger.info(traceback.format_exc())
  346. logger.info(
  347. "ERROR!!!! \n"
  348. "Please read the FAQ:https://github.com/PaddlePaddle/PaddleOCR#faq \n"
  349. "If your model has tps module: "
  350. "TPS does not support variable shape.\n"
  351. "Please set --rec_image_shape='3,32,100' and --rec_char_type='en' ")
  352. exit()
  353. for ino in range(len(img_list)):
  354. logger.info("Predicts of {}:{}".format(valid_image_file_list[ino],
  355. rec_res[ino]))
  356. logger.info("Total predict time for {} images, cost: {:.3f}".format(
  357. len(img_list), predict_time))
  358. if __name__ == "__main__":
  359. main(utility.parse_args())