predict_det.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. import tools.infer.utility as utility
  25. from ppocr.utils.logging import get_logger
  26. from ppocr.utils.utility import get_image_file_list, check_and_read_gif
  27. from ppocr.data import create_operators, transform
  28. from ppocr.postprocess import build_post_process
  29. logger = get_logger()
  30. class TextDetector(object):
  31. def __init__(self, args):
  32. self.args = args
  33. self.det_algorithm = args.det_algorithm
  34. pre_process_list = [{
  35. 'DetResizeForTest': None
  36. }, {
  37. 'NormalizeImage': {
  38. 'std': [0.229, 0.224, 0.225],
  39. 'mean': [0.485, 0.456, 0.406],
  40. 'scale': '1./255.',
  41. 'order': 'hwc'
  42. }
  43. }, {
  44. 'ToCHWImage': None
  45. }, {
  46. 'KeepKeys': {
  47. 'keep_keys': ['image', 'shape']
  48. }
  49. }]
  50. postprocess_params = {}
  51. if self.det_algorithm == "DB":
  52. postprocess_params['name'] = 'DBPostProcess'
  53. postprocess_params["thresh"] = args.det_db_thresh
  54. postprocess_params["box_thresh"] = args.det_db_box_thresh
  55. postprocess_params["max_candidates"] = 1000
  56. postprocess_params["unclip_ratio"] = args.det_db_unclip_ratio
  57. postprocess_params["use_dilation"] = args.use_dilation
  58. elif self.det_algorithm == "EAST":
  59. postprocess_params['name'] = 'EASTPostProcess'
  60. postprocess_params["score_thresh"] = args.det_east_score_thresh
  61. postprocess_params["cover_thresh"] = args.det_east_cover_thresh
  62. postprocess_params["nms_thresh"] = args.det_east_nms_thresh
  63. elif self.det_algorithm == "SAST":
  64. pre_process_list[0] = {
  65. 'DetResizeForTest': {
  66. 'resize_long': args.det_limit_side_len
  67. }
  68. }
  69. postprocess_params['name'] = 'SASTPostProcess'
  70. postprocess_params["score_thresh"] = args.det_sast_score_thresh
  71. postprocess_params["nms_thresh"] = args.det_sast_nms_thresh
  72. self.det_sast_polygon = args.det_sast_polygon
  73. if self.det_sast_polygon:
  74. postprocess_params["sample_pts_num"] = 6
  75. postprocess_params["expand_scale"] = 1.2
  76. postprocess_params["shrink_ratio_of_width"] = 0.2
  77. else:
  78. postprocess_params["sample_pts_num"] = 2
  79. postprocess_params["expand_scale"] = 1.0
  80. postprocess_params["shrink_ratio_of_width"] = 0.3
  81. else:
  82. logger.info("unknown det_algorithm:{}".format(self.det_algorithm))
  83. sys.exit(0)
  84. self.preprocess_op = create_operators(pre_process_list)
  85. self.postprocess_op = build_post_process(postprocess_params)
  86. self.predictor, self.input_tensor, self.output_tensors = utility.create_predictor(
  87. args, 'det', logger) # paddle.jit.load(args.det_model_dir)
  88. # self.predictor.eval()
  89. def order_points_clockwise(self, pts):
  90. """
  91. reference from: https://github.com/jrosebr1/imutils/blob/master/imutils/perspective.py
  92. # sort the points based on their x-coordinates
  93. """
  94. xSorted = pts[np.argsort(pts[:, 0]), :]
  95. # grab the left-most and right-most points from the sorted
  96. # x-roodinate points
  97. leftMost = xSorted[:2, :]
  98. rightMost = xSorted[2:, :]
  99. # now, sort the left-most coordinates according to their
  100. # y-coordinates so we can grab the top-left and bottom-left
  101. # points, respectively
  102. leftMost = leftMost[np.argsort(leftMost[:, 1]), :]
  103. (tl, bl) = leftMost
  104. rightMost = rightMost[np.argsort(rightMost[:, 1]), :]
  105. (tr, br) = rightMost
  106. rect = np.array([tl, tr, br, bl], dtype="float32")
  107. return rect
  108. def clip_det_res(self, points, img_height, img_width):
  109. for pno in range(points.shape[0]):
  110. points[pno, 0] = int(min(max(points[pno, 0], 0), img_width - 1))
  111. points[pno, 1] = int(min(max(points[pno, 1], 0), img_height - 1))
  112. return points
  113. def filter_tag_det_res(self, dt_boxes, image_shape):
  114. img_height, img_width = image_shape[0:2]
  115. dt_boxes_new = []
  116. for box in dt_boxes:
  117. box = self.order_points_clockwise(box)
  118. box = self.clip_det_res(box, img_height, img_width)
  119. rect_width = int(np.linalg.norm(box[0] - box[1]))
  120. rect_height = int(np.linalg.norm(box[0] - box[3]))
  121. if rect_width <= 3 or rect_height <= 3:
  122. continue
  123. dt_boxes_new.append(box)
  124. dt_boxes = np.array(dt_boxes_new)
  125. return dt_boxes
  126. def filter_tag_det_res_only_clip(self, dt_boxes, image_shape):
  127. img_height, img_width = image_shape[0:2]
  128. dt_boxes_new = []
  129. for box in dt_boxes:
  130. box = self.clip_det_res(box, img_height, img_width)
  131. dt_boxes_new.append(box)
  132. dt_boxes = np.array(dt_boxes_new)
  133. return dt_boxes
  134. def __call__(self, img):
  135. ori_im = img.copy()
  136. data = {'image': img}
  137. data = transform(data, self.preprocess_op)
  138. img, shape_list = data
  139. if img is None:
  140. return None, 0
  141. img = np.expand_dims(img, axis=0)
  142. shape_list = np.expand_dims(shape_list, axis=0)
  143. img = img.copy()
  144. starttime = time.time()
  145. self.input_tensor.copy_from_cpu(img)
  146. self.predictor.run()
  147. outputs = []
  148. for output_tensor in self.output_tensors:
  149. output = output_tensor.copy_to_cpu()
  150. outputs.append(output)
  151. preds = {}
  152. if self.det_algorithm == "EAST":
  153. preds['f_geo'] = outputs[0]
  154. preds['f_score'] = outputs[1]
  155. elif self.det_algorithm == 'SAST':
  156. preds['f_border'] = outputs[0]
  157. preds['f_score'] = outputs[1]
  158. preds['f_tco'] = outputs[2]
  159. preds['f_tvo'] = outputs[3]
  160. elif self.det_algorithm == 'DB':
  161. preds['maps'] = outputs[0]
  162. else:
  163. raise NotImplementedError
  164. post_result = self.postprocess_op(preds, shape_list)
  165. dt_boxes = post_result[0]['points']
  166. if self.det_algorithm == "SAST" and self.det_sast_polygon:
  167. dt_boxes = self.filter_tag_det_res_only_clip(dt_boxes, ori_im.shape)
  168. else:
  169. dt_boxes = self.filter_tag_det_res(dt_boxes, ori_im.shape)
  170. elapse = time.time() - starttime
  171. return dt_boxes, elapse
  172. if __name__ == "__main__":
  173. args = utility.parse_args()
  174. image_file_list = get_image_file_list(args.image_dir)
  175. text_detector = TextDetector(args)
  176. count = 0
  177. total_time = 0
  178. draw_img_save = "./inference_results"
  179. if not os.path.exists(draw_img_save):
  180. os.makedirs(draw_img_save)
  181. for image_file in image_file_list:
  182. img, flag = check_and_read_gif(image_file)
  183. if not flag:
  184. img = cv2.imread(image_file)
  185. if img is None:
  186. logger.info("error in loading image:{}".format(image_file))
  187. continue
  188. dt_boxes, elapse = text_detector(img)
  189. if count > 0:
  190. total_time += elapse
  191. count += 1
  192. logger.info("Predict time of {}: {}".format(image_file, elapse))
  193. src_im = utility.draw_text_det_res(dt_boxes, image_file)
  194. img_name_pure = os.path.split(image_file)[-1]
  195. img_path = os.path.join(draw_img_save,
  196. "det_res_{}".format(img_name_pure))
  197. cv2.imwrite(img_path, src_im)
  198. logger.info("The visualized image saved in {}".format(img_path))
  199. if count > 1:
  200. logger.info("Avg Time: {}".format(total_time / (count - 1)))