convert_image.py 44 KB

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