convert_image.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. # encoding=utf8
  2. import inspect
  3. import io
  4. import logging
  5. import os
  6. import sys
  7. import time
  8. import requests
  9. import numpy as np
  10. from PIL import Image
  11. sys.path.append(os.path.dirname(__file__) + "/../")
  12. from pdfminer.layout import LTLine
  13. import traceback
  14. import cv2
  15. from isr.pre_process import count_red_pixel
  16. from format_convert.utils import judge_error_code, add_div, LineTable, get_table_html, get_logger, log, \
  17. memory_decorator, pil_resize
  18. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface, from_gpu_interface_redis, \
  19. from_idc_interface, from_isr_interface
  20. from format_convert.table_correct import get_rotated_image
  21. def image_process(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  22. from format_convert.convert_tree import _Table, _Sentence
  23. def get_cluster(t_list, b_list, axis):
  24. zip_list = list(zip(t_list, b_list))
  25. if len(zip_list) == 0:
  26. return t_list, b_list
  27. if len(zip_list[0]) > 0:
  28. zip_list.sort(key=lambda x: x[1][axis][1])
  29. cluster_list = []
  30. margin = 5
  31. for text, bbox in zip_list:
  32. _find = 0
  33. for cluster in cluster_list:
  34. if abs(cluster[1] - bbox[axis][1]) <= margin:
  35. cluster[0].append([text, bbox])
  36. cluster[1] = bbox[axis][1]
  37. _find = 1
  38. break
  39. if not _find:
  40. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  41. new_text_list = []
  42. new_bbox_list = []
  43. for cluster in cluster_list:
  44. # print("=============convert_image")
  45. # print("cluster_list", cluster)
  46. center_y = 0
  47. for text, bbox in cluster[0]:
  48. center_y += bbox[axis][1]
  49. center_y = int(center_y / len(cluster[0]))
  50. for text, bbox in cluster[0]:
  51. bbox[axis][1] = center_y
  52. new_text_list.append(text)
  53. new_bbox_list.append(bbox)
  54. # print("cluster_list", cluster)
  55. return new_text_list, new_bbox_list
  56. def merge_textbox(textbox_list, in_objs):
  57. delete_obj = []
  58. threshold = 5
  59. textbox_list.sort(key=lambda x:x.bbox[0])
  60. for k in range(len(textbox_list)):
  61. tb1 = textbox_list[k]
  62. if tb1 not in in_objs and tb1 not in delete_obj:
  63. for m in range(k+1, len(textbox_list)):
  64. tb2 = textbox_list[m]
  65. if tb2 in in_objs:
  66. continue
  67. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  68. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  69. if tb1.bbox[0] <= tb2.bbox[0]:
  70. tb1.text = tb1.text + tb2.text
  71. else:
  72. tb1.text = tb2.text + tb1.text
  73. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  74. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  75. delete_obj.append(tb2)
  76. for _obj in delete_obj:
  77. if _obj in textbox_list:
  78. textbox_list.remove(_obj)
  79. return textbox_list
  80. log("into image_preprocess")
  81. try:
  82. # 图片倾斜校正,写入原来的图片路径
  83. # print("image_process", image_path)
  84. g_r_i = get_rotated_image(image_np, image_path)
  85. if judge_error_code(g_r_i):
  86. if is_from_docx:
  87. return []
  88. else:
  89. return g_r_i
  90. image_np = cv2.imread(image_path)
  91. if image_np is None:
  92. return []
  93. # if image_np is None:
  94. # return []
  95. #
  96. # # idc模型实现图片倾斜校正
  97. # image_resize = pil_resize(image_np, 640, 640)
  98. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  99. # cv2.imwrite(image_resize_path, image_resize)
  100. #
  101. # with open(image_resize_path, "rb") as f:
  102. # image_bytes = f.read()
  103. # angle = from_idc_interface(image_bytes)
  104. # if judge_error_code(angle):
  105. # if is_from_docx:
  106. # return []
  107. # else:
  108. # return angle
  109. # # 根据角度旋转
  110. # image_pil = Image.fromarray(image_np)
  111. # image_np = np.array(image_pil.rotate(angle, expand=1))
  112. # # 写入
  113. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  114. # cv2.imwrite(idc_path, image_np)
  115. # isr模型去除印章
  116. if count_red_pixel(image_np):
  117. # 红色像素达到一定值才过模型
  118. with open(image_path, "rb") as f:
  119. image_bytes = f.read()
  120. image_np = from_isr_interface(image_bytes)
  121. if judge_error_code(image_np):
  122. if is_from_docx:
  123. return []
  124. else:
  125. return image_np
  126. # [1]代表检测不到印章,直接返回
  127. if isinstance(image_np, list) and image_np == [1]:
  128. log("no seals detected!")
  129. else:
  130. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  131. cv2.imwrite(isr_path, image_np)
  132. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  133. best_h, best_w = get_best_predict_size(image_np)
  134. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  135. image_resize = pil_resize(image_np, best_h, best_w)
  136. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  137. cv2.imwrite(image_resize_path, image_resize)
  138. # 调用otr模型接口
  139. with open(image_resize_path, "rb") as f:
  140. image_bytes = f.read()
  141. list_line = from_otr_interface(image_bytes, is_from_pdf)
  142. if judge_error_code(list_line):
  143. return list_line
  144. # # 预处理
  145. # if is_from_pdf:
  146. # prob = 0.2
  147. # else:
  148. # prob = 0.5
  149. # with open(image_resize_path, "rb") as f:
  150. # image_bytes = f.read()
  151. # img_new, inputs = table_preprocess(image_bytes, prob)
  152. # if type(img_new) is list and judge_error_code(img_new):
  153. # return img_new
  154. # log("img_new.shape " + str(img_new.shape))
  155. #
  156. # # 调用模型运行接口
  157. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  158. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  159. # if judge_error_code(result):
  160. # logging.error("from_gpu_interface failed! " + str(result))
  161. # raise requests.exceptions.RequestException
  162. #
  163. # pred = result.get("preds")
  164. # gpu_time = result.get("gpu_time")
  165. # log("otr model predict time " + str(gpu_time))
  166. #
  167. # # # 解压numpy
  168. # # decompressed_array = io.BytesIO()
  169. # # decompressed_array.write(pred)
  170. # # decompressed_array.seek(0)
  171. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  172. # # log("inputs.shape" + str(pred.shape))
  173. #
  174. # 调用gpu共享内存处理
  175. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  176. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  177. # if judge_error_code(result):
  178. # logging.error("from_gpu_interface failed! " + str(result))
  179. # raise requests.exceptions.RequestException
  180. #
  181. # pred = result.get("preds")
  182. # gpu_time = result.get("gpu_time")
  183. # log("otr model predict time " + str(gpu_time))
  184. #
  185. # # 后处理
  186. # list_line = table_postprocess(img_new, pred, prob)
  187. # log("len(list_line) " + str(len(list_line)))
  188. # if judge_error_code(list_line):
  189. # return list_line
  190. # otr resize后得到的bbox根据比例还原
  191. start_time = time.time()
  192. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  193. for i in range(len(list_line)):
  194. point = list_line[i]
  195. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  196. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  197. log("otr resize bbox recover " + str(time.time()-start_time))
  198. # ocr图片过大内存溢出,需resize
  199. start_time = time.time()
  200. threshold = 3000
  201. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  202. best_h, best_w = get_best_predict_size2(image_np, threshold)
  203. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  204. image_resize = pil_resize(image_np, best_h, best_w)
  205. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  206. cv2.imwrite(image_resize_path, image_resize)
  207. log("ocr resize before " + str(time.time()-start_time))
  208. # 调用ocr模型接口
  209. with open(image_resize_path, "rb") as f:
  210. image_bytes = f.read()
  211. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  212. if judge_error_code(text_list):
  213. return text_list
  214. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  215. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  216. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  217. # # 循环每张图片识别结果
  218. # text_list = []
  219. # bbox_list = []
  220. # for line in results:
  221. # # print("ocr_interface line", line)
  222. # text_list.append(line[-1][0])
  223. # bbox_list.append(line[0])
  224. # if len(text_list) == 0:
  225. # return []
  226. # ocr resize后的bbox还原
  227. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  228. for i in range(len(bbox_list)):
  229. point = bbox_list[i]
  230. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  231. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  232. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  233. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  234. # for _a,_b in zip(text_list,bbox_list):
  235. # print("bbox1",_a,_b)
  236. # 调用现成方法形成表格
  237. try:
  238. from format_convert.convert_tree import TableLine
  239. list_lines = []
  240. for line in list_line:
  241. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  242. from format_convert.convert_tree import TextBox
  243. list_text_boxes = []
  244. for i in range(len(bbox_list)):
  245. bbox = bbox_list[i]
  246. b_text = text_list[i]
  247. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  248. bbox[2][0], bbox[2][1]], b_text))
  249. # for _textbox in list_text_boxes:
  250. # print("==",_textbox.get_text())
  251. lt = LineTable()
  252. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  253. # 合并同一行textbox
  254. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  255. obj_list = []
  256. for table in tables:
  257. obj_list.append(_Table(table["table"], table["bbox"]))
  258. for text_box in list_text_boxes:
  259. if text_box not in obj_in_table:
  260. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  261. return obj_list
  262. except:
  263. traceback.print_exc()
  264. return [-8]
  265. except Exception as e:
  266. log("image_preprocess error")
  267. traceback.print_exc()
  268. return [-1]
  269. @memory_decorator
  270. def picture2text(path, html=False):
  271. log("into picture2text")
  272. try:
  273. # 判断图片中表格
  274. img = cv2.imread(path)
  275. if img is None:
  276. return [-3]
  277. text = image_process(img, path)
  278. if judge_error_code(text):
  279. return text
  280. if html:
  281. text = add_div(text)
  282. return [text]
  283. except Exception as e:
  284. log("picture2text error!")
  285. print("picture2text", traceback.print_exc())
  286. return [-1]
  287. def get_best_predict_size(image_np, times=64):
  288. sizes = []
  289. for i in range(1, 100):
  290. if i*times <= 1300:
  291. sizes.append(i*times)
  292. sizes.sort(key=lambda x: x, reverse=True)
  293. min_len = 10000
  294. best_height = sizes[0]
  295. for height in sizes:
  296. if abs(image_np.shape[0] - height) < min_len:
  297. min_len = abs(image_np.shape[0] - height)
  298. best_height = height
  299. min_len = 10000
  300. best_width = sizes[0]
  301. for width in sizes:
  302. if abs(image_np.shape[1] - width) < min_len:
  303. min_len = abs(image_np.shape[1] - width)
  304. best_width = width
  305. return best_height, best_width
  306. def get_best_predict_size2(image_np, threshold=3000):
  307. h, w = image_np.shape[:2]
  308. scale = threshold / max(h, w)
  309. h = int(h * scale)
  310. w = int(w * scale)
  311. return h, w
  312. class ImageConvert:
  313. def __init__(self, path, unique_type_dir):
  314. from format_convert.convert_tree import _Document
  315. self._doc = _Document(path)
  316. self.path = path
  317. self.unique_type_dir = unique_type_dir
  318. def init_package(self):
  319. # 各个包初始化
  320. try:
  321. with open(self.path, "rb") as f:
  322. self.image = f.read()
  323. except:
  324. log("cannot open image!")
  325. traceback.print_exc()
  326. self._doc.error_code = [-3]
  327. def convert(self):
  328. from format_convert.convert_tree import _Page, _Image
  329. self.init_package()
  330. if self._doc.error_code is not None:
  331. return
  332. _page = _Page(None, 0)
  333. _image = _Image(self.image, self.path)
  334. _page.add_child(_image)
  335. self._doc.add_child(_page)
  336. def get_html(self):
  337. try:
  338. self.convert()
  339. except:
  340. traceback.print_exc()
  341. self._doc.error_code = [-1]
  342. if self._doc.error_code is not None:
  343. return self._doc.error_code
  344. return self._doc.get_html()