convert_image.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import logging
  2. import os
  3. import sys
  4. sys.path.append(os.path.dirname(__file__) + "/../")
  5. from pdfminer.layout import LTLine
  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, get_table_html
  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_process(image_np, image_path, is_from_pdf, use_ocr=True):
  13. from format_convert.convert_tree import _Table, _Sentence
  14. def get_cluster(t_list, b_list, axis):
  15. zip_list = list(zip(t_list, b_list))
  16. if len(zip_list) == 0:
  17. return t_list, b_list
  18. if len(zip_list[0]) > 0:
  19. zip_list.sort(key=lambda x: x[1][axis][1])
  20. cluster_list = []
  21. margin = 5
  22. for text, bbox in zip_list:
  23. _find = 0
  24. for cluster in cluster_list:
  25. if abs(cluster[1] - bbox[axis][1]) <= margin:
  26. cluster[0].append([text, bbox])
  27. cluster[1] = bbox[axis][1]
  28. _find = 1
  29. break
  30. if not _find:
  31. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  32. new_text_list = []
  33. new_bbox_list = []
  34. for cluster in cluster_list:
  35. # print("=============convert_image")
  36. # print("cluster_list", cluster)
  37. center_y = 0
  38. for text, bbox in cluster[0]:
  39. center_y += bbox[axis][1]
  40. center_y = int(center_y / len(cluster[0]))
  41. for text, bbox in cluster[0]:
  42. bbox[axis][1] = center_y
  43. new_text_list.append(text)
  44. new_bbox_list.append(bbox)
  45. # print("cluster_list", cluster)
  46. return new_text_list, new_bbox_list
  47. def merge_textbox(textbox_list, in_objs):
  48. delete_obj = []
  49. threshold = 5
  50. for k in range(len(textbox_list)):
  51. tb1 = textbox_list[k]
  52. if tb1 not in in_objs and tb1 not in delete_obj:
  53. for m in range(k+1, len(textbox_list)):
  54. tb2 = textbox_list[m]
  55. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  56. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  57. if tb1.bbox[0] <= tb2.bbox[0]:
  58. tb1.text = tb1.text + tb2.text
  59. else:
  60. tb1.text = tb2.text + tb1.text
  61. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  62. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  63. delete_obj.append(tb2)
  64. for _obj in delete_obj:
  65. if _obj in textbox_list:
  66. textbox_list.remove(_obj)
  67. return textbox_list
  68. logging.info("into image_preprocess")
  69. try:
  70. # 图片倾斜校正,写入原来的图片路径
  71. print("image_process", image_path)
  72. g_r_i = get_rotated_image(image_np, image_path)
  73. if g_r_i == [-1]:
  74. return [-1]
  75. # otr需要图片resize, 写入另一个路径
  76. image_np = cv2.imread(image_path)
  77. if image_np is None:
  78. return []
  79. best_h, best_w = get_best_predict_size(image_np)
  80. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  81. # image_resize_path = image_path[:-4] + "_resize" + image_path[-4:]
  82. image_resize_path = image_path.split(".")[0] + "_resize." + image_path.split(".")[-1]
  83. cv2.imwrite(image_resize_path, image_resize)
  84. # 调用otr模型接口
  85. with open(image_resize_path, "rb") as f:
  86. image_bytes = f.read()
  87. list_line = from_otr_interface(image_bytes, is_from_pdf)
  88. if judge_error_code(list_line):
  89. return list_line
  90. # 将resize后得到的bbox根据比例还原
  91. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  92. for i in range(len(list_line)):
  93. point = list_line[i]
  94. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  95. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  96. # 调用ocr模型接口
  97. with open(image_path, "rb") as f:
  98. image_bytes = f.read()
  99. text_list, bbox_list = from_ocr_interface(image_bytes, True)
  100. # print("convert_image", text_list)
  101. if judge_error_code(text_list):
  102. return text_list
  103. # 对文字框的y进行聚类
  104. text_list, bbox_list = get_cluster(text_list, bbox_list, 0)
  105. # text_list, bbox_list = get_cluster(text_list, bbox_list, 1)
  106. text_list, bbox_list = get_cluster(text_list, bbox_list, 2)
  107. # text_list, bbox_list = get_cluster(text_list, bbox_list, 3)
  108. # 调用现成方法形成表格
  109. try:
  110. from format_convert.convert_tree import TableLine
  111. list_lines = []
  112. for line in list_line:
  113. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  114. from format_convert.convert_tree import TextBox
  115. list_text_boxes = []
  116. for i in range(len(bbox_list)):
  117. bbox = bbox_list[i]
  118. b_text = text_list[i]
  119. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  120. bbox[2][0], bbox[2][1]], b_text))
  121. lt = LineTable()
  122. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  123. # 合并同一行textbox
  124. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  125. obj_list = []
  126. for table in tables:
  127. obj_list.append(_Table(table["table"], table["bbox"]))
  128. for text_box in list_text_boxes:
  129. if text_box not in obj_in_table:
  130. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  131. return obj_list
  132. except:
  133. traceback.print_exc()
  134. return [-8]
  135. except Exception as e:
  136. logging.info("image_preprocess error")
  137. print("image_preprocess", traceback.print_exc())
  138. return [-1]
  139. @get_memory_info.memory_decorator
  140. def picture2text(path, html=False):
  141. logging.info("into picture2text")
  142. try:
  143. # 判断图片中表格
  144. img = cv2.imread(path)
  145. if img is None:
  146. return [-3]
  147. text = image_process(img, path)
  148. if judge_error_code(text):
  149. return text
  150. if html:
  151. text = add_div(text)
  152. return [text]
  153. except Exception as e:
  154. logging.info("picture2text error!")
  155. print("picture2text", traceback.print_exc())
  156. return [-1]
  157. def get_best_predict_size(image_np, times=64):
  158. sizes = []
  159. for i in range(1, 100):
  160. if i*times <= 1300:
  161. sizes.append(i*times)
  162. sizes.sort(key=lambda x: x, reverse=True)
  163. min_len = 10000
  164. best_height = sizes[0]
  165. for height in sizes:
  166. if abs(image_np.shape[0] - height) < min_len:
  167. min_len = abs(image_np.shape[0] - height)
  168. best_height = height
  169. min_len = 10000
  170. best_width = sizes[0]
  171. for width in sizes:
  172. if abs(image_np.shape[1] - width) < min_len:
  173. min_len = abs(image_np.shape[1] - width)
  174. best_width = width
  175. return best_height, best_width
  176. class ImageConvert:
  177. def __init__(self, path, unique_type_dir):
  178. from format_convert.convert_tree import _Document
  179. self._doc = _Document(path)
  180. self.path = path
  181. self.unique_type_dir = unique_type_dir
  182. def init_package(self):
  183. # 各个包初始化
  184. try:
  185. with open(self.path, "rb") as f:
  186. self.image = f.read()
  187. except:
  188. logging.info("cannot open image!")
  189. traceback.print_exc()
  190. self._doc.error_code = [-3]
  191. def convert(self):
  192. from format_convert.convert_tree import _Page, _Image
  193. self.init_package()
  194. if self._doc.error_code is not None:
  195. return
  196. _page = _Page(None, 0)
  197. _image = _Image(self.image, self.path)
  198. _page.add_child(_image)
  199. self._doc.add_child(_page)
  200. def get_html(self):
  201. try:
  202. self.convert()
  203. except:
  204. traceback.print_exc()
  205. self._doc.error_code = [-1]
  206. if self._doc.error_code is not None:
  207. return self._doc.error_code
  208. return self._doc.get_html()