convert_image.py 32 KB

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