predict_rec.py 17 KB

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