convert_image.py 15 KB

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