convert_image.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  1. # encoding=utf8
  2. import copy
  3. import inspect
  4. import io
  5. import logging
  6. import os
  7. import re
  8. import sys
  9. import time
  10. from glob import glob
  11. import requests
  12. import numpy as np
  13. from PIL import Image
  14. sys.path.append(os.path.dirname(__file__) + "/../")
  15. from pdfminer.layout import LTLine
  16. import traceback
  17. import cv2
  18. from isr.pre_process import count_red_pixel
  19. from format_convert.utils import judge_error_code, add_div, LineTable, get_table_html, get_logger, log, \
  20. memory_decorator, pil_resize, np2bytes, ocr_cant_read, get_garble_code2, line_iou
  21. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface, from_gpu_interface_redis, \
  22. from_idc_interface, from_isr_interface
  23. from format_convert.table_correct import get_rotated_image
  24. from botr.extract_table import get_table
  25. def image_process(image_np, image_path, is_from_pdf=False, is_from_docx=False,
  26. b_table_from_text=False, pdf_obj_list=[], pdf_layout_size=()):
  27. from format_convert.convert_tree import _Table, _Sentence
  28. def get_cluster(t_list, b_list, axis):
  29. zip_list = list(zip(t_list, b_list))
  30. if len(zip_list) == 0:
  31. return t_list, b_list
  32. if len(zip_list[0]) > 0:
  33. zip_list.sort(key=lambda x: x[1][axis][1])
  34. cluster_list = []
  35. margin = 5
  36. for text, bbox in zip_list:
  37. _find = 0
  38. for cluster in cluster_list:
  39. if abs(cluster[1] - bbox[axis][1]) <= margin:
  40. cluster[0].append([text, bbox])
  41. cluster[1] = bbox[axis][1]
  42. _find = 1
  43. break
  44. if not _find:
  45. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  46. new_text_list = []
  47. new_bbox_list = []
  48. for cluster in cluster_list:
  49. # print("=============convert_image")
  50. # print("cluster_list", cluster)
  51. center_y = 0
  52. for text, bbox in cluster[0]:
  53. center_y += bbox[axis][1]
  54. center_y = int(center_y / len(cluster[0]))
  55. for text, bbox in cluster[0]:
  56. bbox[axis][1] = center_y
  57. new_text_list.append(text)
  58. new_bbox_list.append(bbox)
  59. # print("cluster_list", cluster)
  60. return new_text_list, new_bbox_list
  61. def merge_textbox(textbox_list, in_objs):
  62. delete_obj = []
  63. threshold = 5
  64. textbox_list.sort(key=lambda x:x.bbox[0])
  65. for k in range(len(textbox_list)):
  66. tb1 = textbox_list[k]
  67. if tb1 not in in_objs and tb1 not in delete_obj:
  68. for m in range(k+1, len(textbox_list)):
  69. tb2 = textbox_list[m]
  70. if tb2 in in_objs:
  71. continue
  72. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  73. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  74. if tb1.bbox[0] <= tb2.bbox[0]:
  75. tb1.text = tb1.text + tb2.text
  76. else:
  77. tb1.text = tb2.text + tb1.text
  78. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  79. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  80. delete_obj.append(tb2)
  81. for _obj in delete_obj:
  82. if _obj in textbox_list:
  83. textbox_list.remove(_obj)
  84. return textbox_list
  85. def idc_process(_image_np, return_angle=False):
  86. # 图片倾斜校正,写入原来的图片路径
  87. # print("image_process", image_path)
  88. # g_r_i = get_rotated_image(_image_np, image_path)
  89. # if judge_error_code(g_r_i):
  90. # if is_from_docx:
  91. # return []
  92. # else:
  93. # return g_r_i
  94. # _image_np = cv2.imread(image_path)
  95. # if _image_np is None:
  96. # return []
  97. # return _image_np
  98. # if _image_np is None:
  99. # return []
  100. # idc模型实现图片倾斜校正
  101. h, w = get_best_predict_size2(_image_np, 1080)
  102. image_resize = pil_resize(_image_np, h, w)
  103. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  104. # cv2.imwrite(image_resize_path, image_resize)
  105. # with open(image_resize_path, "rb") as f:
  106. # image_bytes = f.read()
  107. image_bytes = np2bytes(image_resize)
  108. angle = from_idc_interface(image_bytes)
  109. log('idc_process angle ' + str(angle))
  110. if judge_error_code(angle):
  111. if return_angle:
  112. if is_from_docx:
  113. return [], []
  114. else:
  115. return angle, angle
  116. else:
  117. if is_from_docx:
  118. return []
  119. else:
  120. return angle
  121. # 根据角度旋转
  122. _image_pil = Image.fromarray(_image_np)
  123. _image_np = np.array(_image_pil.rotate(angle, expand=1))
  124. # 写入
  125. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  126. # cv2.imwrite(idc_path, image_np)
  127. if return_angle:
  128. return _image_np, angle
  129. return _image_np
  130. def isr_process(_image_np):
  131. log("isr_process image shape " + str(_image_np.shape))
  132. image_np_copy = copy.deepcopy(_image_np)
  133. # isr模型去除印章
  134. _isr_time = time.time()
  135. if count_red_pixel(_image_np):
  136. # 红色像素达到一定值才过模型
  137. image_bytes = np2bytes(_image_np)
  138. _image_np = from_isr_interface(image_bytes)
  139. if judge_error_code(_image_np):
  140. if is_from_docx:
  141. return []
  142. else:
  143. return _image_np
  144. # [1]代表检测不到印章,直接返回
  145. if isinstance(_image_np, list) and _image_np == [1]:
  146. log("no seals detected!")
  147. _image_np = image_np_copy
  148. log("isr total time "+str(time.time()-_isr_time))
  149. return _image_np
  150. def ocr_process(_image_np, _threshold=2048):
  151. log("ocr_process image shape " + str(_image_np.shape))
  152. # ocr图片过大内存溢出,需resize
  153. # 大图按比例缩小,小图维持不变;若统一拉伸成固定大小如1024会爆显存
  154. ratio = (1, 1)
  155. if _image_np.shape[0] > _threshold or _image_np.shape[1] > _threshold:
  156. best_h, best_w = get_best_predict_size2(_image_np, _threshold)
  157. _image_np = pil_resize(_image_np, best_h, best_w)
  158. log("ocr_process image resize " + str(_image_np.shape))
  159. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  160. # 大图片ocr加锁,防止爆显存
  161. # if _image_np.shape[0] >= 1024 and _image_np.shape[1] >= 1024:
  162. # file_lock = True
  163. # else:
  164. # file_lock = False
  165. # 调用ocr模型接口
  166. image_bytes = np2bytes(_image_np)
  167. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=1)
  168. if judge_error_code(text_list):
  169. return text_list, text_list
  170. for i in range(len(bbox_list)):
  171. point = bbox_list[i]
  172. bbox_list[i] = [[int(point[0][0]*ratio[0]), int(point[0][1]*ratio[1])],
  173. [int(point[1][0]*ratio[0]), int(point[1][1]*ratio[1])],
  174. [int(point[2][0]*ratio[0]), int(point[2][1]*ratio[1])],
  175. [int(point[3][0]*ratio[0]), int(point[3][1]*ratio[1])]]
  176. # 去除水印字 根据识别是否为矩形框
  177. temp_text_list = []
  178. temp_bbox_list = []
  179. water_mark_dict = {}
  180. for i in range(len(bbox_list)):
  181. bbox = bbox_list[i]
  182. text = text_list[i]
  183. if len(re.findall('[\u4e00-\u9fa5]', text)) == len(text):
  184. if (abs(bbox[0][1] - bbox[1][1]) <= 2 and abs(bbox[2][1] - bbox[3][1]) <= 2) \
  185. or (abs(bbox[0][0] - bbox[3][0]) <= 4 and abs(bbox[2][0] - bbox[1][0]) <= 4):
  186. temp_text_list.append(text)
  187. temp_bbox_list.append(bbox)
  188. else:
  189. if text in water_mark_dict.keys():
  190. water_mark_dict[text] += [bbox]
  191. else:
  192. water_mark_dict[text] = [bbox]
  193. else:
  194. temp_text_list.append(text)
  195. temp_bbox_list.append(bbox)
  196. # 数量多的才算水印
  197. for text in water_mark_dict.keys():
  198. bbox_list = water_mark_dict.get(text)
  199. if len(bbox_list) < 3:
  200. for bbox in bbox_list:
  201. temp_text_list.append(text)
  202. temp_bbox_list.append(bbox)
  203. text_list = temp_text_list
  204. bbox_list = temp_bbox_list
  205. return text_list, bbox_list
  206. def otr_process(_image_np):
  207. log("otr_process image shape " + str(_image_np.shape))
  208. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  209. best_h, best_w = get_best_predict_size(_image_np)
  210. image_resize = pil_resize(_image_np, best_h, best_w)
  211. # image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  212. # cv2.imwrite(image_resize_path, image_resize)
  213. # 调用otr模型接口
  214. # with open(image_resize_path, "rb") as f:
  215. # image_bytes = f.read()
  216. image_bytes = np2bytes(image_resize)
  217. list_line = from_otr_interface(image_bytes, is_from_pdf)
  218. if judge_error_code(list_line):
  219. if is_from_docx:
  220. return []
  221. else:
  222. return list_line
  223. # otr resize后得到的bbox根据比例还原
  224. start_time = time.time()
  225. ratio = (_image_np.shape[0]/best_h, _image_np.shape[1]/best_w)
  226. for i in range(len(list_line)):
  227. point = list_line[i]
  228. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  229. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  230. log("otr resize bbox recover " + str(time.time()-start_time))
  231. return list_line
  232. def botr_process(_image_np, table_list2, text_list2, box_list2, text_box_list2, obj_in_table_list2,
  233. from_pdf=False, pdf_obj_list=[], pdf_layout_size=()):
  234. if from_pdf:
  235. # 交叉验证 ocr结果与pdf obj,暂时使用pdf提取的
  236. h_ratio = _image_np.shape[0] / pdf_layout_size[1]
  237. w_ratio = _image_np.shape[1] / pdf_layout_size[0]
  238. pdf_text_list = []
  239. pdf_box_list = []
  240. for obj in pdf_obj_list:
  241. # pdf坐标是上下颠倒的
  242. obj.bbox = (obj.bbox[0], pdf_layout_size[1]-obj.bbox[1],
  243. obj.bbox[2], pdf_layout_size[1]-obj.bbox[3])
  244. # 根据两个页面大小比例调整坐标
  245. obj.bbox = (obj.bbox[0]*w_ratio, obj.bbox[1]*h_ratio,
  246. obj.bbox[2]*w_ratio, obj.bbox[3]*h_ratio)
  247. # 剔除水印字
  248. text = re.sub('[\n ]', '', obj.get_text())
  249. if len(text) == 1 and abs(obj.bbox[0] - obj.bbox[2]) >= 70:
  250. continue
  251. pdf_box_list.append([[int(obj.bbox[0]), int(obj.bbox[3])],
  252. [],
  253. [int(obj.bbox[2]), int(obj.bbox[1])],
  254. []
  255. ])
  256. pdf_text_list.append(re.sub('[\n]', '', obj.get_text()))
  257. pdf_text_box_list = get_text_box_obj(pdf_text_list, pdf_box_list)
  258. text_list2 = pdf_text_list
  259. box_list2 = pdf_box_list
  260. text_box_list2 = pdf_text_box_list
  261. _text_box_list, _table_list, _obj_in_table_list = get_table(_image_np, table_list2, text_list2, box_list2, text_box_list2)
  262. # 保存无边框表格文件
  263. if _table_list:
  264. try:
  265. save_b_table(_image_np, text_box_list2, from_pdf)
  266. except:
  267. pass
  268. # print('_text_box_list', _text_box_list)
  269. # print('_table_list', _table_list)
  270. if from_pdf:
  271. text_box_list2 = []
  272. table_list2 = []
  273. if _table_list and _text_box_list:
  274. text_box_list2 += _text_box_list
  275. text_box_list2 = list(set(text_box_list2))
  276. # table_list2 += _table_list
  277. # obj_in_table_list2 = obj_in_table_list2.union(_obj_in_table_list)
  278. return text_box_list2, _table_list, _obj_in_table_list
  279. def table_process(list_line, list_text_boxes, _image_np):
  280. # 调用现成方法形成表格
  281. try:
  282. if list_line:
  283. # 排除掉短且经过文字bbox中间的竖线
  284. temp_list = []
  285. for line in list_line:
  286. find_cnt = 0
  287. if abs(line[0]-line[2]) < abs(line[1]-line[3]) and abs(line[1] - line[3]) <= _image_np.shape[0] / 20:
  288. for t_obj in list_text_boxes:
  289. # if not (t_obj.bbox[1] <= line[1] <= t_obj.bbox[3] or t_obj.bbox[1] <= line[3] <= t_obj.bbox[3]):
  290. # continue
  291. if line_iou([[t_obj.bbox[1], 0], [t_obj.bbox[3], 0]], [[line[1], 0], [line[3], 0]]) < 0.3:
  292. continue
  293. if abs(t_obj.bbox[0]-t_obj.bbox[2])/5 + min(t_obj.bbox[0], t_obj.bbox[2]) <= line[0] <= abs(t_obj.bbox[0]-t_obj.bbox[2])/5*4 + min(t_obj.bbox[0], t_obj.bbox[2]) and (t_obj.bbox[0]-t_obj.bbox[2]) <= 60:
  294. # print('match', line[0], t_obj.bbox[0], t_obj.bbox[2], t_obj.get_text())
  295. find_cnt += 1
  296. if find_cnt >= 2:
  297. break
  298. if find_cnt >= 2:
  299. continue
  300. temp_list.append(line)
  301. list_line = temp_list
  302. from format_convert.convert_tree import TableLine
  303. list_lines = []
  304. for line in list_line:
  305. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  306. lt = LineTable()
  307. tables, obj_in_table, _, connect_textbox_list = lt.recognize_table(list_text_boxes, list_lines,
  308. sourceP_LB=False, splited=False,
  309. from_pdf=is_from_pdf)
  310. # 需分割textbox
  311. if connect_textbox_list:
  312. list_text_boxes = table_textbox_split(_image_np, connect_textbox_list, list_text_boxes)
  313. # 新的textbox,重新做表格
  314. tables, obj_in_table, _, connect_textbox_list = lt.recognize_table(list_text_boxes, list_lines,
  315. sourceP_LB=False, splited=True,
  316. from_pdf=is_from_pdf)
  317. if not tables:
  318. return list_text_boxes, tables, obj_in_table
  319. return list_text_boxes, tables, obj_in_table
  320. else:
  321. return list_text_boxes, [], set()
  322. except:
  323. traceback.print_exc()
  324. return [-8], [-8], [-8]
  325. def get_text_box_obj(_text_list, _bbox_list):
  326. from format_convert.convert_tree import TextBox
  327. _text_box_list = []
  328. for i in range(len(_bbox_list)):
  329. bbox = _bbox_list[i]
  330. b_text = _text_list[i]
  331. _text_box_list.append(TextBox([bbox[0][0], bbox[0][1],
  332. bbox[2][0], bbox[2][1]], b_text))
  333. return _text_box_list
  334. def save_b_table(image_np2, text_box_list2, from_pdf=False):
  335. _start_time = time.time()
  336. _path = '/data/fangjiasheng/format_conversion_maxcompute/save_b_table'
  337. # _path = 'D:/Project/format_conversion_maxcompute/save_b_table'
  338. max_index = 20000
  339. if os.path.exists(_path):
  340. file_list = glob(_path + '/*')
  341. if file_list:
  342. file_index_list = [int(re.split('[/.\\\\-]', x)[-3]) for x in file_list]
  343. file_index_list.sort(key=lambda x: x)
  344. index = file_index_list[-1] + 1
  345. else:
  346. index = 0
  347. if index > max_index:
  348. return
  349. # 文件md5
  350. from format_convert import _global
  351. _md5 = _global.get("md5")
  352. _image_path = _path + '/' + str(index) + '-' + str(_md5) + '.png'
  353. cv2.imwrite(_image_path, image_np2)
  354. log('save b_table image success!')
  355. # if from_pdf:
  356. # _file_path = _path + '/' + str(_md5) + '-' + str(index) + '.txt'
  357. # new_text_box_list2 = [str(x) + '\n' for x in text_box_list2]
  358. # with open(_file_path, 'w') as f:
  359. # f.writelines(new_text_box_list2)
  360. # log('save b_table txt success!')
  361. log('save_b_table cost: ' + str(time.time()-_start_time))
  362. def table_textbox_split(image_np2, connect_textbox_list, textbox_list):
  363. """
  364. 两个单元格里的文本被ocr识别为一个,需分开才能准确放进表格
  365. :return:
  366. """
  367. split_bbox_list = []
  368. split_text_list = []
  369. splited_textbox_list = []
  370. for textbox in connect_textbox_list:
  371. bbox = textbox.bbox
  372. bbox = [[bbox[0], bbox[1]], [], [bbox[2], bbox[3]], []]
  373. sub_image_np = image_np2[int(bbox[0][1]):int(bbox[2][1]), int(bbox[0][0]):int(bbox[2][0]), :]
  374. split_index_list = []
  375. # 从左到右遍历img
  376. for i in range(5, sub_image_np.shape[1]-5):
  377. # 找表格分割线,这一列都为黑色像素
  378. if np.where(sub_image_np[:, i, 0] < 200)[0].size >= sub_image_np.shape[0]:
  379. split_index_list.append(i)
  380. # 判断两线之间宽度,去重
  381. if len(split_index_list) > 1:
  382. last_index = split_index_list[0]
  383. temp_list = []
  384. delete_list = []
  385. for index in split_index_list[1:]:
  386. if index in delete_list:
  387. continue
  388. if index - last_index <= 5:
  389. delete_list.append(index)
  390. else:
  391. last_index = index
  392. temp_list.append(last_index)
  393. split_index_list = temp_list
  394. # n条以上分割线,有问题
  395. if len(split_index_list) == 0 or len(split_index_list) >= 2:
  396. # print('len(split_index_list)', len(split_index_list), split_index_list)
  397. continue
  398. else:
  399. # 根据index拆开图片,重新ocr
  400. split_index_list.insert(0, 0)
  401. print('split_index_list1', split_index_list)
  402. for _i, index in enumerate(split_index_list):
  403. if _i == len(split_index_list) - 1:
  404. split_image_np = sub_image_np[:, index:, :]
  405. split_bbox_list.append([[bbox[0][0]+index, bbox[0][1]], [], [bbox[2][0], bbox[2][1]], []])
  406. else:
  407. next_index = split_index_list[_i+1]
  408. split_image_np = sub_image_np[:, index:next_index, :]
  409. split_bbox_list.append([[bbox[0][0]+index, bbox[0][1]], [], [bbox[0][0]+next_index, bbox[2][1]], []])
  410. # ocr
  411. split_image_bytes = np2bytes(split_image_np)
  412. text_list2, bbox_list2 = from_ocr_interface(split_image_bytes, is_table=1, only_rec=1)
  413. # print('text_list2', text_list2)
  414. # print('bbox_list2', split_bbox_list)
  415. if judge_error_code(text_list2):
  416. text2 = ''
  417. else:
  418. if text_list2:
  419. text2 = text_list2[0]
  420. else:
  421. text2 = ''
  422. split_text_list.append(text2)
  423. splited_textbox_list.append(textbox)
  424. if split_text_list and split_bbox_list:
  425. split_textbox_list = get_text_box_obj(split_text_list, split_bbox_list)
  426. for tb in splited_textbox_list:
  427. if tb in textbox_list:
  428. textbox_list.remove(tb)
  429. textbox_list += split_textbox_list
  430. return textbox_list
  431. log("into image_preprocess")
  432. try:
  433. if image_np is None:
  434. log("image_preprocess image_np is None")
  435. return []
  436. if image_np.shape[0] <= 20 or image_np.shape[1] <= 20:
  437. log('image_np.shape[0] <= 20 or image_np.shape[1] <= 20')
  438. return []
  439. if not b_table_from_text:
  440. # 判断是否需要长图分割
  441. slice_flag = need_image_slice(image_np)
  442. log("need_image_slice " + str(slice_flag) + " " + str(image_np.shape))
  443. idc_flag = False
  444. image_np_list = [image_np]
  445. if slice_flag:
  446. # 方向分类
  447. image_np = idc_process(image_np)
  448. idc_flag = True
  449. if isinstance(image_np, list):
  450. return image_np
  451. # 再判断
  452. if need_image_slice(image_np):
  453. # 长图分割
  454. image_np_list = image_slice_new(image_np)
  455. if len(image_np_list) < 1:
  456. log("image_slice failed!")
  457. image_np_list = [image_np]
  458. # return [-10]
  459. all_obj_list = []
  460. _add_y = 0
  461. for image_np in image_np_list:
  462. # print("sub image shape", image_np.shape)
  463. # 整体分辨率限制
  464. threshold = 2048
  465. if image_np.shape[0] > threshold or image_np.shape[1] > threshold:
  466. h, w = get_best_predict_size2(image_np, threshold=threshold)
  467. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  468. image_np = pil_resize(image_np, h, w)
  469. # 印章去除
  470. image_np = isr_process(image_np)
  471. if isinstance(image_np, list):
  472. return image_np
  473. # 文字识别
  474. text_list, box_list = ocr_process(image_np)
  475. # print('text_list', text_list)
  476. if judge_error_code(text_list):
  477. return text_list
  478. # 判断ocr识别是否正确
  479. if ocr_cant_read(text_list, box_list) and not idc_flag:
  480. # if True:
  481. # 方向分类
  482. image_np, angle = idc_process(image_np, return_angle=True)
  483. if isinstance(image_np, list):
  484. return image_np
  485. # 如果角度不变,旋转180
  486. if angle in [0, 360]:
  487. image_pil = Image.fromarray(image_np)
  488. image_np = np.array(image_pil.rotate(180, expand=1))
  489. # cv2.imshow("idc_process", image_np)
  490. # cv2.waitKey(0)
  491. # 文字识别
  492. text_list1, box_list_1 = ocr_process(image_np)
  493. if judge_error_code(text_list1):
  494. return text_list1
  495. # all_text = ''.join(text_list1)
  496. # all_text = re.sub('[\s\d]', '', all_text)
  497. # if len(re.findall(get_garble_code2(), all_text)) >= 2:
  498. # log('text_list1' + ''.join(text_list1))
  499. if len(text_list1) > 0 and ocr_cant_read(text_list1, box_list_1) and is_from_pdf:
  500. return [-16]
  501. # 比较字数
  502. # print("ocr process", len("".join(text_list)), len("".join(text_list1)))
  503. if len("".join(text_list)) < len("".join(text_list1)):
  504. text_list = text_list1
  505. box_list = box_list_1
  506. # 表格识别
  507. line_list = otr_process(image_np)
  508. if judge_error_code(line_list):
  509. return line_list
  510. # 生成TextBox对象
  511. text_box_list = get_text_box_obj(text_list, box_list)
  512. # for t in text_box_list:
  513. # print('text_box0', t.get_text())
  514. # 表格生成
  515. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_box_list, image_np)
  516. # for t in text_box_list:
  517. # print('text_box1', t.get_text())
  518. # print('table_list', table_list)
  519. # for t in obj_in_table_list:
  520. # print('obj_text_box2', t.get_text())
  521. if judge_error_code(table_list):
  522. return table_list
  523. # 无边框表格识别
  524. start_time = time.time()
  525. text_box_list, b_table_list, b_obj_in_table_list = botr_process(image_np, table_list,
  526. text_list, box_list,
  527. text_box_list,
  528. obj_in_table_list,
  529. b_table_from_text,
  530. pdf_obj_list,
  531. pdf_layout_size,
  532. )
  533. log('botr process cost: ' + str(time.time()-start_time))
  534. # 合并非表格的同一行TextBox
  535. text_box_list = merge_textbox(text_box_list, obj_in_table_list)
  536. # 对象生成
  537. obj_list = []
  538. for table in table_list:
  539. _table = _Table(table["table"], table["bbox"])
  540. obj_list.append(_table)
  541. for table in b_table_list:
  542. _table = _Table(table["table"], table["bbox"])
  543. obj_list.append(_table)
  544. _table.y += 10000
  545. for text_box in text_box_list:
  546. if text_box not in obj_in_table_list:
  547. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  548. # 多图修正y
  549. if len(image_np_list) > 1:
  550. list_y = []
  551. for obj in obj_list:
  552. obj.y += _add_y
  553. list_y.append(obj.y)
  554. if len(list_y) > 0:
  555. _add_y = max(list_y)
  556. # 合并
  557. all_obj_list += obj_list
  558. else:
  559. all_obj_list = []
  560. table_list = []
  561. text_list = []
  562. box_list = []
  563. text_box_list = []
  564. obj_in_table_list = set()
  565. # 表格识别
  566. line_list = otr_process(image_np)
  567. if judge_error_code(line_list):
  568. return line_list
  569. # 生成TextBox对象
  570. text_box_list = get_text_box_obj(text_list, box_list)
  571. # 表格生成
  572. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_box_list, image_np)
  573. if judge_error_code(table_list):
  574. return table_list
  575. # 无边框表格识别
  576. start_time = time.time()
  577. text_box_list, table_list, obj_in_table_list = botr_process(image_np, table_list,
  578. text_list, box_list,
  579. text_box_list,
  580. obj_in_table_list,
  581. b_table_from_text,
  582. pdf_obj_list,
  583. pdf_layout_size,
  584. )
  585. log('botr process cost: ' + str(time.time()-start_time))
  586. # 合并非表格的同一行TextBox
  587. text_box_list = merge_textbox(text_box_list, obj_in_table_list)
  588. # 对象生成
  589. obj_list = []
  590. # print('table_list', table_list)
  591. for table in table_list:
  592. _table = _Table(table["table"], table["bbox"])
  593. obj_list.append(_table)
  594. for text_box in text_box_list:
  595. if text_box not in obj_in_table_list:
  596. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  597. # 合并
  598. all_obj_list += obj_list
  599. return all_obj_list
  600. except Exception as e:
  601. log("image_preprocess error")
  602. traceback.print_exc()
  603. return [-1]
  604. @memory_decorator
  605. def picture2text(path, html=False):
  606. log("into picture2text")
  607. try:
  608. # 判断图片中表格
  609. img = cv2.imread(path)
  610. if img is None:
  611. return [-3]
  612. text = image_process(img, path)
  613. if judge_error_code(text):
  614. return text
  615. if html:
  616. text = add_div(text)
  617. return [text]
  618. except Exception as e:
  619. log("picture2text error!")
  620. print("picture2text", traceback.print_exc())
  621. return [-1]
  622. def get_best_predict_size(image_np, times=64):
  623. sizes = []
  624. for i in range(1, 100):
  625. if i*times <= 1300:
  626. sizes.append(i*times)
  627. sizes.sort(key=lambda x: x, reverse=True)
  628. min_len = 10000
  629. best_height = sizes[0]
  630. for height in sizes:
  631. if abs(image_np.shape[0] - height) < min_len:
  632. min_len = abs(image_np.shape[0] - height)
  633. best_height = height
  634. min_len = 10000
  635. best_width = sizes[0]
  636. for width in sizes:
  637. if abs(image_np.shape[1] - width) < min_len:
  638. min_len = abs(image_np.shape[1] - width)
  639. best_width = width
  640. return best_height, best_width
  641. def get_best_predict_size2(image_np, threshold=3000):
  642. h, w = image_np.shape[:2]
  643. scale = threshold / max(h, w)
  644. h = int(h * scale)
  645. w = int(w * scale)
  646. return h, w
  647. def image_slice(image_np):
  648. """
  649. slice the image if the height is to large
  650. :return:
  651. """
  652. _sum = np.average(image_np, axis=1)
  653. list_white_line = []
  654. list_ave = list(_sum)
  655. for _i in range(len(list_ave)):
  656. if (list_ave[_i] > 250).all():
  657. list_white_line.append(_i)
  658. set_white_line = set(list_white_line)
  659. width = image_np.shape[1]
  660. height = image_np.shape[0]
  661. list_images = []
  662. _begin = 0
  663. _end = 0
  664. while 1:
  665. if _end > height:
  666. break
  667. _end += width
  668. while 1:
  669. if _begin in set_white_line:
  670. break
  671. if _begin > height:
  672. break
  673. _begin += 1
  674. _image = image_np[_begin:_end, ...]
  675. list_images.append(_image)
  676. _begin = _end
  677. log("image_slice into %d parts" % (len(list_images)))
  678. return list_images
  679. def image_slice_new(image_np):
  680. """
  681. 长图分割
  682. :return:
  683. """
  684. height, width = image_np.shape[:2]
  685. image_origin = copy.deepcopy(image_np)
  686. # 去除黑边
  687. image_np = remove_black_border(image_np)
  688. # 1. 转化成灰度图
  689. image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  690. # 2. 二值化
  691. ret, binary = cv2.threshold(image_np, 125, 255, cv2.THRESH_BINARY_INV)
  692. # 3. 膨胀和腐蚀操作的核函数
  693. kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  694. # 4. 膨胀一次,让轮廓突出
  695. dilation = cv2.dilate(binary, kernal, iterations=1)
  696. # dilation = np.add(np.int0(np.full(dilation.shape, 255)), -1 * np.int0(dilation))
  697. # dilation = np.uint8(dilation)
  698. # cv2.namedWindow("dilation", 0)
  699. # cv2.resizeWindow("dilation", 1000, 800)
  700. # cv2.imshow("dilation", dilation)
  701. # cv2.waitKey(0)
  702. # cv2.imwrite("error.jpg", dilation)
  703. # 按行求平均
  704. width_avg = np.average(np.float32(dilation), axis=1)
  705. zero_index = np.where(width_avg == 0.)[0]
  706. # print(height, width)
  707. # print(width_avg)
  708. # print(width_avg.shape)
  709. # print(zero_index)
  710. # print(zero_index.shape)
  711. # zero_index.sort(key=lambda x: x)
  712. # 截取范围内寻找分割点
  713. max_distance = int(width / 2)
  714. image_list = []
  715. last_h = 0
  716. for i in range(height // width + 1):
  717. h = last_h + width
  718. # 前后的分割点
  719. zero_h_after = zero_index[np.where(zero_index >= h)]
  720. zero_h_before = zero_index[np.where(zero_index <= h)]
  721. # print("last_h, h", last_h, h)
  722. # print("last_h, h", last_h, h)
  723. # print(zero_index.shape)
  724. # print("zero_h_after.shape", zero_h_after.shape)
  725. if zero_h_after.shape[0] == 0:
  726. # 最后一截
  727. last_image = image_origin[last_h:, :, :]
  728. if last_image.shape[0] <= max_distance:
  729. image_list[-1] = np.concatenate([image_list[-1], last_image], axis=0)
  730. else:
  731. image_list.append(last_image)
  732. break
  733. # 分割点距离不能太远
  734. cut_h = zero_h_after.tolist()[0]
  735. # print("cut_h", cut_h)
  736. if abs(h - cut_h) <= max_distance:
  737. image_list.append(image_origin[last_h:cut_h, :, :])
  738. last_h = cut_h
  739. # 后面找不到往前找
  740. else:
  741. cut_h = zero_h_before.tolist()[-1]
  742. if abs(cut_h - h) <= max_distance:
  743. image_list.append(image_origin[last_h:cut_h, :, :])
  744. last_h = cut_h
  745. # i = 0
  746. # for im in image_list:
  747. # print(im.shape)
  748. # cv2.imwrite("error" + str(i) + ".jpg", im)
  749. # i += 1
  750. # cv2.namedWindow("im", 0)
  751. # cv2.resizeWindow("im", 1000, 800)
  752. # cv2.imshow("im", im)
  753. # cv2.waitKey(0)
  754. log("image_slice into %d parts" % (len(image_list)))
  755. return image_list
  756. def need_image_slice(image_np):
  757. h, w = image_np.shape[:2]
  758. # if h > 3000 and w < 2000:
  759. # return True
  760. if 2. <= h / w and w >= 100:
  761. return True
  762. return False
  763. def remove_black_border(img_np):
  764. try:
  765. # 阈值
  766. threshold = 100
  767. # 转换为灰度图像
  768. gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
  769. # 获取图片尺寸
  770. h, w = gray.shape[:2]
  771. # 无法区分黑色区域超过一半的情况
  772. rowc = gray[:, int(1/2*w)]
  773. colc = gray[int(1/2*h), :]
  774. rowflag = np.argwhere(rowc > threshold)
  775. colflag = np.argwhere(colc > threshold)
  776. left, bottom, right, top = rowflag[0, 0], colflag[-1, 0], rowflag[-1, 0], colflag[0, 0]
  777. # cv2.imshow('remove_black_border', img_np[left:right, top:bottom, :])
  778. # cv2.waitKey()
  779. return img_np[left:right, top:bottom, :]
  780. except:
  781. return img_np
  782. class ImageConvert:
  783. def __init__(self, path, unique_type_dir):
  784. from format_convert.convert_tree import _Document
  785. self._doc = _Document(path)
  786. self.path = path
  787. self.unique_type_dir = unique_type_dir
  788. def init_package(self):
  789. # 各个包初始化
  790. try:
  791. with open(self.path, "rb") as f:
  792. self.image = f.read()
  793. except:
  794. log("cannot open image!")
  795. traceback.print_exc()
  796. self._doc.error_code = [-3]
  797. def convert(self):
  798. from format_convert.convert_tree import _Page, _Image
  799. self.init_package()
  800. if self._doc.error_code is not None:
  801. return
  802. _page = _Page(None, 0)
  803. _image = _Image(self.image, self.path)
  804. _page.add_child(_image)
  805. self._doc.add_child(_page)
  806. def get_html(self):
  807. try:
  808. self.convert()
  809. except:
  810. traceback.print_exc()
  811. self._doc.error_code = [-1]
  812. if self._doc.error_code is not None:
  813. return self._doc.error_code
  814. return self._doc.get_html()
  815. def image_process_old(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  816. from format_convert.convert_tree import _Table, _Sentence
  817. def get_cluster(t_list, b_list, axis):
  818. zip_list = list(zip(t_list, b_list))
  819. if len(zip_list) == 0:
  820. return t_list, b_list
  821. if len(zip_list[0]) > 0:
  822. zip_list.sort(key=lambda x: x[1][axis][1])
  823. cluster_list = []
  824. margin = 5
  825. for text, bbox in zip_list:
  826. _find = 0
  827. for cluster in cluster_list:
  828. if abs(cluster[1] - bbox[axis][1]) <= margin:
  829. cluster[0].append([text, bbox])
  830. cluster[1] = bbox[axis][1]
  831. _find = 1
  832. break
  833. if not _find:
  834. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  835. new_text_list = []
  836. new_bbox_list = []
  837. for cluster in cluster_list:
  838. # print("=============convert_image")
  839. # print("cluster_list", cluster)
  840. center_y = 0
  841. for text, bbox in cluster[0]:
  842. center_y += bbox[axis][1]
  843. center_y = int(center_y / len(cluster[0]))
  844. for text, bbox in cluster[0]:
  845. bbox[axis][1] = center_y
  846. new_text_list.append(text)
  847. new_bbox_list.append(bbox)
  848. # print("cluster_list", cluster)
  849. return new_text_list, new_bbox_list
  850. def merge_textbox(textbox_list, in_objs):
  851. delete_obj = []
  852. threshold = 5
  853. textbox_list.sort(key=lambda x:x.bbox[0])
  854. for k in range(len(textbox_list)):
  855. tb1 = textbox_list[k]
  856. if tb1 not in in_objs and tb1 not in delete_obj:
  857. for m in range(k+1, len(textbox_list)):
  858. tb2 = textbox_list[m]
  859. if tb2 in in_objs:
  860. continue
  861. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  862. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  863. if tb1.bbox[0] <= tb2.bbox[0]:
  864. tb1.text = tb1.text + tb2.text
  865. else:
  866. tb1.text = tb2.text + tb1.text
  867. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  868. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  869. delete_obj.append(tb2)
  870. for _obj in delete_obj:
  871. if _obj in textbox_list:
  872. textbox_list.remove(_obj)
  873. return textbox_list
  874. log("into image_preprocess")
  875. try:
  876. if image_np is None:
  877. return []
  878. # 整体分辨率限制
  879. if image_np.shape[0] > 2000 or image_np.shape[1] > 2000:
  880. h, w = get_best_predict_size2(image_np, threshold=2000)
  881. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  882. image_np = pil_resize(image_np, h, w)
  883. # 图片倾斜校正,写入原来的图片路径
  884. # print("image_process", image_path)
  885. g_r_i = get_rotated_image(image_np, image_path)
  886. if judge_error_code(g_r_i):
  887. if is_from_docx:
  888. return []
  889. else:
  890. return g_r_i
  891. image_np = cv2.imread(image_path)
  892. image_np_copy = copy.deepcopy(image_np)
  893. if image_np is None:
  894. return []
  895. # if image_np is None:
  896. # return []
  897. #
  898. # # idc模型实现图片倾斜校正
  899. # image_resize = pil_resize(image_np, 640, 640)
  900. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  901. # cv2.imwrite(image_resize_path, image_resize)
  902. #
  903. # with open(image_resize_path, "rb") as f:
  904. # image_bytes = f.read()
  905. # angle = from_idc_interface(image_bytes)
  906. # if judge_error_code(angle):
  907. # if is_from_docx:
  908. # return []
  909. # else:
  910. # return angle
  911. # # 根据角度旋转
  912. # image_pil = Image.fromarray(image_np)
  913. # image_np = np.array(image_pil.rotate(angle, expand=1))
  914. # # 写入
  915. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  916. # cv2.imwrite(idc_path, image_np)
  917. # isr模型去除印章
  918. _isr_time = time.time()
  919. if count_red_pixel(image_np):
  920. # 红色像素达到一定值才过模型
  921. with open(image_path, "rb") as f:
  922. image_bytes = f.read()
  923. image_np = from_isr_interface(image_bytes)
  924. if judge_error_code(image_np):
  925. if is_from_docx:
  926. return []
  927. else:
  928. return image_np
  929. # [1]代表检测不到印章,直接返回
  930. if isinstance(image_np, list) and image_np == [1]:
  931. log("no seals detected!")
  932. image_np = image_np_copy
  933. else:
  934. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  935. cv2.imwrite(isr_path, image_np)
  936. log("isr total time "+str(time.time()-_isr_time))
  937. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  938. best_h, best_w = get_best_predict_size(image_np)
  939. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  940. image_resize = pil_resize(image_np, best_h, best_w)
  941. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  942. cv2.imwrite(image_resize_path, image_resize)
  943. # 调用otr模型接口
  944. with open(image_resize_path, "rb") as f:
  945. image_bytes = f.read()
  946. list_line = from_otr_interface(image_bytes, is_from_pdf)
  947. if judge_error_code(list_line):
  948. return list_line
  949. # # 预处理
  950. # if is_from_pdf:
  951. # prob = 0.2
  952. # else:
  953. # prob = 0.5
  954. # with open(image_resize_path, "rb") as f:
  955. # image_bytes = f.read()
  956. # img_new, inputs = table_preprocess(image_bytes, prob)
  957. # if type(img_new) is list and judge_error_code(img_new):
  958. # return img_new
  959. # log("img_new.shape " + str(img_new.shape))
  960. #
  961. # # 调用模型运行接口
  962. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  963. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  964. # if judge_error_code(result):
  965. # logging.error("from_gpu_interface failed! " + str(result))
  966. # raise requests.exceptions.RequestException
  967. #
  968. # pred = result.get("preds")
  969. # gpu_time = result.get("gpu_time")
  970. # log("otr model predict time " + str(gpu_time))
  971. #
  972. # # # 解压numpy
  973. # # decompressed_array = io.BytesIO()
  974. # # decompressed_array.write(pred)
  975. # # decompressed_array.seek(0)
  976. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  977. # # log("inputs.shape" + str(pred.shape))
  978. #
  979. # 调用gpu共享内存处理
  980. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  981. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  982. # if judge_error_code(result):
  983. # logging.error("from_gpu_interface failed! " + str(result))
  984. # raise requests.exceptions.RequestException
  985. #
  986. # pred = result.get("preds")
  987. # gpu_time = result.get("gpu_time")
  988. # log("otr model predict time " + str(gpu_time))
  989. #
  990. # # 后处理
  991. # list_line = table_postprocess(img_new, pred, prob)
  992. # log("len(list_line) " + str(len(list_line)))
  993. # if judge_error_code(list_line):
  994. # return list_line
  995. # otr resize后得到的bbox根据比例还原
  996. start_time = time.time()
  997. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  998. for i in range(len(list_line)):
  999. point = list_line[i]
  1000. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  1001. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  1002. log("otr resize bbox recover " + str(time.time()-start_time))
  1003. # ocr图片过大内存溢出,需resize
  1004. start_time = time.time()
  1005. threshold = 3000
  1006. ocr_resize_flag = 0
  1007. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  1008. ocr_resize_flag = 1
  1009. best_h, best_w = get_best_predict_size2(image_np, threshold)
  1010. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  1011. image_resize = pil_resize(image_np, best_h, best_w)
  1012. log("ocr_process image resize " + str(image_resize.shape))
  1013. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  1014. cv2.imwrite(image_resize_path, image_resize)
  1015. log("ocr resize before " + str(time.time()-start_time))
  1016. # 调用ocr模型接口
  1017. with open(image_resize_path, "rb") as f:
  1018. image_bytes = f.read()
  1019. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=1)
  1020. if judge_error_code(text_list):
  1021. return text_list
  1022. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  1023. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  1024. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  1025. # # 循环每张图片识别结果
  1026. # text_list = []
  1027. # bbox_list = []
  1028. # for line in results:
  1029. # # print("ocr_interface line", line)
  1030. # text_list.append(line[-1][0])
  1031. # bbox_list.append(line[0])
  1032. # if len(text_list) == 0:
  1033. # return []
  1034. # ocr resize后的bbox还原
  1035. if ocr_resize_flag:
  1036. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  1037. else:
  1038. ratio = (1, 1)
  1039. for i in range(len(bbox_list)):
  1040. point = bbox_list[i]
  1041. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  1042. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  1043. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  1044. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  1045. # 调用现成方法形成表格
  1046. try:
  1047. from format_convert.convert_tree import TableLine
  1048. list_lines = []
  1049. for line in list_line:
  1050. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  1051. from format_convert.convert_tree import TextBox
  1052. list_text_boxes = []
  1053. for i in range(len(bbox_list)):
  1054. bbox = bbox_list[i]
  1055. b_text = text_list[i]
  1056. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  1057. bbox[2][0], bbox[2][1]], b_text))
  1058. # for _textbox in list_text_boxes:
  1059. # print("==",_textbox.get_text())
  1060. lt = LineTable()
  1061. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  1062. # 合并同一行textbox
  1063. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  1064. obj_list = []
  1065. for table in tables:
  1066. obj_list.append(_Table(table["table"], table["bbox"]))
  1067. for text_box in list_text_boxes:
  1068. if text_box not in obj_in_table:
  1069. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  1070. return obj_list
  1071. except:
  1072. traceback.print_exc()
  1073. return [-8]
  1074. except Exception as e:
  1075. log("image_preprocess error")
  1076. traceback.print_exc()
  1077. return [-1]
  1078. if __name__ == "__main__":
  1079. image_slice_new(cv2.imread("C:/Users/Administrator/Desktop/test_image/error28.jpg"))