convert_image.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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, 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)
  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. if judge_error_code(text_list):
  101. return text_list
  102. # 对文字框的y进行聚类
  103. text_list, bbox_list = get_cluster(text_list, bbox_list, 0)
  104. # text_list, bbox_list = get_cluster(text_list, bbox_list, 1)
  105. text_list, bbox_list = get_cluster(text_list, bbox_list, 2)
  106. # text_list, bbox_list = get_cluster(text_list, bbox_list, 3)
  107. # 调用现成方法形成表格
  108. try:
  109. from format_convert.convert_tree import TableLine
  110. list_lines = []
  111. for line in list_line:
  112. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  113. from format_convert.convert_tree import TextBox
  114. list_text_boxes = []
  115. for i in range(len(bbox_list)):
  116. bbox = bbox_list[i]
  117. b_text = text_list[i]
  118. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  119. bbox[2][0], bbox[2][1]], b_text))
  120. lt = LineTable()
  121. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  122. # 合并同一行textbox
  123. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  124. obj_list = []
  125. for table in tables:
  126. obj_list.append(_Table(table["table"], table["bbox"]))
  127. for text_box in list_text_boxes:
  128. if text_box not in obj_in_table:
  129. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  130. return obj_list
  131. except:
  132. traceback.print_exc()
  133. return [-8]
  134. except Exception as e:
  135. logging.info("image_preprocess error")
  136. print("image_preprocess", traceback.print_exc())
  137. return [-1]
  138. @get_memory_info.memory_decorator
  139. def picture2text(path, html=False):
  140. logging.info("into picture2text")
  141. try:
  142. # 判断图片中表格
  143. img = cv2.imread(path)
  144. if img is None:
  145. return [-3]
  146. text = image_process(img, path)
  147. if judge_error_code(text):
  148. return text
  149. if html:
  150. text = add_div(text)
  151. return [text]
  152. except Exception as e:
  153. logging.info("picture2text error!")
  154. print("picture2text", traceback.print_exc())
  155. return [-1]
  156. def get_best_predict_size(image_np, times=64):
  157. sizes = []
  158. for i in range(1, 100):
  159. if i*times <= 3000:
  160. sizes.append(i*times)
  161. sizes.sort(key=lambda x: x, reverse=True)
  162. min_len = 10000
  163. best_height = sizes[0]
  164. for height in sizes:
  165. if abs(image_np.shape[0] - height) < min_len:
  166. min_len = abs(image_np.shape[0] - height)
  167. best_height = height
  168. min_len = 10000
  169. best_width = sizes[0]
  170. for width in sizes:
  171. if abs(image_np.shape[1] - width) < min_len:
  172. min_len = abs(image_np.shape[1] - width)
  173. best_width = width
  174. return best_height, best_width
  175. class ImageConvert:
  176. def __init__(self, path, unique_type_dir):
  177. from format_convert.convert_tree import _Document
  178. self._doc = _Document(path)
  179. self.path = path
  180. self.unique_type_dir = unique_type_dir
  181. def init_package(self):
  182. # 各个包初始化
  183. try:
  184. with open(self.path, "rb") as f:
  185. self.image = f.read()
  186. except:
  187. logging.info("cannot open image!")
  188. traceback.print_exc()
  189. self._doc.error_code = [-3]
  190. def convert(self):
  191. from format_convert.convert_tree import _Page, _Image
  192. self.init_package()
  193. if self._doc.error_code is not None:
  194. return
  195. _page = _Page(None, 0)
  196. _image = _Image(self.image, self.path)
  197. _page.add_child(_image)
  198. self._doc.add_child(_page)
  199. def get_html(self):
  200. try:
  201. self.convert()
  202. except:
  203. traceback.print_exc()
  204. self._doc.error_code = [-1]
  205. if self._doc.error_code is not None:
  206. return self._doc.error_code
  207. return self._doc.get_html()