convert_image.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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, np2bytes, ocr_cant_read
  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. def idc_process(_image_np):
  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. # return _image_np
  94. # if _image_np is None:
  95. # return []
  96. # idc模型实现图片倾斜校正
  97. h, w = get_best_predict_size2(_image_np, 1080)
  98. image_resize = pil_resize(_image_np, h, w)
  99. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  100. # cv2.imwrite(image_resize_path, image_resize)
  101. # with open(image_resize_path, "rb") as f:
  102. # image_bytes = f.read()
  103. image_bytes = np2bytes(image_resize)
  104. angle = from_idc_interface(image_bytes)
  105. if judge_error_code(angle):
  106. if is_from_docx:
  107. return []
  108. else:
  109. return angle
  110. # 根据角度旋转
  111. image_pil = Image.fromarray(_image_np)
  112. _image_np = np.array(image_pil.rotate(angle, expand=1))
  113. # 写入
  114. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  115. # cv2.imwrite(idc_path, image_np)
  116. return _image_np
  117. def isr_process(_image_np):
  118. image_np_copy = copy.deepcopy(_image_np)
  119. # isr模型去除印章
  120. _isr_time = time.time()
  121. if count_red_pixel(_image_np):
  122. # 红色像素达到一定值才过模型
  123. with open(image_path, "rb") as f:
  124. image_bytes = f.read()
  125. _image_np = from_isr_interface(image_bytes)
  126. if judge_error_code(_image_np):
  127. if is_from_docx:
  128. return []
  129. else:
  130. return _image_np
  131. # [1]代表检测不到印章,直接返回
  132. if isinstance(_image_np, list) and _image_np == [1]:
  133. log("no seals detected!")
  134. _image_np = image_np_copy
  135. else:
  136. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  137. cv2.imwrite(isr_path, _image_np)
  138. log("isr total time "+str(time.time()-_isr_time))
  139. return _image_np
  140. def ocr_process(_image_np):
  141. # ocr图片过大内存溢出,需resize
  142. start_time = time.time()
  143. # 调用ocr模型接口
  144. image_bytes = np2bytes(_image_np)
  145. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  146. if judge_error_code(text_list):
  147. return text_list, text_list
  148. for i in range(len(bbox_list)):
  149. point = bbox_list[i]
  150. bbox_list[i] = [[int(point[0][0]), int(point[0][1])],
  151. [int(point[1][0]), int(point[1][1])],
  152. [int(point[2][0]), int(point[2][1])],
  153. [int(point[3][0]), int(point[3][1])]]
  154. return text_list, bbox_list
  155. def otr_process(_image_np):
  156. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  157. best_h, best_w = get_best_predict_size(_image_np)
  158. image_resize = pil_resize(_image_np, best_h, best_w)
  159. # image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  160. # cv2.imwrite(image_resize_path, image_resize)
  161. # 调用otr模型接口
  162. # with open(image_resize_path, "rb") as f:
  163. # image_bytes = f.read()
  164. image_bytes = np2bytes(image_resize)
  165. list_line = from_otr_interface(image_bytes, is_from_pdf)
  166. if judge_error_code(list_line):
  167. if is_from_docx:
  168. return []
  169. else:
  170. return list_line
  171. # otr resize后得到的bbox根据比例还原
  172. start_time = time.time()
  173. ratio = (_image_np.shape[0]/best_h, _image_np.shape[1]/best_w)
  174. for i in range(len(list_line)):
  175. point = list_line[i]
  176. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  177. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  178. log("otr resize bbox recover " + str(time.time()-start_time))
  179. return list_line
  180. def table_process(list_line, text_list, bbox_list):
  181. # 调用现成方法形成表格
  182. try:
  183. from format_convert.convert_tree import TableLine
  184. list_lines = []
  185. for line in list_line:
  186. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  187. from format_convert.convert_tree import TextBox
  188. list_text_boxes = []
  189. for i in range(len(bbox_list)):
  190. bbox = bbox_list[i]
  191. b_text = text_list[i]
  192. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  193. bbox[2][0], bbox[2][1]], b_text))
  194. # for _textbox in list_text_boxes:
  195. # print("==",_textbox.get_text())
  196. lt = LineTable()
  197. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  198. # 合并同一行textbox
  199. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  200. return list_text_boxes, tables, obj_in_table
  201. except:
  202. traceback.print_exc()
  203. return [-8], [-8], [-8]
  204. log("into image_preprocess")
  205. try:
  206. if image_np is None:
  207. return []
  208. # 整体分辨率限制
  209. threshold = 2000
  210. if image_np.shape[0] > threshold or image_np.shape[1] > threshold:
  211. h, w = get_best_predict_size2(image_np, threshold=threshold)
  212. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  213. image_np = pil_resize(image_np, h, w)
  214. # 印章去除
  215. image_np = isr_process(image_np)
  216. if isinstance(image_np, list):
  217. return image_np
  218. # 文字识别
  219. text_list, box_list = ocr_process(image_np)
  220. if judge_error_code(text_list):
  221. return text_list
  222. # 判断ocr识别是否正确
  223. if ocr_cant_read(text_list, box_list):
  224. # 方向分类
  225. image_np = idc_process(image_np)
  226. # cv2.imshow("idc_process", image_np)
  227. # cv2.waitKey(0)
  228. if isinstance(image_np, list):
  229. return image_np
  230. # 文字识别
  231. text_list1, box_list_1 = ocr_process(image_np)
  232. if judge_error_code(text_list1):
  233. return text_list1
  234. # 比较字数
  235. # print("ocr process", len("".join(text_list)), len("".join(text_list1)))
  236. if len("".join(text_list)) < len("".join(text_list1)):
  237. text_list = text_list1
  238. box_list = box_list_1
  239. # 表格识别
  240. line_list = otr_process(image_np)
  241. if judge_error_code(line_list):
  242. return line_list
  243. # 表格生成
  244. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_list, box_list)
  245. if judge_error_code(table_list):
  246. return table_list
  247. # 对象生成
  248. obj_list = []
  249. for table in table_list:
  250. obj_list.append(_Table(table["table"], table["bbox"]))
  251. for text_box in text_box_list:
  252. if text_box not in obj_in_table_list:
  253. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  254. return obj_list
  255. except Exception as e:
  256. log("image_preprocess error")
  257. traceback.print_exc()
  258. return [-1]
  259. @memory_decorator
  260. def picture2text(path, html=False):
  261. log("into picture2text")
  262. try:
  263. # 判断图片中表格
  264. img = cv2.imread(path)
  265. if img is None:
  266. return [-3]
  267. text = image_process(img, path)
  268. if judge_error_code(text):
  269. return text
  270. if html:
  271. text = add_div(text)
  272. return [text]
  273. except Exception as e:
  274. log("picture2text error!")
  275. print("picture2text", traceback.print_exc())
  276. return [-1]
  277. def get_best_predict_size(image_np, times=64):
  278. sizes = []
  279. for i in range(1, 100):
  280. if i*times <= 1300:
  281. sizes.append(i*times)
  282. sizes.sort(key=lambda x: x, reverse=True)
  283. min_len = 10000
  284. best_height = sizes[0]
  285. for height in sizes:
  286. if abs(image_np.shape[0] - height) < min_len:
  287. min_len = abs(image_np.shape[0] - height)
  288. best_height = height
  289. min_len = 10000
  290. best_width = sizes[0]
  291. for width in sizes:
  292. if abs(image_np.shape[1] - width) < min_len:
  293. min_len = abs(image_np.shape[1] - width)
  294. best_width = width
  295. return best_height, best_width
  296. def get_best_predict_size2(image_np, threshold=3000):
  297. h, w = image_np.shape[:2]
  298. scale = threshold / max(h, w)
  299. h = int(h * scale)
  300. w = int(w * scale)
  301. return h, w
  302. class ImageConvert:
  303. def __init__(self, path, unique_type_dir):
  304. from format_convert.convert_tree import _Document
  305. self._doc = _Document(path)
  306. self.path = path
  307. self.unique_type_dir = unique_type_dir
  308. def init_package(self):
  309. # 各个包初始化
  310. try:
  311. with open(self.path, "rb") as f:
  312. self.image = f.read()
  313. except:
  314. log("cannot open image!")
  315. traceback.print_exc()
  316. self._doc.error_code = [-3]
  317. def convert(self):
  318. from format_convert.convert_tree import _Page, _Image
  319. self.init_package()
  320. if self._doc.error_code is not None:
  321. return
  322. _page = _Page(None, 0)
  323. _image = _Image(self.image, self.path)
  324. _page.add_child(_image)
  325. self._doc.add_child(_page)
  326. def get_html(self):
  327. try:
  328. self.convert()
  329. except:
  330. traceback.print_exc()
  331. self._doc.error_code = [-1]
  332. if self._doc.error_code is not None:
  333. return self._doc.error_code
  334. return self._doc.get_html()
  335. def image_process_old(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  336. from format_convert.convert_tree import _Table, _Sentence
  337. def get_cluster(t_list, b_list, axis):
  338. zip_list = list(zip(t_list, b_list))
  339. if len(zip_list) == 0:
  340. return t_list, b_list
  341. if len(zip_list[0]) > 0:
  342. zip_list.sort(key=lambda x: x[1][axis][1])
  343. cluster_list = []
  344. margin = 5
  345. for text, bbox in zip_list:
  346. _find = 0
  347. for cluster in cluster_list:
  348. if abs(cluster[1] - bbox[axis][1]) <= margin:
  349. cluster[0].append([text, bbox])
  350. cluster[1] = bbox[axis][1]
  351. _find = 1
  352. break
  353. if not _find:
  354. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  355. new_text_list = []
  356. new_bbox_list = []
  357. for cluster in cluster_list:
  358. # print("=============convert_image")
  359. # print("cluster_list", cluster)
  360. center_y = 0
  361. for text, bbox in cluster[0]:
  362. center_y += bbox[axis][1]
  363. center_y = int(center_y / len(cluster[0]))
  364. for text, bbox in cluster[0]:
  365. bbox[axis][1] = center_y
  366. new_text_list.append(text)
  367. new_bbox_list.append(bbox)
  368. # print("cluster_list", cluster)
  369. return new_text_list, new_bbox_list
  370. def merge_textbox(textbox_list, in_objs):
  371. delete_obj = []
  372. threshold = 5
  373. textbox_list.sort(key=lambda x:x.bbox[0])
  374. for k in range(len(textbox_list)):
  375. tb1 = textbox_list[k]
  376. if tb1 not in in_objs and tb1 not in delete_obj:
  377. for m in range(k+1, len(textbox_list)):
  378. tb2 = textbox_list[m]
  379. if tb2 in in_objs:
  380. continue
  381. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  382. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  383. if tb1.bbox[0] <= tb2.bbox[0]:
  384. tb1.text = tb1.text + tb2.text
  385. else:
  386. tb1.text = tb2.text + tb1.text
  387. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  388. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  389. delete_obj.append(tb2)
  390. for _obj in delete_obj:
  391. if _obj in textbox_list:
  392. textbox_list.remove(_obj)
  393. return textbox_list
  394. log("into image_preprocess")
  395. try:
  396. if image_np is None:
  397. return []
  398. # 整体分辨率限制
  399. if image_np.shape[0] > 2000 or image_np.shape[1] > 2000:
  400. h, w = get_best_predict_size2(image_np, threshold=2000)
  401. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  402. image_np = pil_resize(image_np, h, w)
  403. # 图片倾斜校正,写入原来的图片路径
  404. # print("image_process", image_path)
  405. g_r_i = get_rotated_image(image_np, image_path)
  406. if judge_error_code(g_r_i):
  407. if is_from_docx:
  408. return []
  409. else:
  410. return g_r_i
  411. image_np = cv2.imread(image_path)
  412. image_np_copy = copy.deepcopy(image_np)
  413. if image_np is None:
  414. return []
  415. # if image_np is None:
  416. # return []
  417. #
  418. # # idc模型实现图片倾斜校正
  419. # image_resize = pil_resize(image_np, 640, 640)
  420. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  421. # cv2.imwrite(image_resize_path, image_resize)
  422. #
  423. # with open(image_resize_path, "rb") as f:
  424. # image_bytes = f.read()
  425. # angle = from_idc_interface(image_bytes)
  426. # if judge_error_code(angle):
  427. # if is_from_docx:
  428. # return []
  429. # else:
  430. # return angle
  431. # # 根据角度旋转
  432. # image_pil = Image.fromarray(image_np)
  433. # image_np = np.array(image_pil.rotate(angle, expand=1))
  434. # # 写入
  435. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  436. # cv2.imwrite(idc_path, image_np)
  437. # isr模型去除印章
  438. _isr_time = time.time()
  439. if count_red_pixel(image_np):
  440. # 红色像素达到一定值才过模型
  441. with open(image_path, "rb") as f:
  442. image_bytes = f.read()
  443. image_np = from_isr_interface(image_bytes)
  444. if judge_error_code(image_np):
  445. if is_from_docx:
  446. return []
  447. else:
  448. return image_np
  449. # [1]代表检测不到印章,直接返回
  450. if isinstance(image_np, list) and image_np == [1]:
  451. log("no seals detected!")
  452. image_np = image_np_copy
  453. else:
  454. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  455. cv2.imwrite(isr_path, image_np)
  456. log("isr total time "+str(time.time()-_isr_time))
  457. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  458. best_h, best_w = get_best_predict_size(image_np)
  459. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  460. image_resize = pil_resize(image_np, best_h, best_w)
  461. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  462. cv2.imwrite(image_resize_path, image_resize)
  463. # 调用otr模型接口
  464. with open(image_resize_path, "rb") as f:
  465. image_bytes = f.read()
  466. list_line = from_otr_interface(image_bytes, is_from_pdf)
  467. if judge_error_code(list_line):
  468. return list_line
  469. # # 预处理
  470. # if is_from_pdf:
  471. # prob = 0.2
  472. # else:
  473. # prob = 0.5
  474. # with open(image_resize_path, "rb") as f:
  475. # image_bytes = f.read()
  476. # img_new, inputs = table_preprocess(image_bytes, prob)
  477. # if type(img_new) is list and judge_error_code(img_new):
  478. # return img_new
  479. # log("img_new.shape " + str(img_new.shape))
  480. #
  481. # # 调用模型运行接口
  482. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  483. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  484. # if judge_error_code(result):
  485. # logging.error("from_gpu_interface failed! " + str(result))
  486. # raise requests.exceptions.RequestException
  487. #
  488. # pred = result.get("preds")
  489. # gpu_time = result.get("gpu_time")
  490. # log("otr model predict time " + str(gpu_time))
  491. #
  492. # # # 解压numpy
  493. # # decompressed_array = io.BytesIO()
  494. # # decompressed_array.write(pred)
  495. # # decompressed_array.seek(0)
  496. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  497. # # log("inputs.shape" + str(pred.shape))
  498. #
  499. # 调用gpu共享内存处理
  500. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  501. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  502. # if judge_error_code(result):
  503. # logging.error("from_gpu_interface failed! " + str(result))
  504. # raise requests.exceptions.RequestException
  505. #
  506. # pred = result.get("preds")
  507. # gpu_time = result.get("gpu_time")
  508. # log("otr model predict time " + str(gpu_time))
  509. #
  510. # # 后处理
  511. # list_line = table_postprocess(img_new, pred, prob)
  512. # log("len(list_line) " + str(len(list_line)))
  513. # if judge_error_code(list_line):
  514. # return list_line
  515. # otr resize后得到的bbox根据比例还原
  516. start_time = time.time()
  517. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  518. for i in range(len(list_line)):
  519. point = list_line[i]
  520. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  521. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  522. log("otr resize bbox recover " + str(time.time()-start_time))
  523. # ocr图片过大内存溢出,需resize
  524. start_time = time.time()
  525. threshold = 3000
  526. ocr_resize_flag = 0
  527. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  528. ocr_resize_flag = 1
  529. best_h, best_w = get_best_predict_size2(image_np, threshold)
  530. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  531. image_resize = pil_resize(image_np, best_h, best_w)
  532. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  533. cv2.imwrite(image_resize_path, image_resize)
  534. log("ocr resize before " + str(time.time()-start_time))
  535. # 调用ocr模型接口
  536. with open(image_resize_path, "rb") as f:
  537. image_bytes = f.read()
  538. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  539. if judge_error_code(text_list):
  540. return text_list
  541. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  542. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  543. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  544. # # 循环每张图片识别结果
  545. # text_list = []
  546. # bbox_list = []
  547. # for line in results:
  548. # # print("ocr_interface line", line)
  549. # text_list.append(line[-1][0])
  550. # bbox_list.append(line[0])
  551. # if len(text_list) == 0:
  552. # return []
  553. # ocr resize后的bbox还原
  554. if ocr_resize_flag:
  555. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  556. else:
  557. ratio = (1, 1)
  558. for i in range(len(bbox_list)):
  559. point = bbox_list[i]
  560. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  561. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  562. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  563. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  564. # 调用现成方法形成表格
  565. try:
  566. from format_convert.convert_tree import TableLine
  567. list_lines = []
  568. for line in list_line:
  569. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  570. from format_convert.convert_tree import TextBox
  571. list_text_boxes = []
  572. for i in range(len(bbox_list)):
  573. bbox = bbox_list[i]
  574. b_text = text_list[i]
  575. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  576. bbox[2][0], bbox[2][1]], b_text))
  577. # for _textbox in list_text_boxes:
  578. # print("==",_textbox.get_text())
  579. lt = LineTable()
  580. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  581. # 合并同一行textbox
  582. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  583. obj_list = []
  584. for table in tables:
  585. obj_list.append(_Table(table["table"], table["bbox"]))
  586. for text_box in list_text_boxes:
  587. if text_box not in obj_in_table:
  588. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  589. return obj_list
  590. except:
  591. traceback.print_exc()
  592. return [-8]
  593. except Exception as e:
  594. log("image_preprocess error")
  595. traceback.print_exc()
  596. return [-1]