predict_det.py 15 KB

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