predict_rec.py 17 KB

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