convert_image.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. # encoding=utf8
  2. import copy
  3. import inspect
  4. import io
  5. import logging
  6. import os
  7. import sys
  8. import time
  9. import requests
  10. import numpy as np
  11. from PIL import Image
  12. sys.path.append(os.path.dirname(__file__) + "/../")
  13. from pdfminer.layout import LTLine
  14. import traceback
  15. import cv2
  16. from isr.pre_process import count_red_pixel
  17. from format_convert.utils import judge_error_code, add_div, LineTable, get_table_html, get_logger, log, \
  18. memory_decorator, pil_resize, np2bytes, ocr_cant_read
  19. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface, from_gpu_interface_redis, \
  20. from_idc_interface, from_isr_interface
  21. from format_convert.table_correct import get_rotated_image
  22. def image_process(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  23. from format_convert.convert_tree import _Table, _Sentence
  24. def get_cluster(t_list, b_list, axis):
  25. zip_list = list(zip(t_list, b_list))
  26. if len(zip_list) == 0:
  27. return t_list, b_list
  28. if len(zip_list[0]) > 0:
  29. zip_list.sort(key=lambda x: x[1][axis][1])
  30. cluster_list = []
  31. margin = 5
  32. for text, bbox in zip_list:
  33. _find = 0
  34. for cluster in cluster_list:
  35. if abs(cluster[1] - bbox[axis][1]) <= margin:
  36. cluster[0].append([text, bbox])
  37. cluster[1] = bbox[axis][1]
  38. _find = 1
  39. break
  40. if not _find:
  41. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  42. new_text_list = []
  43. new_bbox_list = []
  44. for cluster in cluster_list:
  45. # print("=============convert_image")
  46. # print("cluster_list", cluster)
  47. center_y = 0
  48. for text, bbox in cluster[0]:
  49. center_y += bbox[axis][1]
  50. center_y = int(center_y / len(cluster[0]))
  51. for text, bbox in cluster[0]:
  52. bbox[axis][1] = center_y
  53. new_text_list.append(text)
  54. new_bbox_list.append(bbox)
  55. # print("cluster_list", cluster)
  56. return new_text_list, new_bbox_list
  57. def merge_textbox(textbox_list, in_objs):
  58. delete_obj = []
  59. threshold = 5
  60. textbox_list.sort(key=lambda x:x.bbox[0])
  61. for k in range(len(textbox_list)):
  62. tb1 = textbox_list[k]
  63. if tb1 not in in_objs and tb1 not in delete_obj:
  64. for m in range(k+1, len(textbox_list)):
  65. tb2 = textbox_list[m]
  66. if tb2 in in_objs:
  67. continue
  68. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  69. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  70. if tb1.bbox[0] <= tb2.bbox[0]:
  71. tb1.text = tb1.text + tb2.text
  72. else:
  73. tb1.text = tb2.text + tb1.text
  74. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  75. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  76. delete_obj.append(tb2)
  77. for _obj in delete_obj:
  78. if _obj in textbox_list:
  79. textbox_list.remove(_obj)
  80. return textbox_list
  81. def idc_process(_image_np):
  82. # 图片倾斜校正,写入原来的图片路径
  83. # print("image_process", image_path)
  84. # g_r_i = get_rotated_image(_image_np, image_path)
  85. # if judge_error_code(g_r_i):
  86. # if is_from_docx:
  87. # return []
  88. # else:
  89. # return g_r_i
  90. # _image_np = cv2.imread(image_path)
  91. # if _image_np is None:
  92. # return []
  93. # return _image_np
  94. # if _image_np is None:
  95. # return []
  96. # idc模型实现图片倾斜校正
  97. h, w = get_best_predict_size2(_image_np, 1080)
  98. image_resize = pil_resize(_image_np, h, w)
  99. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  100. # cv2.imwrite(image_resize_path, image_resize)
  101. # with open(image_resize_path, "rb") as f:
  102. # image_bytes = f.read()
  103. image_bytes = np2bytes(image_resize)
  104. angle = from_idc_interface(image_bytes)
  105. if judge_error_code(angle):
  106. if is_from_docx:
  107. return []
  108. else:
  109. return angle
  110. # 根据角度旋转
  111. image_pil = Image.fromarray(_image_np)
  112. _image_np = np.array(image_pil.rotate(angle, expand=1))
  113. # 写入
  114. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  115. # cv2.imwrite(idc_path, image_np)
  116. return _image_np
  117. def isr_process(_image_np):
  118. log("isr_process image shape " + str(_image_np.shape))
  119. image_np_copy = copy.deepcopy(_image_np)
  120. # isr模型去除印章
  121. _isr_time = time.time()
  122. if count_red_pixel(_image_np):
  123. # 红色像素达到一定值才过模型
  124. image_bytes = np2bytes(_image_np)
  125. _image_np = from_isr_interface(image_bytes)
  126. if judge_error_code(_image_np):
  127. if is_from_docx:
  128. return []
  129. else:
  130. return _image_np
  131. # [1]代表检测不到印章,直接返回
  132. if isinstance(_image_np, list) and _image_np == [1]:
  133. log("no seals detected!")
  134. _image_np = image_np_copy
  135. log("isr total time "+str(time.time()-_isr_time))
  136. return _image_np
  137. def ocr_process(_image_np, _threshold=1024):
  138. log("ocr_process image shape " + str(_image_np.shape))
  139. # ocr图片过大内存溢出,需resize
  140. # 大图按比例缩小,小图维持不变;若统一拉伸成固定大小如1024会爆显存
  141. ratio = (1, 1)
  142. if _image_np.shape[0] >= _threshold or _image_np.shape[1] >= _threshold:
  143. best_h, best_w = get_best_predict_size2(_image_np, 1024)
  144. _image_np = pil_resize(_image_np, best_h, best_w)
  145. log("ocr_process image resize " + str(_image_np.shape))
  146. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  147. # 调用ocr模型接口
  148. image_bytes = np2bytes(_image_np)
  149. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  150. if judge_error_code(text_list):
  151. return text_list, text_list
  152. for i in range(len(bbox_list)):
  153. point = bbox_list[i]
  154. bbox_list[i] = [[int(point[0][0]*ratio[0]), int(point[0][1]*ratio[1])],
  155. [int(point[1][0]*ratio[0]), int(point[1][1]*ratio[1])],
  156. [int(point[2][0]*ratio[0]), int(point[2][1]*ratio[1])],
  157. [int(point[3][0]*ratio[0]), int(point[3][1]*ratio[1])]]
  158. return text_list, bbox_list
  159. def otr_process(_image_np):
  160. log("otr_process image shape " + str(_image_np.shape))
  161. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  162. best_h, best_w = get_best_predict_size(_image_np)
  163. image_resize = pil_resize(_image_np, best_h, best_w)
  164. # image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  165. # cv2.imwrite(image_resize_path, image_resize)
  166. # 调用otr模型接口
  167. # with open(image_resize_path, "rb") as f:
  168. # image_bytes = f.read()
  169. image_bytes = np2bytes(image_resize)
  170. list_line = from_otr_interface(image_bytes, is_from_pdf)
  171. if judge_error_code(list_line):
  172. if is_from_docx:
  173. return []
  174. else:
  175. return list_line
  176. # otr resize后得到的bbox根据比例还原
  177. start_time = time.time()
  178. ratio = (_image_np.shape[0]/best_h, _image_np.shape[1]/best_w)
  179. for i in range(len(list_line)):
  180. point = list_line[i]
  181. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  182. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  183. log("otr resize bbox recover " + str(time.time()-start_time))
  184. return list_line
  185. def table_process(list_line, text_list, bbox_list):
  186. # 调用现成方法形成表格
  187. try:
  188. from format_convert.convert_tree import TableLine
  189. list_lines = []
  190. for line in list_line:
  191. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  192. from format_convert.convert_tree import TextBox
  193. list_text_boxes = []
  194. for i in range(len(bbox_list)):
  195. bbox = bbox_list[i]
  196. b_text = text_list[i]
  197. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  198. bbox[2][0], bbox[2][1]], b_text))
  199. # for _textbox in list_text_boxes:
  200. # print("==",_textbox.get_text())
  201. lt = LineTable()
  202. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  203. # 合并同一行textbox
  204. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  205. return list_text_boxes, tables, obj_in_table
  206. except:
  207. traceback.print_exc()
  208. return [-8], [-8], [-8]
  209. log("into image_preprocess")
  210. try:
  211. if image_np is None:
  212. return []
  213. if image_np.shape[0] <= 20 or image_np.shape[1] <= 20:
  214. return []
  215. # 判断是否需要长图分割
  216. slice_flag = need_image_slice(image_np)
  217. log("need_image_slice " + str(slice_flag) + " " + str(image_np.shape))
  218. idc_flag = False
  219. image_np_list = [image_np]
  220. if slice_flag:
  221. # 方向分类
  222. image_np = idc_process(image_np)
  223. idc_flag = True
  224. if isinstance(image_np, list):
  225. return image_np
  226. # 再判断
  227. if need_image_slice(image_np):
  228. # 长图分割
  229. image_np_list = image_slice_new(image_np)
  230. if len(image_np_list) < 1:
  231. return [-12]
  232. all_obj_list = []
  233. _add_y = 0
  234. for image_np in image_np_list:
  235. print("sub image shape", image_np.shape)
  236. # 整体分辨率限制
  237. threshold = 2000
  238. if image_np.shape[0] > threshold or image_np.shape[1] > threshold:
  239. h, w = get_best_predict_size2(image_np, threshold=threshold)
  240. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  241. image_np = pil_resize(image_np, h, w)
  242. # 印章去除
  243. image_np = isr_process(image_np)
  244. if isinstance(image_np, list):
  245. return image_np
  246. # 文字识别
  247. text_list, box_list = ocr_process(image_np)
  248. if judge_error_code(text_list):
  249. return text_list
  250. # 判断ocr识别是否正确
  251. if ocr_cant_read(text_list, box_list) and not idc_flag:
  252. # 方向分类
  253. image_np = idc_process(image_np)
  254. # cv2.imshow("idc_process", image_np)
  255. # cv2.waitKey(0)
  256. if isinstance(image_np, list):
  257. return image_np
  258. # 文字识别
  259. text_list1, box_list_1 = ocr_process(image_np)
  260. if judge_error_code(text_list1):
  261. return text_list1
  262. # 比较字数
  263. # print("ocr process", len("".join(text_list)), len("".join(text_list1)))
  264. if len("".join(text_list)) < len("".join(text_list1)):
  265. text_list = text_list1
  266. box_list = box_list_1
  267. # 表格识别
  268. line_list = otr_process(image_np)
  269. if judge_error_code(line_list):
  270. return line_list
  271. # 表格生成
  272. text_box_list, table_list, obj_in_table_list = table_process(line_list, text_list, box_list)
  273. if judge_error_code(table_list):
  274. return table_list
  275. # 对象生成
  276. obj_list = []
  277. for table in table_list:
  278. obj_list.append(_Table(table["table"], table["bbox"]))
  279. for text_box in text_box_list:
  280. if text_box not in obj_in_table_list:
  281. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  282. # 修正y
  283. if len(image_np_list) > 1:
  284. list_y = []
  285. for obj in obj_list:
  286. obj.y += _add_y
  287. list_y.append(obj.y)
  288. if len(list_y) > 0:
  289. _add_y = max(list_y)
  290. # 合并
  291. all_obj_list += obj_list
  292. return all_obj_list
  293. except Exception as e:
  294. log("image_preprocess error")
  295. traceback.print_exc()
  296. return [-1]
  297. @memory_decorator
  298. def picture2text(path, html=False):
  299. log("into picture2text")
  300. try:
  301. # 判断图片中表格
  302. img = cv2.imread(path)
  303. if img is None:
  304. return [-3]
  305. text = image_process(img, path)
  306. if judge_error_code(text):
  307. return text
  308. if html:
  309. text = add_div(text)
  310. return [text]
  311. except Exception as e:
  312. log("picture2text error!")
  313. print("picture2text", traceback.print_exc())
  314. return [-1]
  315. def get_best_predict_size(image_np, times=64):
  316. sizes = []
  317. for i in range(1, 100):
  318. if i*times <= 1300:
  319. sizes.append(i*times)
  320. sizes.sort(key=lambda x: x, reverse=True)
  321. min_len = 10000
  322. best_height = sizes[0]
  323. for height in sizes:
  324. if abs(image_np.shape[0] - height) < min_len:
  325. min_len = abs(image_np.shape[0] - height)
  326. best_height = height
  327. min_len = 10000
  328. best_width = sizes[0]
  329. for width in sizes:
  330. if abs(image_np.shape[1] - width) < min_len:
  331. min_len = abs(image_np.shape[1] - width)
  332. best_width = width
  333. return best_height, best_width
  334. def get_best_predict_size2(image_np, threshold=3000):
  335. h, w = image_np.shape[:2]
  336. scale = threshold / max(h, w)
  337. h = int(h * scale)
  338. w = int(w * scale)
  339. return h, w
  340. def image_slice(image_np):
  341. """
  342. slice the image if the height is to large
  343. :return:
  344. """
  345. _sum = np.average(image_np, axis=1)
  346. list_white_line = []
  347. list_ave = list(_sum)
  348. for _i in range(len(list_ave)):
  349. if (list_ave[_i] > 250).all():
  350. list_white_line.append(_i)
  351. set_white_line = set(list_white_line)
  352. width = image_np.shape[1]
  353. height = image_np.shape[0]
  354. list_images = []
  355. _begin = 0
  356. _end = 0
  357. while 1:
  358. if _end > height:
  359. break
  360. _end += width
  361. while 1:
  362. if _begin in set_white_line:
  363. break
  364. if _begin > height:
  365. break
  366. _begin += 1
  367. _image = image_np[_begin:_end, ...]
  368. list_images.append(_image)
  369. _begin = _end
  370. log("image_slice into %d parts" % (len(list_images)))
  371. return list_images
  372. def image_slice_new(image_np):
  373. """
  374. 长图分割
  375. :return:
  376. """
  377. height, width = image_np.shape[:2]
  378. image_origin = copy.deepcopy(image_np)
  379. # 去除黑边
  380. image_np = remove_black_border(image_np)
  381. # 1. 转化成灰度图
  382. image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  383. # 2. 二值化
  384. ret, binary = cv2.threshold(image_np, 125, 255, cv2.THRESH_BINARY_INV)
  385. # 3. 膨胀和腐蚀操作的核函数
  386. kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  387. # 4. 膨胀一次,让轮廓突出
  388. dilation = cv2.dilate(binary, kernal, iterations=1)
  389. # dilation = np.add(np.int0(np.full(dilation.shape, 255)), -1 * np.int0(dilation))
  390. # dilation = np.uint8(dilation)
  391. # cv2.namedWindow("dilation", 0)
  392. # cv2.resizeWindow("dilation", 1000, 800)
  393. # cv2.imshow("dilation", dilation)
  394. # cv2.waitKey(0)
  395. # cv2.imwrite("error.jpg", dilation)
  396. # 按行求平均
  397. width_avg = np.average(np.float32(dilation), axis=1)
  398. zero_index = np.where(width_avg == 0.)[0]
  399. # print(height, width)
  400. # print(width_avg)
  401. # print(width_avg.shape)
  402. # print(zero_index)
  403. # print(zero_index.shape)
  404. # zero_index.sort(key=lambda x: x)
  405. # 截取范围内寻找分割点
  406. max_distance = int(width / 2)
  407. image_list = []
  408. last_h = 0
  409. for i in range(height // width + 1):
  410. h = last_h + width
  411. # 前后的分割点
  412. zero_h_after = zero_index[np.where(zero_index >= h)]
  413. zero_h_before = zero_index[np.where(zero_index <= h)]
  414. # print("last_h, h", last_h, h)
  415. # print("last_h, h", last_h, h)
  416. # print(zero_index.shape)
  417. # print("zero_h_after.shape", zero_h_after.shape)
  418. if zero_h_after.shape[0] == 0:
  419. # 最后一截
  420. last_image = image_origin[last_h:, :, :]
  421. if last_image.shape[0] <= max_distance:
  422. image_list[-1] = np.concatenate([image_list[-1], last_image], axis=0)
  423. else:
  424. image_list.append(last_image)
  425. break
  426. # 分割点距离不能太远
  427. cut_h = zero_h_after.tolist()[0]
  428. if abs(h - cut_h) <= max_distance:
  429. image_list.append(image_origin[last_h:cut_h, :, :])
  430. last_h = cut_h
  431. # 后面找不到往前找
  432. else:
  433. cut_h = zero_h_before.tolist()[-1]
  434. if abs(cut_h - h) <= max_distance:
  435. image_list.append(image_origin[last_h:cut_h, :, :])
  436. last_h = cut_h
  437. # i = 0
  438. # for im in image_list:
  439. # print(im.shape)
  440. # cv2.imwrite("error" + str(i) + ".jpg", im)
  441. # i += 1
  442. # cv2.namedWindow("im", 0)
  443. # cv2.resizeWindow("im", 1000, 800)
  444. # cv2.imshow("im", im)
  445. # cv2.waitKey(0)
  446. log("image_slice into %d parts" % (len(image_list)))
  447. return image_list
  448. def need_image_slice(image_np):
  449. h, w = image_np.shape[:2]
  450. # if h > 3000 and w < 2000:
  451. # return True
  452. if 2. <= h / w and w >= 100:
  453. return True
  454. return False
  455. def remove_black_border(img_np):
  456. try:
  457. # 阈值
  458. threshold = 100
  459. # 转换为灰度图像
  460. gray = cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
  461. # 获取图片尺寸
  462. h, w = gray.shape[:2]
  463. # 无法区分黑色区域超过一半的情况
  464. rowc = gray[:, int(1/2*w)]
  465. colc = gray[int(1/2*h), :]
  466. rowflag = np.argwhere(rowc > threshold)
  467. colflag = np.argwhere(colc > threshold)
  468. left, bottom, right, top = rowflag[0, 0], colflag[-1, 0], rowflag[-1, 0], colflag[0, 0]
  469. # cv2.imshow('remove_black_border', img_np[left:right, top:bottom, :])
  470. # cv2.waitKey()
  471. return img_np[left:right, top:bottom, :]
  472. except:
  473. return img_np
  474. class ImageConvert:
  475. def __init__(self, path, unique_type_dir):
  476. from format_convert.convert_tree import _Document
  477. self._doc = _Document(path)
  478. self.path = path
  479. self.unique_type_dir = unique_type_dir
  480. def init_package(self):
  481. # 各个包初始化
  482. try:
  483. with open(self.path, "rb") as f:
  484. self.image = f.read()
  485. except:
  486. log("cannot open image!")
  487. traceback.print_exc()
  488. self._doc.error_code = [-3]
  489. def convert(self):
  490. from format_convert.convert_tree import _Page, _Image
  491. self.init_package()
  492. if self._doc.error_code is not None:
  493. return
  494. _page = _Page(None, 0)
  495. _image = _Image(self.image, self.path)
  496. _page.add_child(_image)
  497. self._doc.add_child(_page)
  498. def get_html(self):
  499. try:
  500. self.convert()
  501. except:
  502. traceback.print_exc()
  503. self._doc.error_code = [-1]
  504. if self._doc.error_code is not None:
  505. return self._doc.error_code
  506. return self._doc.get_html()
  507. def image_process_old(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  508. from format_convert.convert_tree import _Table, _Sentence
  509. def get_cluster(t_list, b_list, axis):
  510. zip_list = list(zip(t_list, b_list))
  511. if len(zip_list) == 0:
  512. return t_list, b_list
  513. if len(zip_list[0]) > 0:
  514. zip_list.sort(key=lambda x: x[1][axis][1])
  515. cluster_list = []
  516. margin = 5
  517. for text, bbox in zip_list:
  518. _find = 0
  519. for cluster in cluster_list:
  520. if abs(cluster[1] - bbox[axis][1]) <= margin:
  521. cluster[0].append([text, bbox])
  522. cluster[1] = bbox[axis][1]
  523. _find = 1
  524. break
  525. if not _find:
  526. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  527. new_text_list = []
  528. new_bbox_list = []
  529. for cluster in cluster_list:
  530. # print("=============convert_image")
  531. # print("cluster_list", cluster)
  532. center_y = 0
  533. for text, bbox in cluster[0]:
  534. center_y += bbox[axis][1]
  535. center_y = int(center_y / len(cluster[0]))
  536. for text, bbox in cluster[0]:
  537. bbox[axis][1] = center_y
  538. new_text_list.append(text)
  539. new_bbox_list.append(bbox)
  540. # print("cluster_list", cluster)
  541. return new_text_list, new_bbox_list
  542. def merge_textbox(textbox_list, in_objs):
  543. delete_obj = []
  544. threshold = 5
  545. textbox_list.sort(key=lambda x:x.bbox[0])
  546. for k in range(len(textbox_list)):
  547. tb1 = textbox_list[k]
  548. if tb1 not in in_objs and tb1 not in delete_obj:
  549. for m in range(k+1, len(textbox_list)):
  550. tb2 = textbox_list[m]
  551. if tb2 in in_objs:
  552. continue
  553. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  554. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  555. if tb1.bbox[0] <= tb2.bbox[0]:
  556. tb1.text = tb1.text + tb2.text
  557. else:
  558. tb1.text = tb2.text + tb1.text
  559. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  560. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  561. delete_obj.append(tb2)
  562. for _obj in delete_obj:
  563. if _obj in textbox_list:
  564. textbox_list.remove(_obj)
  565. return textbox_list
  566. log("into image_preprocess")
  567. try:
  568. if image_np is None:
  569. return []
  570. # 整体分辨率限制
  571. if image_np.shape[0] > 2000 or image_np.shape[1] > 2000:
  572. h, w = get_best_predict_size2(image_np, threshold=2000)
  573. log("global image resize " + str(image_np.shape[:2]) + " -> " + str(h) + "," + str(w))
  574. image_np = pil_resize(image_np, h, w)
  575. # 图片倾斜校正,写入原来的图片路径
  576. # print("image_process", image_path)
  577. g_r_i = get_rotated_image(image_np, image_path)
  578. if judge_error_code(g_r_i):
  579. if is_from_docx:
  580. return []
  581. else:
  582. return g_r_i
  583. image_np = cv2.imread(image_path)
  584. image_np_copy = copy.deepcopy(image_np)
  585. if image_np is None:
  586. return []
  587. # if image_np is None:
  588. # return []
  589. #
  590. # # idc模型实现图片倾斜校正
  591. # image_resize = pil_resize(image_np, 640, 640)
  592. # image_resize_path = image_path.split(".")[0] + "_resize_idc." + image_path.split(".")[-1]
  593. # cv2.imwrite(image_resize_path, image_resize)
  594. #
  595. # with open(image_resize_path, "rb") as f:
  596. # image_bytes = f.read()
  597. # angle = from_idc_interface(image_bytes)
  598. # if judge_error_code(angle):
  599. # if is_from_docx:
  600. # return []
  601. # else:
  602. # return angle
  603. # # 根据角度旋转
  604. # image_pil = Image.fromarray(image_np)
  605. # image_np = np.array(image_pil.rotate(angle, expand=1))
  606. # # 写入
  607. # idc_path = image_path.split(".")[0] + "_idc." + image_path.split(".")[-1]
  608. # cv2.imwrite(idc_path, image_np)
  609. # isr模型去除印章
  610. _isr_time = time.time()
  611. if count_red_pixel(image_np):
  612. # 红色像素达到一定值才过模型
  613. with open(image_path, "rb") as f:
  614. image_bytes = f.read()
  615. image_np = from_isr_interface(image_bytes)
  616. if judge_error_code(image_np):
  617. if is_from_docx:
  618. return []
  619. else:
  620. return image_np
  621. # [1]代表检测不到印章,直接返回
  622. if isinstance(image_np, list) and image_np == [1]:
  623. log("no seals detected!")
  624. image_np = image_np_copy
  625. else:
  626. isr_path = image_path.split(".")[0] + "_isr." + image_path.split(".")[-1]
  627. cv2.imwrite(isr_path, image_np)
  628. log("isr total time "+str(time.time()-_isr_time))
  629. # otr模型识别表格,需要图片resize成模型所需大小, 写入另一个路径
  630. best_h, best_w = get_best_predict_size(image_np)
  631. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  632. image_resize = pil_resize(image_np, best_h, best_w)
  633. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  634. cv2.imwrite(image_resize_path, image_resize)
  635. # 调用otr模型接口
  636. with open(image_resize_path, "rb") as f:
  637. image_bytes = f.read()
  638. list_line = from_otr_interface(image_bytes, is_from_pdf)
  639. if judge_error_code(list_line):
  640. return list_line
  641. # # 预处理
  642. # if is_from_pdf:
  643. # prob = 0.2
  644. # else:
  645. # prob = 0.5
  646. # with open(image_resize_path, "rb") as f:
  647. # image_bytes = f.read()
  648. # img_new, inputs = table_preprocess(image_bytes, prob)
  649. # if type(img_new) is list and judge_error_code(img_new):
  650. # return img_new
  651. # log("img_new.shape " + str(img_new.shape))
  652. #
  653. # # 调用模型运行接口
  654. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  655. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  656. # if judge_error_code(result):
  657. # logging.error("from_gpu_interface failed! " + str(result))
  658. # raise requests.exceptions.RequestException
  659. #
  660. # pred = result.get("preds")
  661. # gpu_time = result.get("gpu_time")
  662. # log("otr model predict time " + str(gpu_time))
  663. #
  664. # # # 解压numpy
  665. # # decompressed_array = io.BytesIO()
  666. # # decompressed_array.write(pred)
  667. # # decompressed_array.seek(0)
  668. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  669. # # log("inputs.shape" + str(pred.shape))
  670. #
  671. # 调用gpu共享内存处理
  672. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  673. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  674. # if judge_error_code(result):
  675. # logging.error("from_gpu_interface failed! " + str(result))
  676. # raise requests.exceptions.RequestException
  677. #
  678. # pred = result.get("preds")
  679. # gpu_time = result.get("gpu_time")
  680. # log("otr model predict time " + str(gpu_time))
  681. #
  682. # # 后处理
  683. # list_line = table_postprocess(img_new, pred, prob)
  684. # log("len(list_line) " + str(len(list_line)))
  685. # if judge_error_code(list_line):
  686. # return list_line
  687. # otr resize后得到的bbox根据比例还原
  688. start_time = time.time()
  689. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  690. for i in range(len(list_line)):
  691. point = list_line[i]
  692. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  693. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  694. log("otr resize bbox recover " + str(time.time()-start_time))
  695. # ocr图片过大内存溢出,需resize
  696. start_time = time.time()
  697. threshold = 3000
  698. ocr_resize_flag = 0
  699. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  700. ocr_resize_flag = 1
  701. best_h, best_w = get_best_predict_size2(image_np, threshold)
  702. # image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  703. image_resize = pil_resize(image_np, best_h, best_w)
  704. log("ocr_process image resize " + str(image_resize.shape))
  705. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  706. cv2.imwrite(image_resize_path, image_resize)
  707. log("ocr resize before " + str(time.time()-start_time))
  708. # 调用ocr模型接口
  709. with open(image_resize_path, "rb") as f:
  710. image_bytes = f.read()
  711. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  712. if judge_error_code(text_list):
  713. return text_list
  714. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  715. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  716. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  717. # # 循环每张图片识别结果
  718. # text_list = []
  719. # bbox_list = []
  720. # for line in results:
  721. # # print("ocr_interface line", line)
  722. # text_list.append(line[-1][0])
  723. # bbox_list.append(line[0])
  724. # if len(text_list) == 0:
  725. # return []
  726. # ocr resize后的bbox还原
  727. if ocr_resize_flag:
  728. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  729. else:
  730. ratio = (1, 1)
  731. for i in range(len(bbox_list)):
  732. point = bbox_list[i]
  733. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  734. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  735. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  736. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  737. # 调用现成方法形成表格
  738. try:
  739. from format_convert.convert_tree import TableLine
  740. list_lines = []
  741. for line in list_line:
  742. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  743. from format_convert.convert_tree import TextBox
  744. list_text_boxes = []
  745. for i in range(len(bbox_list)):
  746. bbox = bbox_list[i]
  747. b_text = text_list[i]
  748. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  749. bbox[2][0], bbox[2][1]], b_text))
  750. # for _textbox in list_text_boxes:
  751. # print("==",_textbox.get_text())
  752. lt = LineTable()
  753. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  754. # 合并同一行textbox
  755. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  756. obj_list = []
  757. for table in tables:
  758. obj_list.append(_Table(table["table"], table["bbox"]))
  759. for text_box in list_text_boxes:
  760. if text_box not in obj_in_table:
  761. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  762. return obj_list
  763. except:
  764. traceback.print_exc()
  765. return [-8]
  766. except Exception as e:
  767. log("image_preprocess error")
  768. traceback.print_exc()
  769. return [-1]
  770. if __name__ == "__main__":
  771. image_slice_new(cv2.imread("C:/Users/Administrator/Desktop/test_image/1653566873838.png"))