predict_system.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. sys.path.append(os.path.abspath(os.path.join(__dir__, '../../..')))
  20. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  21. # print("sys.path", sys.path)
  22. import cv2
  23. import copy
  24. import numpy as np
  25. import time
  26. from PIL import Image
  27. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  28. import utility as utility
  29. # import ocr.tools.infer.predict_rec as predict_rec
  30. import ocr.tools.infer.predict_rec_pytorch as predict_rec # pytorch rec model
  31. # import ocr.tools.infer.predict_det as predict_det
  32. import ocr.tools.infer.predict_det_pytorch as predict_det # pytorch det model
  33. import ocr.tools.infer.predict_cls as predict_cls
  34. from ocr.ppocr.utils.utility import get_image_file_list, check_and_read_gif
  35. from ocr.ppocr.utils.logging import get_logger
  36. from ocr.tools.infer.utility import draw_ocr_box_txt
  37. from format_convert.utils import has_intersection
  38. logger = get_logger()
  39. class TextSystem(object):
  40. def __init__(self, args):
  41. self.text_detector = predict_det.TextDetector(args)
  42. self.text_recognizer = predict_rec.TextRecognizer(args)
  43. self.use_angle_cls = args.use_angle_cls
  44. self.drop_score = args.drop_score
  45. if self.use_angle_cls:
  46. self.text_classifier = predict_cls.TextClassifier(args)
  47. def get_rotate_crop_image(self, img, points):
  48. '''
  49. img_height, img_width = img.shape[0:2]
  50. left = int(np.min(points[:, 0]))
  51. right = int(np.max(points[:, 0]))
  52. top = int(np.min(points[:, 1]))
  53. bottom = int(np.max(points[:, 1]))
  54. img_crop = img[top:bottom, left:right, :].copy()
  55. points[:, 0] = points[:, 0] - left
  56. points[:, 1] = points[:, 1] - top
  57. '''
  58. img_crop_width = int(
  59. max(
  60. np.linalg.norm(points[0] - points[1]),
  61. np.linalg.norm(points[2] - points[3])))
  62. img_crop_height = int(
  63. max(
  64. np.linalg.norm(points[0] - points[3]),
  65. np.linalg.norm(points[1] - points[2])))
  66. pts_std = np.float32([[0, 0], [img_crop_width, 0],
  67. [img_crop_width, img_crop_height],
  68. [0, img_crop_height]])
  69. M = cv2.getPerspectiveTransform(points, pts_std)
  70. dst_img = cv2.warpPerspective(
  71. img,
  72. M, (img_crop_width, img_crop_height),
  73. borderMode=cv2.BORDER_REPLICATE,
  74. flags=cv2.INTER_CUBIC)
  75. dst_img_height, dst_img_width = dst_img.shape[0:2]
  76. # if dst_img_height * 1.0 / dst_img_width >= 1.5:
  77. if dst_img_height * 1.0 / dst_img_width >= 2.0:
  78. dst_img = np.rot90(dst_img)
  79. return dst_img
  80. def print_draw_crop_rec_res(self, img_crop_list, rec_res):
  81. bbox_num = len(img_crop_list)
  82. for bno in range(bbox_num):
  83. cv2.imwrite("./output/img_crop_%d.jpg" % bno, img_crop_list[bno])
  84. logger.info(bno, rec_res[bno])
  85. def __call__(self, img):
  86. # cv2.imshow('img',img)
  87. # cv2.waitKey(0)
  88. ori_im = img.copy()
  89. dt_boxes, elapse = self.text_detector(img)
  90. logger.info("dt_boxes num : {}, elapse : {}".format(
  91. len(dt_boxes), elapse))
  92. if dt_boxes is None:
  93. return None, None
  94. img_crop_list = []
  95. dt_boxes = sorted_boxes(dt_boxes)
  96. for bno in range(len(dt_boxes)):
  97. tmp_box = copy.deepcopy(dt_boxes[bno])
  98. img_crop = self.get_rotate_crop_image(ori_im, tmp_box)
  99. img_crop_list.append(img_crop)
  100. if self.use_angle_cls:
  101. img_crop_list, angle_list, elapse = self.text_classifier(
  102. img_crop_list)
  103. logger.info("cls num : {}, elapse : {}".format(
  104. len(img_crop_list), elapse))
  105. rec_res, elapse = self.text_recognizer(img_crop_list)
  106. logger.info("rec_res num : {}, elapse : {}".format(
  107. len(rec_res), elapse))
  108. # self.print_draw_crop_rec_res(img_crop_list, rec_res)
  109. filter_boxes, filter_rec_res = [], []
  110. # dt_boxes 上下重合检测框修正
  111. # t1 = time.time()
  112. dt_boxes = boxex_points_fixup(dt_boxes)
  113. # print("boxex_points_fixup cost:",time.time()-t1)
  114. for box, rec_reuslt in zip(dt_boxes, rec_res):
  115. text, score = rec_reuslt
  116. if score >= self.drop_score:
  117. filter_boxes.append(box)
  118. filter_rec_res.append(rec_reuslt)
  119. return filter_boxes, filter_rec_res
  120. def boxex_points_fixup(dt_boxes):
  121. # 检查框全部转换为矩形
  122. # for i in range(len(dt_boxes)):
  123. # box1 = dt_boxes[i]
  124. # x_list = [box1[0][0],box1[1][0],box1[2][0],box1[3][0]]
  125. # y_list = [box1[0][1],box1[1][1],box1[2][1],box1[3][1]]
  126. # x_max = max(x_list)
  127. # x_min = min(x_list)
  128. # y_max = max(y_list)
  129. # y_min = min(y_list)
  130. # dt_boxes[i] = np.array([[x_min,y_min],[x_max,y_min],[x_max,y_max],[x_min,y_max]])
  131. for i in range(len(dt_boxes)):
  132. box1 = dt_boxes[i]
  133. box1_point3 = box1[2]
  134. box1_point4 = box1[3] # 四边形底边的两点坐标
  135. bottom_line = (min(box1_point3[0],box1_point4[0]),max(box1_point3[0],box1_point4[0]))
  136. bottom_line_len = abs(bottom_line[1]-bottom_line[0])
  137. for j in range(i+1,len(dt_boxes)):
  138. box2 = dt_boxes[j]
  139. box2_point1 = box2[0]
  140. box2_point2 = box2[1] # 四边形顶边的两点坐标
  141. top_line = (min(box2_point1[0], box2_point2[0]), max(box2_point1[0], box2_point2[0]))
  142. top_line_len = abs(top_line[1]-top_line[0])
  143. if has_intersection(box1, box2): # 四边形框是否有交集
  144. if not (min(top_line)>=max(bottom_line) or min(bottom_line)>=max(top_line)): # x轴方向上有交集
  145. # 求重合部分y中间值
  146. mid_y = ((box2_point1[1] + box2_point2[1]) / 2 + (box1_point3[1] + box1_point4[1]) / 2) // 2
  147. if not mid_y:
  148. continue
  149. max_line_len = max(bottom_line_len,top_line_len)
  150. cross_line_len = bottom_line_len + top_line_len - \
  151. (max(bottom_line[1],bottom_line[0],top_line[1],top_line[0]) - min(bottom_line[1],bottom_line[0],top_line[1],top_line[0]))
  152. # print(cross_line_len,max_line_len,cross_line_len/max_line_len)
  153. if cross_line_len/max_line_len>=0.55: # 重合比例
  154. box1[2] = [box1_point3[0],mid_y]
  155. box1[3] = [box1_point4[0],mid_y]
  156. box2[0] = [box2_point1[0],mid_y]
  157. box2[1] = [box2_point2[0],mid_y]
  158. break
  159. return dt_boxes
  160. def sorted_boxes(dt_boxes):
  161. """
  162. Sort text boxes in order from top to bottom, left to right
  163. args:
  164. dt_boxes(array):detected text boxes with shape [4, 2]
  165. return:
  166. sorted boxes(array) with shape [4, 2]
  167. """
  168. num_boxes = dt_boxes.shape[0]
  169. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  170. _boxes = list(sorted_boxes)
  171. for i in range(num_boxes - 1):
  172. if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \
  173. (_boxes[i + 1][0][0] < _boxes[i][0][0]):
  174. tmp = _boxes[i]
  175. _boxes[i] = _boxes[i + 1]
  176. _boxes[i + 1] = tmp
  177. return _boxes
  178. def main(args):
  179. image_file_list = get_image_file_list(args.image_dir)
  180. text_sys = TextSystem(args)
  181. is_visualize = True
  182. font_path = args.vis_font_path
  183. drop_score = args.drop_score
  184. for image_file in image_file_list:
  185. img, flag = check_and_read_gif(image_file)
  186. if not flag:
  187. img = cv2.imread(image_file)
  188. if img is None:
  189. logger.info("error in loading image:{}".format(image_file))
  190. continue
  191. starttime = time.time()
  192. dt_boxes, rec_res = text_sys(img)
  193. elapse = time.time() - starttime
  194. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  195. for text, score in rec_res:
  196. logger.info("{}, {:.3f}".format(text, score))
  197. if is_visualize:
  198. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  199. boxes = dt_boxes
  200. txts = [rec_res[i][0] for i in range(len(rec_res))]
  201. scores = [rec_res[i][1] for i in range(len(rec_res))]
  202. draw_img = draw_ocr_box_txt(
  203. image,
  204. boxes,
  205. txts,
  206. scores,
  207. drop_score=drop_score,
  208. font_path=font_path)
  209. draw_img_save = "./inference_results/"
  210. if not os.path.exists(draw_img_save):
  211. os.makedirs(draw_img_save)
  212. cv2.imwrite(
  213. os.path.join(draw_img_save, os.path.basename(image_file)),
  214. draw_img[:, :, ::-1])
  215. logger.info("The visualized image saved in {}".format(
  216. os.path.join(draw_img_save, os.path.basename(image_file))))
  217. if __name__ == "__main__":
  218. main(utility.parse_args())
  219. pass