predict_system.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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 copy
  22. import numpy as np
  23. import time
  24. from PIL import Image
  25. import tools.infer.utility as utility
  26. import tools.infer.predict_rec as predict_rec
  27. import tools.infer.predict_det as predict_det
  28. import tools.infer.predict_cls as predict_cls
  29. from ppocr.utils.utility import get_image_file_list, check_and_read_gif
  30. from ppocr.utils.logging import get_logger
  31. from tools.infer.utility import draw_ocr_box_txt
  32. logger = get_logger()
  33. class TextSystem(object):
  34. def __init__(self, args):
  35. self.text_detector = predict_det.TextDetector(args)
  36. self.text_recognizer = predict_rec.TextRecognizer(args)
  37. self.use_angle_cls = args.use_angle_cls
  38. self.drop_score = args.drop_score
  39. if self.use_angle_cls:
  40. self.text_classifier = predict_cls.TextClassifier(args)
  41. def get_rotate_crop_image(self, img, points):
  42. '''
  43. img_height, img_width = img.shape[0:2]
  44. left = int(np.min(points[:, 0]))
  45. right = int(np.max(points[:, 0]))
  46. top = int(np.min(points[:, 1]))
  47. bottom = int(np.max(points[:, 1]))
  48. img_crop = img[top:bottom, left:right, :].copy()
  49. points[:, 0] = points[:, 0] - left
  50. points[:, 1] = points[:, 1] - top
  51. '''
  52. img_crop_width = int(
  53. max(
  54. np.linalg.norm(points[0] - points[1]),
  55. np.linalg.norm(points[2] - points[3])))
  56. img_crop_height = int(
  57. max(
  58. np.linalg.norm(points[0] - points[3]),
  59. np.linalg.norm(points[1] - points[2])))
  60. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  61. [img_crop_width, img_crop_height],
  62. [0, img_crop_height]])
  63. M = cv2.getPerspectiveTransform(points, pts_std)
  64. dst_img = cv2.warpPerspective(
  65. img,
  66. M, (img_crop_width, img_crop_height),
  67. borderMode=cv2.BORDER_REPLICATE,
  68. flags=cv2.INTER_CUBIC)
  69. dst_img_height, dst_img_width = dst_img.shape[0:2]
  70. if dst_img_height * 1.0 / dst_img_width >= 1.5:
  71. dst_img = np.rot90(dst_img)
  72. return dst_img
  73. def print_draw_crop_rec_res(self, img_crop_list, rec_res):
  74. bbox_num = len(img_crop_list)
  75. for bno in range(bbox_num):
  76. cv2.imwrite("./output/img_crop_%d.jpg" % bno, img_crop_list[bno])
  77. logger.info(bno, rec_res[bno])
  78. def __call__(self, img):
  79. ori_im = img.copy()
  80. dt_boxes, elapse = self.text_detector(img)
  81. logger.info("dt_boxes num : {}, elapse : {}".format(
  82. len(dt_boxes), elapse))
  83. if dt_boxes is None:
  84. return None, None
  85. img_crop_list = []
  86. dt_boxes = sorted_boxes(dt_boxes)
  87. for bno in range(len(dt_boxes)):
  88. tmp_box = copy.deepcopy(dt_boxes[bno])
  89. img_crop = self.get_rotate_crop_image(ori_im, tmp_box)
  90. img_crop_list.append(img_crop)
  91. if self.use_angle_cls:
  92. img_crop_list, angle_list, elapse = self.text_classifier(
  93. img_crop_list)
  94. logger.info("cls num : {}, elapse : {}".format(
  95. len(img_crop_list), elapse))
  96. rec_res, elapse = self.text_recognizer(img_crop_list)
  97. logger.info("rec_res num : {}, elapse : {}".format(
  98. len(rec_res), elapse))
  99. # self.print_draw_crop_rec_res(img_crop_list, rec_res)
  100. filter_boxes, filter_rec_res = [], []
  101. for box, rec_reuslt in zip(dt_boxes, rec_res):
  102. text, score = rec_reuslt
  103. if score >= self.drop_score:
  104. filter_boxes.append(box)
  105. filter_rec_res.append(rec_reuslt)
  106. return filter_boxes, filter_rec_res
  107. def sorted_boxes(dt_boxes):
  108. """
  109. Sort text boxes in order from top to bottom, left to right
  110. args:
  111. dt_boxes(array):detected text boxes with shape [4, 2]
  112. return:
  113. sorted boxes(array) with shape [4, 2]
  114. """
  115. num_boxes = dt_boxes.shape[0]
  116. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  117. _boxes = list(sorted_boxes)
  118. for i in range(num_boxes - 1):
  119. if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \
  120. (_boxes[i + 1][0][0] < _boxes[i][0][0]):
  121. tmp = _boxes[i]
  122. _boxes[i] = _boxes[i + 1]
  123. _boxes[i + 1] = tmp
  124. return _boxes
  125. def main(args):
  126. image_file_list = get_image_file_list(args.image_dir)
  127. text_sys = TextSystem(args)
  128. is_visualize = True
  129. font_path = args.vis_font_path
  130. drop_score = args.drop_score
  131. for image_file in image_file_list:
  132. img, flag = check_and_read_gif(image_file)
  133. if not flag:
  134. img = cv2.imread(image_file)
  135. if img is None:
  136. logger.info("error in loading image:{}".format(image_file))
  137. continue
  138. starttime = time.time()
  139. dt_boxes, rec_res = text_sys(img)
  140. elapse = time.time() - starttime
  141. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  142. for text, score in rec_res:
  143. logger.info("{}, {:.3f}".format(text, score))
  144. if is_visualize:
  145. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  146. boxes = dt_boxes
  147. txts = [rec_res[i][0] for i in range(len(rec_res))]
  148. scores = [rec_res[i][1] for i in range(len(rec_res))]
  149. draw_img = draw_ocr_box_txt(
  150. image,
  151. boxes,
  152. txts,
  153. scores,
  154. drop_score=drop_score,
  155. font_path=font_path)
  156. draw_img_save = "./inference_results/"
  157. if not os.path.exists(draw_img_save):
  158. os.makedirs(draw_img_save)
  159. cv2.imwrite(
  160. os.path.join(draw_img_save, os.path.basename(image_file)),
  161. draw_img[:, :, ::-1])
  162. logger.info("The visualized image saved in {}".format(
  163. os.path.join(draw_img_save, os.path.basename(image_file))))
  164. if __name__ == "__main__":
  165. main(utility.parse_args())