predict_rec_pytorch.py 18 KB

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