predict_det_pytorch.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../../../")
  20. import requests
  21. from format_convert import _global
  22. from format_convert.utils import judge_error_code, log, namespace_to_dict, get_platform, file_lock, \
  23. get_gpu_memory_usage, get_current_process_gpu_id
  24. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  25. import cv2
  26. import numpy as np
  27. import time
  28. import sys
  29. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  30. import ocr.tools.infer.utility as utility
  31. from ocr.ppocr.utils.logging import get_logger
  32. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  33. from ocr.ppocr.data import create_operators, transform
  34. from ocr.ppocr.postprocess import build_post_process
  35. from config.max_compute_config import MAX_COMPUTE
  36. import torch
  37. from torch import nn
  38. from ocr.tools.infer.torch_det_model import DB_ResNet_18
  39. import gc
  40. logger = get_logger()
  41. class TextDetector(object):
  42. shrink_memory_count = 0
  43. def __init__(self, args):
  44. self.args = args
  45. self.det_algorithm = args.det_algorithm
  46. pre_process_list = [{
  47. 'DetResizeForTest': None
  48. }, {
  49. 'NormalizeImage': {
  50. 'std': [0.229, 0.224, 0.225],
  51. 'mean': [0.485, 0.456, 0.406],
  52. 'scale': '1./255.',
  53. 'order': 'hwc'
  54. }
  55. }, {
  56. 'ToCHWImage': None
  57. }, {
  58. 'KeepKeys': {
  59. 'keep_keys': ['image', 'shape']
  60. }
  61. }]
  62. postprocess_params = {}
  63. if self.det_algorithm == "DB":
  64. postprocess_params['name'] = 'DBPostProcess'
  65. postprocess_params["thresh"] = args.det_db_thresh
  66. postprocess_params["box_thresh"] = args.det_db_box_thresh
  67. postprocess_params["max_candidates"] = 1000
  68. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  69. postprocess_params["use_dilation"] = args.use_dilation
  70. elif self.det_algorithm == "EAST":
  71. postprocess_params['name'] = 'EASTPostProcess'
  72. postprocess_params["score_thresh"] = args.det_east_score_thresh
  73. postprocess_params["cover_thresh"] = args.det_east_cover_thresh
  74. postprocess_params["nms_thresh"] = args.det_east_nms_thresh
  75. elif self.det_algorithm == "SAST":
  76. pre_process_list[0] = {
  77. 'DetResizeForTest': {
  78. 'resize_long': args.det_limit_side_len
  79. }
  80. }
  81. postprocess_params['name'] = 'SASTPostProcess'
  82. postprocess_params["score_thresh"] = args.det_sast_score_thresh
  83. postprocess_params["nms_thresh"] = args.det_sast_nms_thresh
  84. self.det_sast_polygon = args.det_sast_polygon
  85. if self.det_sast_polygon:
  86. postprocess_params["sample_pts_num"] = 6
  87. postprocess_params["expand_scale"] = 1.2
  88. postprocess_params["shrink_ratio_of_width"] = 0.2
  89. else:
  90. postprocess_params["sample_pts_num"] = 2
  91. postprocess_params["expand_scale"] = 1.0
  92. postprocess_params["shrink_ratio_of_width"] = 0.3
  93. else:
  94. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  95. sys.exit(0)
  96. self.preprocess_op = create_operators(pre_process_list)
  97. self.postprocess_op = build_post_process(postprocess_params)
  98. det_model_path = args.det_model_dir
  99. self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  100. model = DB_ResNet_18()
  101. mode_state_dict = torch.load(det_model_path, self.device)['state_dict']
  102. if str(self.device) == 'cpu': # cpu处理时精度调整,加速推理
  103. for name, value in mode_state_dict.items():
  104. if get_platform() != "Windows":
  105. value = value.double()
  106. value = torch.where((value < 1.0e-23) & (value > 0.0), 1.0e-23, value)
  107. value = torch.where((value > -1.0e-23) & (value < 0.0), -1.0e-23, value)
  108. mode_state_dict[name] = value
  109. model.load_state_dict(mode_state_dict)
  110. self.predictor = model
  111. self.predictor.to(self.device)
  112. self.predictor.eval()
  113. if str(self.device) != 'cpu':
  114. self.gpu_id = get_current_process_gpu_id()
  115. else:
  116. self.gpu_id = None
  117. # self.predictor, self.input_tensor, self.output_tensors = utility.create_predictor(
  118. # args, 'det', logger) # paddle.jit.load(args.det_model_dir)
  119. # self.predictor.eval()
  120. def order_points_clockwise(self, pts):
  121. """
  122. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  123. # sort the points based on their x-coordinates
  124. """
  125. xSorted = pts[np.argsort(pts[:, 0]), :]
  126. # grab the left-most and right-most points from the sorted
  127. # x-roodinate points
  128. leftMost = xSorted[:2, :]
  129. rightMost = xSorted[2:, :]
  130. # now, sort the left-most coordinates according to their
  131. # y-coordinates so we can grab the top-left and bottom-left
  132. # points, respectively
  133. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  134. (tl, bl) = leftMost
  135. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  136. (tr, br) = rightMost
  137. rect = np.array([tl, tr, br, bl], dtype="float32")
  138. return rect
  139. def clip_det_res(self, points, img_height, img_width):
  140. for pno in range(points.shape[0]):
  141. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  142. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  143. return points
  144. def filter_tag_det_res(self, dt_boxes, image_shape):
  145. img_height, img_width = image_shape[0:2]
  146. dt_boxes_new = []
  147. for box in dt_boxes:
  148. box = self.order_points_clockwise(box)
  149. box = self.clip_det_res(box, img_height, img_width)
  150. rect_width = int(np.linalg.norm(box[0] - box[1]))
  151. rect_height = int(np.linalg.norm(box[0] - box[3]))
  152. if rect_width <= 3 or rect_height <= 3:
  153. continue
  154. dt_boxes_new.append(box)
  155. dt_boxes = np.array(dt_boxes_new)
  156. return dt_boxes
  157. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  158. img_height, img_width = image_shape[0:2]
  159. dt_boxes_new = []
  160. for box in dt_boxes:
  161. box = self.clip_det_res(box, img_height, img_width)
  162. dt_boxes_new.append(box)
  163. dt_boxes = np.array(dt_boxes_new)
  164. return dt_boxes
  165. def __call__(self, img):
  166. # cv2.imwrite("/data2/znj/format_conversion_maxcompute/ocr/temp_image/temp.jpg",img)
  167. ori_im = img.copy()
  168. data = {'image': img}
  169. data = transform(data, self.preprocess_op)
  170. img, shape_list = data
  171. if img is None:
  172. return None, 0
  173. img = np.expand_dims(img, axis=0)
  174. shape_list = np.expand_dims(shape_list, axis=0)
  175. img = img.copy()
  176. starttime = time.time()
  177. tensor = torch.from_numpy(img).float()
  178. # self.input_tensor.copy_from_cpu(img)
  179. # if ori_im.shape[0] > 1024 and ori_im.shape[1] > 1024 and get_platform() != "Windows" and not MAX_COMPUTE:
  180. if get_platform() != "Windows" and not MAX_COMPUTE and self.gpu_id is not None:
  181. # 加锁,防止太多大图片同时预测,爆显存
  182. time2 = time.time()
  183. lock_file_sub = f'ocr_{self.gpu_id}'
  184. lock_file = os.path.abspath(os.path.dirname(__file__)) + "/" + lock_file_sub + ".lock"
  185. f = file_lock(lock_file)
  186. log("det get file_lock " + lock_file + " time " + str(time.time()-time2))
  187. try:
  188. time2 = time.time()
  189. if str(self.device) != 'cpu':
  190. torch.cuda.empty_cache()
  191. tensor = tensor.to(self.device)
  192. with torch.no_grad():
  193. out = self.predictor(tensor)
  194. log("get file_lock run det" + " time " + str(time.time()-time2))
  195. except RuntimeError:
  196. log("ocr/tools/infer/predict_det.py predict.run error! maybe no gpu memory!")
  197. log("det predictor shrink memory! ori_im.shape " + str(ori_im.shape))
  198. get_gpu_memory_usage()
  199. raise RuntimeError
  200. finally:
  201. f.close()
  202. if str(self.device) != 'cpu':
  203. torch.cuda.empty_cache()
  204. # gc.collect()
  205. else:
  206. tensor = tensor.to(self.device)
  207. with torch.no_grad():
  208. out = self.predictor(tensor)
  209. out = out.cpu().numpy()
  210. preds = {}
  211. preds['maps'] = out
  212. post_result = self.postprocess_op(preds, shape_list)
  213. dt_boxes = post_result[0]['points']
  214. if self.det_algorithm == "SAST" and self.det_sast_polygon:
  215. dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape)
  216. else:
  217. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  218. elapse = time.time() - starttime
  219. return dt_boxes, elapse
  220. class TextDetector2(object):
  221. shrink_memory_count = 0
  222. def __init__(self, args):
  223. self.args = args
  224. self.det_algorithm = args.det_algorithm
  225. pre_process_list = [{
  226. 'DetResizeForTest': None
  227. }, {
  228. 'NormalizeImage': {
  229. 'std': [0.229, 0.224, 0.225],
  230. 'mean': [0.485, 0.456, 0.406],
  231. 'scale': '1./255.',
  232. 'order': 'hwc'
  233. }
  234. }, {
  235. 'ToCHWImage': None
  236. }, {
  237. 'KeepKeys': {
  238. 'keep_keys': ['image', 'shape']
  239. }
  240. }]
  241. postprocess_params = {}
  242. if self.det_algorithm == "DB":
  243. postprocess_params['name'] = 'DBPostProcess'
  244. postprocess_params["thresh"] = args.det_db_thresh
  245. postprocess_params["box_thresh"] = args.det_db_box_thresh
  246. postprocess_params["max_candidates"] = 1000
  247. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  248. postprocess_params["use_dilation"] = args.use_dilation
  249. else:
  250. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  251. sys.exit(0)
  252. self.preprocess_op = create_operators(pre_process_list)
  253. self.postprocess_op = build_post_process(postprocess_params)
  254. def order_points_clockwise(self, pts):
  255. """
  256. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  257. # sort the points based on their x-coordinates
  258. """
  259. xSorted = pts[np.argsort(pts[:, 0]), :]
  260. # grab the left-most and right-most points from the sorted
  261. # x-roodinate points
  262. leftMost = xSorted[:2, :]
  263. rightMost = xSorted[2:, :]
  264. # now, sort the left-most coordinates according to their
  265. # y-coordinates so we can grab the top-left and bottom-left
  266. # points, respectively
  267. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  268. (tl, bl) = leftMost
  269. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  270. (tr, br) = rightMost
  271. rect = np.array([tl, tr, br, bl], dtype="float32")
  272. return rect
  273. def clip_det_res(self, points, img_height, img_width):
  274. for pno in range(points.shape[0]):
  275. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  276. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  277. return points
  278. def filter_tag_det_res(self, dt_boxes, image_shape):
  279. img_height, img_width = image_shape[0:2]
  280. dt_boxes_new = []
  281. for box in dt_boxes:
  282. box = self.order_points_clockwise(box)
  283. box = self.clip_det_res(box, img_height, img_width)
  284. rect_width = int(np.linalg.norm(box[0] - box[1]))
  285. rect_height = int(np.linalg.norm(box[0] - box[3]))
  286. if rect_width <= 3 or rect_height <= 3:
  287. continue
  288. dt_boxes_new.append(box)
  289. dt_boxes = np.array(dt_boxes_new)
  290. return dt_boxes
  291. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  292. img_height, img_width = image_shape[0:2]
  293. dt_boxes_new = []
  294. for box in dt_boxes:
  295. box = self.clip_det_res(box, img_height, img_width)
  296. dt_boxes_new.append(box)
  297. dt_boxes = np.array(dt_boxes_new)
  298. return dt_boxes
  299. def __call__(self, img):
  300. from format_convert.convert_need_interface import from_gpu_interface_redis
  301. # 预处理
  302. ori_im = img.copy()
  303. data = {'image': img}
  304. data = transform(data, self.preprocess_op)
  305. img, shape_list = data
  306. if img is None:
  307. return None, 0
  308. img = np.expand_dims(img, axis=0)
  309. shape_list = np.expand_dims(shape_list, axis=0)
  310. img = img.copy()
  311. starttime = time.time()
  312. # # 压缩numpy
  313. # compressed_array = io.BytesIO()
  314. # np.savez_compressed(compressed_array, img)
  315. # compressed_array.seek(0)
  316. # img = compressed_array.read()
  317. # 调用GPU接口
  318. _dict = {"inputs": img, "args": str(namespace_to_dict(self.args)), "md5": _global.get("md5")}
  319. result = from_gpu_interface_redis(_dict, model_type="ocr", predictor_type="det")
  320. if judge_error_code(result):
  321. logging.error("from_gpu_interface failed! " + str(result))
  322. raise requests.exceptions.RequestException
  323. _preds = result.get("preds")
  324. gpu_time = result.get("gpu_time")
  325. # # 解压numpy
  326. # decompressed_array = io.BytesIO()
  327. # decompressed_array.write(_preds)
  328. # decompressed_array.seek(0)
  329. # _preds = np.load(decompressed_array, allow_pickle=True)['arr_0']
  330. # log("inputs.shape" + str(_preds.shape))
  331. # 后处理
  332. preds = {}
  333. if self.det_algorithm == 'DB':
  334. preds['maps'] = _preds
  335. else:
  336. raise NotImplementedError
  337. post_result = self.postprocess_op(preds, shape_list)
  338. dt_boxes = post_result[0]['points']
  339. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  340. elapse = time.time() - starttime
  341. log("ocr model predict time - det - time " + str(gpu_time))
  342. return dt_boxes, elapse
  343. if __name__ == "__main__":
  344. args = utility.parse_args()
  345. image_file_list = get_image_file_list(args.image_dir)
  346. text_detector = TextDetector(args)
  347. count = 0
  348. total_time = 0
  349. draw_img_save = "./inference_results"
  350. if not os.path.exists(draw_img_save):
  351. os.makedirs(draw_img_save)
  352. for image_file in image_file_list:
  353. img, flag = check_and_read_gif(image_file)
  354. if not flag:
  355. img = cv2.imread(image_file)
  356. if img is None:
  357. logger.info("error in loading image:{}".format(image_file))
  358. continue
  359. dt_boxes, elapse = text_detector(img)
  360. if count > 0:
  361. total_time += elapse
  362. count += 1
  363. logger.info("Predict time of {}: {}".format(image_file, elapse))
  364. src_im = utility.draw_text_det_res(dt_boxes, image_file)
  365. img_name_pure = os.path.split(image_file)[-1]
  366. img_path = os.path.join(draw_img_save,
  367. "det_res_{}".format(img_name_pure))
  368. cv2.imwrite(img_path, src_im)
  369. logger.info("The visualized image saved in {}".format(img_path))
  370. if count > 1:
  371. logger.info("Avg Time: {}".format(total_time / (count - 1)))