convert_image.py 32 KB

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