predict_det.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. __dir__ = os.path.dirname(os.path.abspath(__file__))
  17. sys.path.append(__dir__)
  18. sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))
  19. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  20. import cv2
  21. import numpy as np
  22. import time
  23. import sys
  24. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  25. import ocr.tools.infer.utility as utility
  26. from ocr.ppocr.utils.logging import get_logger
  27. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  28. from ocr.ppocr.data import create_operators, transform
  29. from ocr.ppocr.postprocess import build_post_process
  30. logger = get_logger()
  31. class TextDetector(object):
  32. shrink_memory_count = 0
  33. def __init__(self, args):
  34. self.args = args
  35. self.det_algorithm = args.det_algorithm
  36. pre_process_list = [{
  37. 'DetResizeForTest': None
  38. }, {
  39. 'NormalizeImage': {
  40. 'std': [0.229, 0.224, 0.225],
  41. 'mean': [0.485, 0.456, 0.406],
  42. 'scale': '1./255.',
  43. 'order': 'hwc'
  44. }
  45. }, {
  46. 'ToCHWImage': None
  47. }, {
  48. 'KeepKeys': {
  49. 'keep_keys': ['image', 'shape']
  50. }
  51. }]
  52. postprocess_params = {}
  53. if self.det_algorithm == "DB":
  54. postprocess_params['name'] = 'DBPostProcess'
  55. postprocess_params["thresh"] = args.det_db_thresh
  56. postprocess_params["box_thresh"] = args.det_db_box_thresh
  57. postprocess_params["max_candidates"] = 1000
  58. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  59. postprocess_params["use_dilation"] = args.use_dilation
  60. elif self.det_algorithm == "EAST":
  61. postprocess_params['name'] = 'EASTPostProcess'
  62. postprocess_params["score_thresh"] = args.det_east_score_thresh
  63. postprocess_params["cover_thresh"] = args.det_east_cover_thresh
  64. postprocess_params["nms_thresh"] = args.det_east_nms_thresh
  65. elif self.det_algorithm == "SAST":
  66. pre_process_list[0] = {
  67. 'DetResizeForTest': {
  68. 'resize_long': args.det_limit_side_len
  69. }
  70. }
  71. postprocess_params['name'] = 'SASTPostProcess'
  72. postprocess_params["score_thresh"] = args.det_sast_score_thresh
  73. postprocess_params["nms_thresh"] = args.det_sast_nms_thresh
  74. self.det_sast_polygon = args.det_sast_polygon
  75. if self.det_sast_polygon:
  76. postprocess_params["sample_pts_num"] = 6
  77. postprocess_params["expand_scale"] = 1.2
  78. postprocess_params["shrink_ratio_of_width"] = 0.2
  79. else:
  80. postprocess_params["sample_pts_num"] = 2
  81. postprocess_params["expand_scale"] = 1.0
  82. postprocess_params["shrink_ratio_of_width"] = 0.3
  83. else:
  84. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  85. sys.exit(0)
  86. self.preprocess_op = create_operators(pre_process_list)
  87. self.postprocess_op = build_post_process(postprocess_params)
  88. self.predictor, self.input_tensor, self.output_tensors = utility.create_predictor(
  89. args, 'det', logger) # paddle.jit.load(args.det_model_dir)
  90. # self.predictor.eval()
  91. def order_points_clockwise(self, pts):
  92. """
  93. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  94. # sort the points based on their x-coordinates
  95. """
  96. xSorted = pts[np.argsort(pts[:, 0]), :]
  97. # grab the left-most and right-most points from the sorted
  98. # x-roodinate points
  99. leftMost = xSorted[:2, :]
  100. rightMost = xSorted[2:, :]
  101. # now, sort the left-most coordinates according to their
  102. # y-coordinates so we can grab the top-left and bottom-left
  103. # points, respectively
  104. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  105. (tl, bl) = leftMost
  106. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  107. (tr, br) = rightMost
  108. rect = np.array([tl, tr, br, bl], dtype="float32")
  109. return rect
  110. def clip_det_res(self, points, img_height, img_width):
  111. for pno in range(points.shape[0]):
  112. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  113. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  114. return points
  115. def filter_tag_det_res(self, dt_boxes, image_shape):
  116. img_height, img_width = image_shape[0:2]
  117. dt_boxes_new = []
  118. for box in dt_boxes:
  119. box = self.order_points_clockwise(box)
  120. box = self.clip_det_res(box, img_height, img_width)
  121. rect_width = int(np.linalg.norm(box[0] - box[1]))
  122. rect_height = int(np.linalg.norm(box[0] - box[3]))
  123. if rect_width <= 3 or rect_height <= 3:
  124. continue
  125. dt_boxes_new.append(box)
  126. dt_boxes = np.array(dt_boxes_new)
  127. return dt_boxes
  128. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  129. img_height, img_width = image_shape[0:2]
  130. dt_boxes_new = []
  131. for box in dt_boxes:
  132. box = self.clip_det_res(box, img_height, img_width)
  133. dt_boxes_new.append(box)
  134. dt_boxes = np.array(dt_boxes_new)
  135. return dt_boxes
  136. def __call__(self, img):
  137. ori_im = img.copy()
  138. data = {'image': img}
  139. data = transform(data, self.preprocess_op)
  140. img, shape_list = data
  141. if img is None:
  142. return None, 0
  143. img = np.expand_dims(img, axis=0)
  144. shape_list = np.expand_dims(shape_list, axis=0)
  145. img = img.copy()
  146. starttime = time.time()
  147. self.input_tensor.copy_from_cpu(img)
  148. self.predictor.run()
  149. outputs = []
  150. for output_tensor in self.output_tensors:
  151. output = output_tensor.copy_to_cpu()
  152. outputs.append(output)
  153. preds = {}
  154. if self.det_algorithm == "EAST":
  155. preds['f_geo'] = outputs[0]
  156. preds['f_score'] = outputs[1]
  157. elif self.det_algorithm == 'SAST':
  158. preds['f_border'] = outputs[0]
  159. preds['f_score'] = outputs[1]
  160. preds['f_tco'] = outputs[2]
  161. preds['f_tvo'] = outputs[3]
  162. elif self.det_algorithm == 'DB':
  163. preds['maps'] = outputs[0]
  164. else:
  165. raise NotImplementedError
  166. post_result = self.postprocess_op(preds, shape_list)
  167. dt_boxes = post_result[0]['points']
  168. if self.det_algorithm == "SAST" and self.det_sast_polygon:
  169. dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape)
  170. else:
  171. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  172. elapse = time.time() - starttime
  173. # 释放内存
  174. # print("TextDetector", self.predictor)
  175. # if TextDetector.shrink_memory_count % 100 == 0:
  176. # print("TextDetector shrink memory")
  177. self.predictor.clear_intermediate_tensor()
  178. self.predictor.try_shrink_memory()
  179. # TextDetector.shrink_memory_count += 1
  180. return dt_boxes, elapse
  181. if __name__ == "__main__":
  182. args = utility.parse_args()
  183. image_file_list = get_image_file_list(args.image_dir)
  184. text_detector = TextDetector(args)
  185. count = 0
  186. total_time = 0
  187. draw_img_save = "./inference_results"
  188. if not os.path.exists(draw_img_save):
  189. os.makedirs(draw_img_save)
  190. for image_file in image_file_list:
  191. img, flag = check_and_read_gif(image_file)
  192. if not flag:
  193. img = cv2.imread(image_file)
  194. if img is None:
  195. logger.info("error in loading image:{}".format(image_file))
  196. continue
  197. dt_boxes, elapse = text_detector(img)
  198. if count > 0:
  199. total_time += elapse
  200. count += 1
  201. logger.info("Predict time of {}: {}".format(image_file, elapse))
  202. src_im = utility.draw_text_det_res(dt_boxes, image_file)
  203. img_name_pure = os.path.split(image_file)[-1]
  204. img_path = os.path.join(draw_img_save,
  205. "det_res_{}".format(img_name_pure))
  206. cv2.imwrite(img_path, src_im)
  207. logger.info("The visualized image saved in {}".format(img_path))
  208. if count > 1:
  209. logger.info("Avg Time: {}".format(total_time / (count - 1)))