predict_system.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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, log
  38. from format_convert import _global
  39. logger = get_logger()
  40. class TextSystem(object):
  41. def __init__(self, args):
  42. self.text_detector = predict_det.TextDetector(args)
  43. self.text_recognizer = predict_rec.TextRecognizer(args)
  44. self.use_angle_cls = args.use_angle_cls
  45. self.drop_score = args.drop_score
  46. if self.use_angle_cls:
  47. self.text_classifier = predict_cls.TextClassifier(args)
  48. def get_rotate_crop_image(self, img, points):
  49. '''
  50. img_height, img_width = img.shape[0:2]
  51. left = int(np.min(points[:, 0]))
  52. right = int(np.max(points[:, 0]))
  53. top = int(np.min(points[:, 1]))
  54. bottom = int(np.max(points[:, 1]))
  55. img_crop = img[top:bottom, left:right, :].copy()
  56. points[:, 0] = points[:, 0] - left
  57. points[:, 1] = points[:, 1] - top
  58. '''
  59. # img_crop_width = int(
  60. # max(
  61. # np.linalg.norm(points[0] - points[1]),
  62. # np.linalg.norm(points[2] - points[3])))
  63. # img_crop_height = int(
  64. # max(
  65. # np.linalg.norm(points[0] - points[3]),
  66. # np.linalg.norm(points[1] - points[2])))
  67. # pts_std = np.float32([[0, 0], [img_crop_width, 0],
  68. # [img_crop_width, img_crop_height],
  69. # [0, img_crop_height]])
  70. # M = cv2.getPerspectiveTransform(points, pts_std)
  71. # dst_img = cv2.warpPerspective(
  72. # img,
  73. # M, (img_crop_width, img_crop_height),
  74. # borderMode=cv2.BORDER_REPLICATE,
  75. # flags=cv2.INTER_CUBIC)
  76. # print('dst_img.shape', dst_img.shape)
  77. #
  78. # print('points', points)
  79. w = abs(points[2][0] - points[0][0])
  80. h = abs(points[2][1] - points[0][1])
  81. dst_img = img[int(points[0][1]):int(points[0][1] + h), int(points[0][0]):int(points[0][0] + w), :]
  82. # print('dst_img.shape2', dst_img.shape)
  83. # cv2.imshow('dst_img', dst_img)
  84. # cv2.waitKey(0)
  85. # dst_img_height, dst_img_width = dst_img.shape[0:2]
  86. # # if dst_img_height * 1.0 / dst_img_width >= 1.5:
  87. # if dst_img_height * 1.0 / dst_img_width >= 2.0:
  88. # dst_img = np.rot90(dst_img)
  89. return dst_img
  90. def print_draw_crop_rec_res(self, img_crop_list, rec_res):
  91. bbox_num = len(img_crop_list)
  92. for bno in range(bbox_num):
  93. cv2.imwrite("./output/img_crop_%d.jpg" % bno, img_crop_list[bno])
  94. logger.info(bno, rec_res[bno])
  95. def __call__(self, img):
  96. # print('into TextSystem __call__')
  97. # cv2.imshow('img',img)
  98. # cv2.waitKey(0)
  99. ori_im = img.copy()
  100. dt_boxes, elapse = self.text_detector(img)
  101. logger.info("dt_boxes num : {}, elapse : {}".format(
  102. len(dt_boxes), elapse))
  103. if dt_boxes is None:
  104. return [], []
  105. temp_list = []
  106. # print('dt_boxes', type(dt_boxes))
  107. # print('dt_boxes.shape', dt_boxes.shape)
  108. # 过滤一些比例离谱的box
  109. for b in dt_boxes:
  110. w = b[2][0] - b[0][0]
  111. h = b[2][1] - b[0][1]
  112. if h == 0 or w == 0 \
  113. or h >= 10000 or w >= 10000 \
  114. or w / h <= 0.5 or w / h >= 100:
  115. continue
  116. temp_list.append(b)
  117. if not temp_list:
  118. return [], []
  119. dt_boxes = np.array(temp_list)
  120. # print('dt_boxes.shape2', dt_boxes.shape)
  121. # show
  122. # for b in dt_boxes:
  123. # p1 = [int(x) for x in b[0]]
  124. # p2 = [int(x) for x in b[2]]
  125. # cv2.rectangle(img, p1, p2, (0, 0, 255))
  126. # cv2.namedWindow('img', cv2.WINDOW_NORMAL)
  127. # cv2.imshow('img', img)
  128. # cv2.waitKey(0)
  129. # # 检测过多单字box,返回None
  130. # if len(dt_boxes) >= 150:
  131. # short_box_cnt = 0
  132. # long_box_cnt = 0
  133. # for b in dt_boxes:
  134. # w = b[2][0] - b[0][0]
  135. # h = b[2][1] - b[0][1]
  136. # if w / h < 1.3:
  137. # short_box_cnt += 1
  138. # if w / h >= 3:
  139. # long_box_cnt += 1
  140. # print('dt_boxes', w, h, round(w/h, 3))
  141. # # print('short_box_cnt, len(dt_boxes)', short_box_cnt, len(dt_boxes))
  142. # log('short_box_cnt, long_box_cnt, len(dt_boxes) ' + str([short_box_cnt, long_box_cnt, len(dt_boxes)]))
  143. # if short_box_cnt >= 2/3 * len(dt_boxes) and long_box_cnt < 10:
  144. # # print('short_box_cnt >= 2/3 * len(dt_boxes), return None')
  145. # log('short_box_cnt >= 2/3 * len(dt_boxes), return None. ' + str([short_box_cnt, long_box_cnt, len(dt_boxes)]))
  146. # return [], []
  147. img_crop_list = []
  148. dt_boxes = sorted_boxes(dt_boxes)
  149. for bno in range(len(dt_boxes)):
  150. tmp_box = copy.deepcopy(dt_boxes[bno])
  151. img_crop = self.get_rotate_crop_image(ori_im, tmp_box)
  152. img_crop_list.append(img_crop)
  153. # print('system len(img_crop_list)', len(img_crop_list))
  154. # for img in img_crop_list:
  155. # if img.shape[1] / img.shape[0] <= 0.5:
  156. # print('system img.shape[1] / img.shape[0] <= 0.5', img.shape)
  157. if self.use_angle_cls:
  158. img_crop_list, angle_list, elapse = self.text_classifier(
  159. img_crop_list)
  160. logger.info("cls num : {}, elapse : {}".format(
  161. len(img_crop_list), elapse))
  162. rec_res, elapse = self.text_recognizer(img_crop_list)
  163. logger.info("rec_res num : {}, elapse : {}".format(
  164. len(rec_res), elapse))
  165. # self.print_draw_crop_rec_res(img_crop_list, rec_res)
  166. filter_boxes, filter_rec_res = [], []
  167. # dt_boxes 上下重合检测框修正
  168. # t1 = time.time()
  169. dt_boxes = boxex_points_fixup(dt_boxes)
  170. # print("boxex_points_fixup cost:",time.time()-t1)
  171. for box, rec_reuslt in zip(dt_boxes, rec_res):
  172. text, score = rec_reuslt
  173. if score >= self.drop_score:
  174. filter_boxes.append(box)
  175. filter_rec_res.append(rec_reuslt)
  176. return filter_boxes, filter_rec_res
  177. def boxex_points_fixup(dt_boxes):
  178. # 检查框全部转换为矩形
  179. # for i in range(len(dt_boxes)):
  180. # box1 = dt_boxes[i]
  181. # x_list = [box1[0][0],box1[1][0],box1[2][0],box1[3][0]]
  182. # y_list = [box1[0][1],box1[1][1],box1[2][1],box1[3][1]]
  183. # x_max = max(x_list)
  184. # x_min = min(x_list)
  185. # y_max = max(y_list)
  186. # y_min = min(y_list)
  187. # dt_boxes[i] = np.array([[x_min,y_min],[x_max,y_min],[x_max,y_max],[x_min,y_max]])
  188. for i in range(len(dt_boxes)):
  189. box1 = dt_boxes[i]
  190. box1_point3 = box1[2]
  191. box1_point4 = box1[3] # 四边形底边的两点坐标
  192. bottom_line = (min(box1_point3[0], box1_point4[0]), max(box1_point3[0], box1_point4[0]))
  193. bottom_line_len = abs(bottom_line[1] - bottom_line[0])
  194. for j in range(i + 1, len(dt_boxes)):
  195. box2 = dt_boxes[j]
  196. box2_point1 = box2[0]
  197. box2_point2 = box2[1] # 四边形顶边的两点坐标
  198. top_line = (min(box2_point1[0], box2_point2[0]), max(box2_point1[0], box2_point2[0]))
  199. top_line_len = abs(top_line[1] - top_line[0])
  200. if has_intersection(box1, box2): # 四边形框是否有交集
  201. if not (min(top_line) >= max(bottom_line) or min(bottom_line) >= max(top_line)): # x轴方向上有交集
  202. # 求重合部分y中间值
  203. mid_y = ((box2_point1[1] + box2_point2[1]) / 2 + (box1_point3[1] + box1_point4[1]) / 2) // 2
  204. if not mid_y:
  205. continue
  206. max_line_len = max(bottom_line_len, top_line_len)
  207. cross_line_len = bottom_line_len + top_line_len - \
  208. (max(bottom_line[1], bottom_line[0], top_line[1], top_line[0]) - min(
  209. bottom_line[1], bottom_line[0], top_line[1], top_line[0]))
  210. # print(cross_line_len,max_line_len,cross_line_len/max_line_len)
  211. if cross_line_len / max_line_len >= 0.55: # 重合比例
  212. box1[2] = [box1_point3[0], mid_y]
  213. box1[3] = [box1_point4[0], mid_y]
  214. box2[0] = [box2_point1[0], mid_y]
  215. box2[1] = [box2_point2[0], mid_y]
  216. break
  217. return dt_boxes
  218. def sorted_boxes(dt_boxes):
  219. """
  220. Sort text boxes in order from top to bottom, left to right
  221. args:
  222. dt_boxes(array):detected text boxes with shape [4, 2]
  223. return:
  224. sorted boxes(array) with shape [4, 2]
  225. """
  226. num_boxes = dt_boxes.shape[0]
  227. sorted_boxes = sorted(dt_boxes, key=lambda x: (x[0][1], x[0][0]))
  228. _boxes = list(sorted_boxes)
  229. for i in range(num_boxes - 1):
  230. if abs(_boxes[i + 1][0][1] - _boxes[i][0][1]) < 10 and \
  231. (_boxes[i + 1][0][0] < _boxes[i][0][0]):
  232. tmp = _boxes[i]
  233. _boxes[i] = _boxes[i + 1]
  234. _boxes[i + 1] = tmp
  235. return _boxes
  236. def main(args):
  237. image_file_list = get_image_file_list(args.image_dir)
  238. text_sys = TextSystem(args)
  239. is_visualize = True
  240. font_path = args.vis_font_path
  241. drop_score = args.drop_score
  242. for image_file in image_file_list:
  243. img, flag = check_and_read_gif(image_file)
  244. if not flag:
  245. img = cv2.imread(image_file)
  246. if img is None:
  247. logger.info("error in loading image:{}".format(image_file))
  248. continue
  249. starttime = time.time()
  250. dt_boxes, rec_res = text_sys(img)
  251. elapse = time.time() - starttime
  252. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  253. for text, score in rec_res:
  254. logger.info("{}, {:.3f}".format(text, score))
  255. if is_visualize:
  256. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  257. boxes = dt_boxes
  258. txts = [rec_res[i][0] for i in range(len(rec_res))]
  259. scores = [rec_res[i][1] for i in range(len(rec_res))]
  260. draw_img = draw_ocr_box_txt(
  261. image,
  262. boxes,
  263. txts,
  264. scores,
  265. drop_score=drop_score,
  266. font_path=font_path)
  267. draw_img_save = "./inference_results/"
  268. if not os.path.exists(draw_img_save):
  269. os.makedirs(draw_img_save)
  270. cv2.imwrite(
  271. os.path.join(draw_img_save, os.path.basename(image_file)),
  272. draw_img[:, :, ::-1])
  273. logger.info("The visualized image saved in {}".format(
  274. os.path.join(draw_img_save, os.path.basename(image_file))))
  275. if __name__ == "__main__":
  276. main(utility.parse_args())
  277. pass