convert_image.py 50 KB

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