convert_image.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. import logging
  2. import os
  3. import sys
  4. from pdfminer.layout import LTLine
  5. sys.path.append(os.path.dirname(__file__) + "/../")
  6. import traceback
  7. import cv2
  8. from format_convert import get_memory_info
  9. from format_convert.utils import judge_error_code, add_div, LineTable
  10. from format_convert.table_correct import get_rotated_image
  11. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface
  12. def image_preprocess(image_np, image_path, use_ocr=True):
  13. logging.info("into image_preprocess")
  14. try:
  15. # 长 宽
  16. # resize_size = (1024, 768)
  17. # 限制图片大小
  18. # resize_image(image_path, resize_size)
  19. # 图片倾斜校正,写入原来的图片路径
  20. g_r_i = get_rotated_image(image_np, image_path)
  21. if g_r_i == [-1]:
  22. return [-1], [], [], 0
  23. # otr需要图片resize, 写入另一个路径
  24. image_np = cv2.imread(image_path)
  25. best_h, best_w = get_best_predict_size(image_np)
  26. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  27. # image_resize_path = image_path[:-4] + "_resize" + image_path[-4:]
  28. image_resize_path = image_path.split(".")[0] + "_resize." + image_path.split(".")[-1]
  29. cv2.imwrite(image_resize_path, image_resize)
  30. # 调用otr模型接口
  31. with open(image_resize_path, "rb") as f:
  32. image_bytes = f.read()
  33. points, split_lines, bboxes, outline_points, lines = from_otr_interface(image_bytes)
  34. if judge_error_code(points):
  35. return points, [], [], 0
  36. # 将resize后得到的bbox根据比例还原
  37. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  38. for i in range(len(bboxes)):
  39. bbox = bboxes[i]
  40. bboxes[i] = [(int(bbox[0][0]*ratio[1]), int(bbox[0][1]*ratio[0])),
  41. (int(bbox[1][0]*ratio[1]), int(bbox[1][1]*ratio[0]))]
  42. for i in range(len(split_lines)):
  43. line = split_lines[i]
  44. split_lines[i] = [(int(line[0][0]*ratio[1]), int(line[0][1]*ratio[0])),
  45. (int(line[1][0]*ratio[1]), int(line[1][1]*ratio[0]))]
  46. for i in range(len(points)):
  47. point = points[i]
  48. points[i] = (int(point[0]*ratio[1]), int(point[1]*ratio[0]))
  49. for i in range(len(outline_points)):
  50. point = outline_points[i]
  51. outline_points[i] = [(int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])),
  52. (int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0]))]
  53. for i in range(len(lines)):
  54. point = lines[i]
  55. lines[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  56. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  57. # 查看是否能输出正确框
  58. for box in bboxes:
  59. cv2.rectangle(image_np, box[0], box[1], (0, 255, 0), 2)
  60. # cv2.namedWindow('bbox', 0)
  61. # cv2.imshow("bbox", image_np)
  62. # cv2.waitKey(0)
  63. # 调用ocr模型接口
  64. with open(image_path, "rb") as f:
  65. image_bytes = f.read()
  66. # 有表格
  67. if len(bboxes) >= 2:
  68. text_list, bbox_list = from_ocr_interface(image_bytes, True)
  69. if judge_error_code(text_list):
  70. return text_list, [], [], 0
  71. # for i in range(len(text_list)):
  72. # print(text_list[i], bbox_list[i])
  73. # 查看是否能输出正确框
  74. # for box in bbox_list:
  75. # cv2.rectangle(image_np, (int(box[0][0]), int(box[0][1])),
  76. # (int(box[2][0]), int(box[2][1])), (255, 0, 0), 1)
  77. # cv2.namedWindow('bbox', 0)
  78. # cv2.imshow("bbox", image_np)
  79. # cv2.waitKey(0)
  80. # text, column_list = get_formatted_table(text_list, bbox_list, bboxes, split_lines)
  81. # 调用现成方法形成表格
  82. try:
  83. from format_convert.convert_tree import TableLine
  84. list_lines = []
  85. for line in lines:
  86. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  87. from format_convert.convert_tree import TextBox
  88. list_text_boxes = []
  89. for i in range(len(bbox_list)):
  90. bbox = bbox_list[i]
  91. b_text = text_list[i]
  92. list_text_boxes.append(TextBox([bbox[3][0], bbox[3][1],
  93. bbox[1][0], bbox[1][1]], b_text))
  94. lt = LineTable()
  95. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines)
  96. text = [tables, obj_in_table]
  97. column_list = []
  98. except:
  99. traceback.print_exc()
  100. text = [-8]
  101. column_list = []
  102. if judge_error_code(text):
  103. return text, [], [], 0
  104. is_table = 1
  105. return text, column_list, outline_points, is_table
  106. # 无表格
  107. else:
  108. if use_ocr:
  109. text = from_ocr_interface(image_bytes)
  110. if judge_error_code(text):
  111. return text, [], [], 0
  112. is_table = 0
  113. return text, [], [], is_table
  114. else:
  115. is_table = 0
  116. return None, [], [], is_table
  117. except Exception as e:
  118. logging.info("image_preprocess error")
  119. print("image_preprocess", traceback.print_exc())
  120. return [-1], [], [], 0
  121. @get_memory_info.memory_decorator
  122. def picture2text(path, html=False):
  123. logging.info("into picture2text")
  124. try:
  125. # 判断图片中表格
  126. img = cv2.imread(path)
  127. if img is None:
  128. return [-3]
  129. text, column_list, outline_points, is_table = image_preprocess(img, path)
  130. if judge_error_code(text):
  131. return text
  132. if html:
  133. text = add_div(text)
  134. return [text]
  135. except Exception as e:
  136. logging.info("picture2text error!")
  137. print("picture2text", traceback.print_exc())
  138. return [-1]
  139. def get_best_predict_size(image_np, times=64):
  140. sizes = []
  141. for i in range(1, 100):
  142. if i*times <= 3000:
  143. sizes.append(i*times)
  144. sizes.sort(key=lambda x: x, reverse=True)
  145. min_len = 10000
  146. best_height = sizes[0]
  147. for height in sizes:
  148. if abs(image_np.shape[0] - height) < min_len:
  149. min_len = abs(image_np.shape[0] - height)
  150. best_height = height
  151. min_len = 10000
  152. best_width = sizes[0]
  153. for width in sizes:
  154. if abs(image_np.shape[1] - width) < min_len:
  155. min_len = abs(image_np.shape[1] - width)
  156. best_width = width
  157. return best_height, best_width