convert_image.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. image_np_source = image_np
  117. _isr_time = time.time()
  118. if count_red_pixel(image_np):
  119. # 红色像素达到一定值才过模型
  120. with open(image_path, "rb") as f:
  121. image_bytes = f.read()
  122. image_np = from_isr_interface(image_bytes)
  123. if judge_error_code(image_np):
  124. if is_from_docx:
  125. return []
  126. else:
  127. return image_np
  128. # [1]代表检测不到印章,直接返回
  129. if isinstance(image_np, list) and image_np == [1]:
  130. log("no seals detected!")
  131. image_np = image_np_source
  132. else:
  133. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  134. cv2.imwrite(isr_path, image_np)
  135. log("isr total time"+str(time.time()-_isr_time))
  136. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  137. best_h, best_w = get_best_predict_size(image_np)
  138. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  139. image_resize = pil_resize(image_np, best_h, best_w)
  140. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  141. cv2.imwrite(image_resize_path, image_resize)
  142. # 调用otr模型接口
  143. with open(image_resize_path, "rb") as f:
  144. image_bytes = f.read()
  145. list_line = from_otr_interface(image_bytes, is_from_pdf)
  146. if judge_error_code(list_line):
  147. return list_line
  148. # # 预处理
  149. # if is_from_pdf:
  150. # prob = 0.2
  151. # else:
  152. # prob = 0.5
  153. # with open(image_resize_path, "rb") as f:
  154. # image_bytes = f.read()
  155. # img_new, inputs = table_preprocess(image_bytes, prob)
  156. # if type(img_new) is list and judge_error_code(img_new):
  157. # return img_new
  158. # log("img_new.shape " + str(img_new.shape))
  159. #
  160. # # 调用模型运行接口
  161. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  162. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  163. # if judge_error_code(result):
  164. # logging.error("from_gpu_interface failed! " + str(result))
  165. # raise requests.exceptions.RequestException
  166. #
  167. # pred = result.get("preds")
  168. # gpu_time = result.get("gpu_time")
  169. # log("otr model predict time " + str(gpu_time))
  170. #
  171. # # # 解压numpy
  172. # # decompressed_array = io.BytesIO()
  173. # # decompressed_array.write(pred)
  174. # # decompressed_array.seek(0)
  175. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  176. # # log("inputs.shape" + str(pred.shape))
  177. #
  178. # 调用gpu共享内存处理
  179. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  180. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  181. # if judge_error_code(result):
  182. # logging.error("from_gpu_interface failed! " + str(result))
  183. # raise requests.exceptions.RequestException
  184. #
  185. # pred = result.get("preds")
  186. # gpu_time = result.get("gpu_time")
  187. # log("otr model predict time " + str(gpu_time))
  188. #
  189. # # 后处理
  190. # list_line = table_postprocess(img_new, pred, prob)
  191. # log("len(list_line) " + str(len(list_line)))
  192. # if judge_error_code(list_line):
  193. # return list_line
  194. # otr resize后得到的bbox根据比例还原
  195. start_time = time.time()
  196. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  197. for i in range(len(list_line)):
  198. point = list_line[i]
  199. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  200. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  201. log("otr resize bbox recover " + str(time.time()-start_time))
  202. # ocr图片过大内存溢出,需resize
  203. start_time = time.time()
  204. threshold = 3000
  205. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  206. best_h, best_w = get_best_predict_size2(image_np, threshold)
  207. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  208. image_resize = pil_resize(image_np, best_h, best_w)
  209. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  210. cv2.imwrite(image_resize_path, image_resize)
  211. log("ocr resize before " + str(time.time()-start_time))
  212. # 调用ocr模型接口
  213. with open(image_resize_path, "rb") as f:
  214. image_bytes = f.read()
  215. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  216. if judge_error_code(text_list):
  217. return text_list
  218. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  219. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  220. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  221. # # 循环每张图片识别结果
  222. # text_list = []
  223. # bbox_list = []
  224. # for line in results:
  225. # # print("ocr_interface line", line)
  226. # text_list.append(line[-1][0])
  227. # bbox_list.append(line[0])
  228. # if len(text_list) == 0:
  229. # return []
  230. # ocr resize后的bbox还原
  231. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  232. for i in range(len(bbox_list)):
  233. point = bbox_list[i]
  234. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  235. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  236. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  237. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  238. # for _a,_b in zip(text_list,bbox_list):
  239. # print("bbox1",_a,_b)
  240. # 调用现成方法形成表格
  241. try:
  242. from format_convert.convert_tree import TableLine
  243. list_lines = []
  244. for line in list_line:
  245. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  246. from format_convert.convert_tree import TextBox
  247. list_text_boxes = []
  248. for i in range(len(bbox_list)):
  249. bbox = bbox_list[i]
  250. b_text = text_list[i]
  251. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  252. bbox[2][0], bbox[2][1]], b_text))
  253. # for _textbox in list_text_boxes:
  254. # print("==",_textbox.get_text())
  255. lt = LineTable()
  256. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  257. # 合并同一行textbox
  258. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  259. obj_list = []
  260. for table in tables:
  261. obj_list.append(_Table(table["table"], table["bbox"]))
  262. for text_box in list_text_boxes:
  263. if text_box not in obj_in_table:
  264. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  265. return obj_list
  266. except:
  267. traceback.print_exc()
  268. return [-8]
  269. except Exception as e:
  270. log("image_preprocess error")
  271. traceback.print_exc()
  272. return [-1]
  273. @memory_decorator
  274. def picture2text(path, html=False):
  275. log("into picture2text")
  276. try:
  277. # 判断图片中表格
  278. img = cv2.imread(path)
  279. if img is None:
  280. return [-3]
  281. text = image_process(img, path)
  282. if judge_error_code(text):
  283. return text
  284. if html:
  285. text = add_div(text)
  286. return [text]
  287. except Exception as e:
  288. log("picture2text error!")
  289. print("picture2text", traceback.print_exc())
  290. return [-1]
  291. def get_best_predict_size(image_np, times=64):
  292. sizes = []
  293. for i in range(1, 100):
  294. if i*times <= 1300:
  295. sizes.append(i*times)
  296. sizes.sort(key=lambda x: x, reverse=True)
  297. min_len = 10000
  298. best_height = sizes[0]
  299. for height in sizes:
  300. if abs(image_np.shape[0] - height) < min_len:
  301. min_len = abs(image_np.shape[0] - height)
  302. best_height = height
  303. min_len = 10000
  304. best_width = sizes[0]
  305. for width in sizes:
  306. if abs(image_np.shape[1] - width) < min_len:
  307. min_len = abs(image_np.shape[1] - width)
  308. best_width = width
  309. return best_height, best_width
  310. def get_best_predict_size2(image_np, threshold=3000):
  311. h, w = image_np.shape[:2]
  312. scale = threshold / max(h, w)
  313. h = int(h * scale)
  314. w = int(w * scale)
  315. return h, w
  316. class ImageConvert:
  317. def __init__(self, path, unique_type_dir):
  318. from format_convert.convert_tree import _Document
  319. self._doc = _Document(path)
  320. self.path = path
  321. self.unique_type_dir = unique_type_dir
  322. def init_package(self):
  323. # 各个包初始化
  324. try:
  325. with open(self.path, "rb") as f:
  326. self.image = f.read()
  327. except:
  328. log("cannot open image!")
  329. traceback.print_exc()
  330. self._doc.error_code = [-3]
  331. def convert(self):
  332. from format_convert.convert_tree import _Page, _Image
  333. self.init_package()
  334. if self._doc.error_code is not None:
  335. return
  336. _page = _Page(None, 0)
  337. _image = _Image(self.image, self.path)
  338. _page.add_child(_image)
  339. self._doc.add_child(_page)
  340. def get_html(self):
  341. try:
  342. self.convert()
  343. except:
  344. traceback.print_exc()
  345. self._doc.error_code = [-1]
  346. if self._doc.error_code is not None:
  347. return self._doc.error_code
  348. return self._doc.get_html()