convert_image.py 50 KB

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