table_line_new.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. import copy
  2. import time
  3. import traceback
  4. import numpy as np
  5. import cv2
  6. import matplotlib.pyplot as plt
  7. from format_convert.utils import log, pil_resize, memory_decorator
  8. def table_line(img, model, size=(512, 1024), prob=0.2, is_test=0):
  9. log("into table_line, prob is " + str(prob))
  10. # resize
  11. w, h = size
  12. img_new = pil_resize(img, h, w)
  13. img_show = copy.deepcopy(img_new)
  14. # predict
  15. start_time = time.time()
  16. pred = model.predict(np.array([img_new]))
  17. pred = pred[0]
  18. log("otr model predict time " + str(time.time() - start_time))
  19. # show
  20. show(pred, title='pred', prob=prob, mode=1, is_test=is_test)
  21. # 根据点获取线
  22. start_time = time.time()
  23. line_list = points2lines(pred, False, prob=prob)
  24. log("points2lines " + str(time.time() - start_time))
  25. if not line_list:
  26. return []
  27. show(line_list, title="points2lines", mode=2, is_test=is_test)
  28. # 清除短线
  29. start_time = time.time()
  30. line_list = delete_short_lines(line_list, img_new.shape)
  31. show(line_list, title="delete_short_lines", mode=2, is_test=is_test)
  32. log("delete_short_lines " + str(time.time() - start_time))
  33. # 分成横竖线
  34. start_time = time.time()
  35. row_line_list = []
  36. col_line_list = []
  37. for line in line_list:
  38. if line[0] == line[2]:
  39. col_line_list.append(line)
  40. elif line[1] == line[3]:
  41. row_line_list.append(line)
  42. log("divide rows and cols " + str(time.time() - start_time))
  43. # 两种线都需要存在,否则跳过
  44. if not row_line_list or not col_line_list:
  45. return []
  46. # 合并错开线
  47. start_time = time.time()
  48. row_line_list = merge_line(row_line_list, axis=0)
  49. col_line_list = merge_line(col_line_list, axis=1)
  50. show(row_line_list + col_line_list, title="merge_line", mode=2, is_test=is_test)
  51. log("merge_line " + str(time.time() - start_time))
  52. # 计算交点
  53. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  54. if not cross_points:
  55. return []
  56. # 删除无交点线 需重复两次才删的干净
  57. row_line_list, col_line_list = delete_single_lines(row_line_list, col_line_list, cross_points)
  58. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  59. row_line_list, col_line_list = delete_single_lines(row_line_list, col_line_list, cross_points)
  60. if not row_line_list or not col_line_list:
  61. return []
  62. # 多个表格分割线,获取多个表格区域
  63. start_time = time.time()
  64. split_lines, split_y = get_split_line(cross_points, col_line_list, img_new)
  65. area_row_line_list, area_col_line_list, area_point_list = get_split_area(split_y, row_line_list, col_line_list, cross_points)
  66. log("get_split_area " + str(time.time() - start_time))
  67. # 根据区域循环
  68. need_split_flag = False
  69. for i in range(len(area_point_list)):
  70. sub_row_line_list = area_row_line_list[i]
  71. sub_col_line_list = area_col_line_list[i]
  72. sub_point_list = area_point_list[i]
  73. # 修复边框
  74. start_time = time.time()
  75. new_rows, new_cols, long_rows, long_cols = fix_outline(img_new,
  76. sub_row_line_list,
  77. sub_col_line_list,
  78. sub_point_list)
  79. # 如有补线
  80. if new_rows or new_cols:
  81. # 连接至补线的延长线
  82. if long_rows:
  83. sub_row_line_list = long_rows
  84. if long_cols:
  85. sub_col_line_list = long_cols
  86. # 新的补线
  87. if new_rows:
  88. sub_row_line_list += new_rows
  89. if new_cols:
  90. sub_col_line_list += new_cols
  91. need_split_flag = True
  92. area_row_line_list[i] = sub_row_line_list
  93. area_col_line_list[i] = sub_col_line_list
  94. row_line_list = [y for x in area_row_line_list for y in x]
  95. col_line_list = [y for x in area_col_line_list for y in x]
  96. if need_split_flag:
  97. # 修复边框后重新计算交点
  98. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  99. split_lines, split_y = get_split_line(cross_points, col_line_list, img_new)
  100. area_row_line_list, area_col_line_list, area_point_list = get_split_area(split_y, row_line_list, col_line_list, cross_points)
  101. show(cross_points, title="get_points", img=img_show, mode=4, is_test=is_test)
  102. show(split_lines, title="split_lines", img=img_show, mode=3, is_test=is_test)
  103. show(row_line_list + col_line_list, title="fix_outline", mode=2, is_test=is_test)
  104. log("fix_outline " + str(time.time() - start_time))
  105. # 根据区域循环
  106. for i in range(len(area_point_list)):
  107. sub_row_line_list = area_row_line_list[i]
  108. sub_col_line_list = area_col_line_list[i]
  109. sub_point_list = area_point_list[i]
  110. # 验证轮廓的4个交点
  111. sub_row_line_list, sub_col_line_list = fix_4_points(sub_point_list, sub_row_line_list, sub_col_line_list)
  112. # 把四个边线在加一次
  113. sub_point_list = get_points(sub_row_line_list, sub_col_line_list, (img_new.shape[0], img_new.shape[1]))
  114. sub_row_line_list, sub_col_line_list = add_outline(sub_point_list, sub_row_line_list, sub_col_line_list)
  115. # 修复内部缺线
  116. start_time = time.time()
  117. sub_row_line_list, sub_col_line_list = fix_inner(sub_row_line_list, sub_col_line_list, sub_point_list)
  118. log("fix_inner " + str(time.time() - start_time))
  119. show(sub_row_line_list + sub_col_line_list, title="fix_inner1", mode=2, is_test=is_test)
  120. # 合并错开
  121. start_time = time.time()
  122. sub_row_line_list = merge_line(sub_row_line_list, axis=0)
  123. sub_col_line_list = merge_line(sub_col_line_list, axis=1)
  124. log("merge_line " + str(time.time() - start_time))
  125. show(sub_row_line_list + sub_col_line_list, title="merge_line", mode=2, is_test=is_test)
  126. # 修复内部线后重新计算交点
  127. start_time = time.time()
  128. cross_points = get_points(sub_row_line_list, sub_col_line_list, (img_new.shape[0], img_new.shape[1]))
  129. show(cross_points, title="get_points3", img=img_show, mode=4, is_test=is_test)
  130. # 消除线突出,获取标准的线
  131. area_row_line_list[i], area_col_line_list[i] = get_standard_lines(sub_row_line_list, sub_col_line_list)
  132. show(area_row_line_list[i] + area_col_line_list[i], title="get_standard_lines", mode=2, is_test=is_test)
  133. row_line_list = [y for x in area_row_line_list for y in x]
  134. col_line_list = [y for x in area_col_line_list for y in x]
  135. line_list = row_line_list + col_line_list
  136. # 打印处理后线
  137. show(line_list, title="all", img=img_show, mode=5, is_test=is_test)
  138. log("otr postprocess table_line " + str(time.time() - start_time))
  139. return line_list
  140. @memory_decorator
  141. def table_line_pdf_post_process(line_list, page_w, page_h, is_test=0):
  142. log('into table_line_pdf_post_process')
  143. for i, line in enumerate(line_list):
  144. line_list[i] = [int(x) for x in line]
  145. # log('pdf img_new h w ' + str(int(page_h+1)) + ' ' + str(int(page_w+1)))
  146. img_new = np.full([int(page_h+1), int(page_w+1), 3], 255, dtype=np.uint8)
  147. # log('pdf np.full')
  148. img_show = copy.deepcopy(img_new)
  149. # log('pdf copy.deepcopy')
  150. show(line_list, title="table_line_pdf start", mode=2, is_test=is_test)
  151. # 分成横竖线
  152. start_time = time.time()
  153. row_line_list = []
  154. col_line_list = []
  155. for line in line_list:
  156. # 可能有斜线
  157. if line[0] == line[2]:
  158. col_line_list.append(line)
  159. elif line[1] == line[3]:
  160. row_line_list.append(line)
  161. else:
  162. if is_test:
  163. print(line)
  164. # log("pdf divide rows and cols " + str(time.time() - start_time))
  165. show(row_line_list + col_line_list, title="divide", mode=2, is_test=is_test)
  166. # 两种线都需要存在,否则跳过
  167. if not row_line_list or not col_line_list:
  168. return []
  169. # 合并线
  170. row_line_list = merge_line(row_line_list, axis=0)
  171. col_line_list = merge_line(col_line_list, axis=1)
  172. # log("pdf merge_line1 " + str(time.time() - start_time))
  173. show(row_line_list + col_line_list, title="merge", mode=2, is_test=is_test)
  174. # 计算交点
  175. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  176. if not cross_points:
  177. return []
  178. show(cross_points, title="get_points", img=img_show, mode=4, is_test=is_test)
  179. # 多个表格分割线,获取多个表格区域
  180. start_time = time.time()
  181. split_lines, split_y = get_split_line(cross_points, col_line_list, img_new)
  182. area_row_line_list, area_col_line_list, area_point_list = get_split_area(split_y, row_line_list, col_line_list, cross_points)
  183. # log("pdf get_split_area " + str(time.time() - start_time))
  184. show(split_lines, title="split_lines", img=img_show, mode=3, is_test=is_test)
  185. if is_test:
  186. print('area_point_list', area_point_list)
  187. print('cross_points', cross_points)
  188. # 特殊情况 - 一页只有1条横线多条竖线,需补横线
  189. if not area_point_list and len(cross_points) >= 3 and len(row_line_list) == 1 and len(col_line_list) >= 3:
  190. row_line_list = fix_one_row_outline(row_line_list, col_line_list, cross_points)
  191. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  192. if not cross_points:
  193. return []
  194. show(cross_points, title="get_points22", img=img_show, mode=4, is_test=is_test)
  195. # 多个表格分割线,获取多个表格区域
  196. start_time = time.time()
  197. split_lines, split_y = get_split_line(cross_points, col_line_list, img_new)
  198. area_row_line_list, area_col_line_list, area_point_list = get_split_area(split_y, row_line_list, col_line_list, cross_points)
  199. # log("pdf get_split_area " + str(time.time() - start_time))
  200. show(split_lines, title="split_lines22", img=img_show, mode=3, is_test=is_test)
  201. # 根据区域循环
  202. need_split_flag = False
  203. for i in range(len(area_point_list)):
  204. sub_row_line_list = area_row_line_list[i]
  205. sub_col_line_list = area_col_line_list[i]
  206. sub_point_list = area_point_list[i]
  207. # 修复边框
  208. start_time = time.time()
  209. new_rows, new_cols, long_rows, long_cols = fix_outline(img_new,
  210. sub_row_line_list,
  211. sub_col_line_list,
  212. sub_point_list,
  213. pdf_line_mode=1)
  214. # log("pdf fix_outline1 " + str(time.time() - start_time))
  215. # 如有补线
  216. if new_rows or new_cols:
  217. # 连接至补线的延长线
  218. if long_rows:
  219. sub_row_line_list = long_rows
  220. if long_cols:
  221. sub_col_line_list = long_cols
  222. # 新的补线
  223. if new_rows:
  224. sub_row_line_list += new_rows
  225. if new_cols:
  226. sub_col_line_list += new_cols
  227. need_split_flag = True
  228. area_row_line_list[i] = sub_row_line_list
  229. area_col_line_list[i] = sub_col_line_list
  230. show(sub_row_line_list + sub_col_line_list, title="fix_outline", mode=2, is_test=is_test)
  231. row_line_list = [y for x in area_row_line_list for y in x]
  232. col_line_list = [y for x in area_col_line_list for y in x]
  233. if need_split_flag:
  234. # 修复边框后重新计算交点
  235. cross_points = get_points(row_line_list, col_line_list, (img_new.shape[0], img_new.shape[1]))
  236. split_lines, split_y = get_split_line(cross_points, col_line_list, img_new)
  237. area_row_line_list, area_col_line_list, area_point_list = get_split_area(split_y, row_line_list, col_line_list, cross_points)
  238. # log("pdf fix_outline2 " + str(time.time() - start_time))
  239. # 根据区域循环
  240. for i in range(len(area_point_list)):
  241. sub_row_line_list = area_row_line_list[i]
  242. sub_col_line_list = area_col_line_list[i]
  243. sub_point_list = area_point_list[i]
  244. # 验证轮廓的4个交点
  245. sub_row_line_list, sub_col_line_list = fix_4_points(sub_point_list, sub_row_line_list, sub_col_line_list)
  246. # log("pdf fix_4_points " + str(time.time() - start_time))
  247. # 把四个边线在加一次
  248. sub_point_list = get_points(sub_row_line_list, sub_col_line_list, (img_new.shape[0], img_new.shape[1]))
  249. sub_row_line_list, sub_col_line_list = add_outline(sub_point_list, sub_row_line_list, sub_col_line_list)
  250. # 修复内部缺线
  251. start_time = time.time()
  252. sub_row_line_list, sub_col_line_list = fix_inner(sub_row_line_list, sub_col_line_list, sub_point_list)
  253. # log("pdf fix_inner " + str(time.time() - start_time))
  254. show(sub_row_line_list + sub_col_line_list, title="fix_inner1", mode=2, is_test=is_test)
  255. # 修复内部线后重新计算交点
  256. start_time = time.time()
  257. cross_points = get_points(sub_row_line_list, sub_col_line_list, (img_new.shape[0], img_new.shape[1]))
  258. show(cross_points, title="get_points3", img=img_show, mode=4, is_test=is_test)
  259. area_point_list[i] = cross_points
  260. # 合并线
  261. area_row_line_list[i] = merge_line(sub_row_line_list, axis=0)
  262. area_col_line_list[i] = merge_line(sub_col_line_list, axis=1)
  263. # log("pdf merge_line2 " + str(time.time() - start_time))
  264. row_line_list = [y for x in area_row_line_list for y in x]
  265. col_line_list = [y for x in area_col_line_list for y in x]
  266. line_list = row_line_list + col_line_list
  267. # 打印处理后线
  268. show(line_list, title="all", img=img_show, mode=5, is_test=is_test)
  269. log("table_line_pdf cost: " + str(time.time() - start_time))
  270. return line_list
  271. def show(pred_or_lines, title='', prob=0.2, img=None, mode=1, is_test=0):
  272. if not is_test:
  273. return
  274. if mode == 1:
  275. plt.figure()
  276. plt.title(title)
  277. _array = []
  278. for _h in range(len(pred_or_lines)):
  279. _line = []
  280. for _w in range(len(pred_or_lines[_h])):
  281. _prob = pred_or_lines[_h][_w]
  282. if _prob[0] > prob:
  283. _line.append((0, 0, 255))
  284. elif _prob[1] > prob:
  285. _line.append((255, 0, 0))
  286. else:
  287. _line.append((255, 255, 255))
  288. _array.append(_line)
  289. # plt.axis('off')
  290. plt.imshow(np.array(_array))
  291. plt.show()
  292. elif mode == 2:
  293. plt.figure()
  294. plt.title(title)
  295. for _line in pred_or_lines:
  296. x0, y0, x1, y1 = _line
  297. plt.plot([x0, x1], [y0, y1])
  298. plt.show()
  299. elif mode == 3:
  300. for _line in pred_or_lines:
  301. x0, y0 = _line[0]
  302. x1, y1 = _line[1]
  303. cv2.line(img, [int(x0), int(y0)], [int(x1), int(y1)], (0, 0, 255), 2)
  304. cv2.namedWindow(title, cv2.WINDOW_NORMAL)
  305. cv2.imshow(title, img)
  306. cv2.waitKey(0)
  307. elif mode == 4:
  308. for point in pred_or_lines:
  309. point = [int(x) for x in point]
  310. cv2.circle(img, (point[0], point[1]), 1, (0, 255, 0), 2)
  311. cv2.namedWindow(title, cv2.WINDOW_NORMAL)
  312. cv2.imshow(title, img)
  313. cv2.waitKey(0)
  314. elif mode == 5:
  315. for _line in pred_or_lines:
  316. x0, y0, x1, y1 = _line
  317. cv2.line(img, [int(x0), int(y0)], [int(x1), int(y1)], (0, 255, 0), 2)
  318. cv2.namedWindow(title, cv2.WINDOW_NORMAL)
  319. cv2.imshow(title, img)
  320. cv2.waitKey(0)
  321. def points2lines(pred, sourceP_LB=True, prob=0.2, line_width=8, padding=3, min_len=10,
  322. cell_width=13):
  323. _time = time.time()
  324. log("starting points2lines")
  325. height = len(pred)
  326. width = len(pred[0])
  327. _sum = list(np.sum(np.array((pred[..., 0] > prob)).astype(int), axis=1))
  328. h_index = -1
  329. h_lines = []
  330. v_lines = []
  331. _step = line_width
  332. while 1:
  333. h_index += 1
  334. if h_index >= height:
  335. break
  336. w_index = -1
  337. if sourceP_LB:
  338. h_i = height - 1 - h_index
  339. else:
  340. h_i = h_index
  341. _start = None
  342. if _sum[h_index] < min_len:
  343. continue
  344. last_back = 0
  345. while 1:
  346. if w_index >= width:
  347. if _start is not None:
  348. _end = w_index - 1
  349. _bbox = [_start, h_i, _end, h_i]
  350. _dict = {"bbox": _bbox}
  351. h_lines.append(_dict)
  352. _start = None
  353. break
  354. _h, _v = pred[h_i][w_index]
  355. if _h > prob:
  356. if _start is None:
  357. _start = w_index
  358. w_index += _step
  359. else:
  360. if _start is not None:
  361. _end = w_index - 1
  362. _bbox = [_start, h_i, _end, h_i]
  363. _dict = {"bbox": _bbox}
  364. h_lines.append(_dict)
  365. _start = None
  366. w_index -= _step // 2
  367. if w_index <= last_back:
  368. w_index = last_back + _step // 2
  369. last_back = w_index
  370. log("starting points2lines 1")
  371. w_index = -1
  372. _sum = list(np.sum(np.array((pred[..., 1] > prob)).astype(int), axis=0))
  373. _step = line_width
  374. while 1:
  375. w_index += 1
  376. if w_index >= width:
  377. break
  378. if _sum[w_index] < min_len:
  379. continue
  380. h_index = -1
  381. _start = None
  382. last_back = 0
  383. list_test = []
  384. list_lineprob = []
  385. while 1:
  386. if h_index >= height:
  387. if _start is not None:
  388. _end = last_h
  389. _bbox = [w_index, _start, w_index, _end]
  390. _dict = {"bbox": _bbox}
  391. v_lines.append(_dict)
  392. _start = None
  393. list_test.append(_dict)
  394. break
  395. if sourceP_LB:
  396. h_i = height - 1 - h_index
  397. else:
  398. h_i = h_index
  399. _h, _v = pred[h_index][w_index]
  400. list_lineprob.append((h_index, _v))
  401. if _v > prob:
  402. if _start is None:
  403. _start = h_i
  404. h_index += _step
  405. else:
  406. if _start is not None:
  407. _end = last_h
  408. _bbox = [w_index, _start, w_index, _end]
  409. _dict = {"bbox": _bbox}
  410. v_lines.append(_dict)
  411. _start = None
  412. list_test.append(_dict)
  413. h_index -= _step // 2
  414. if h_index <= last_back:
  415. h_index = last_back + _step // 2
  416. last_back = h_index
  417. last_h = h_i
  418. log("starting points2lines 2")
  419. for _line in h_lines:
  420. _bbox = _line["bbox"]
  421. _bbox = [max(_bbox[0] - 2, 0), (_bbox[1] + _bbox[3]) / 2, _bbox[2] + 2, (_bbox[1] + _bbox[3]) / 2]
  422. _line["bbox"] = _bbox
  423. for _line in v_lines:
  424. _bbox = _line["bbox"]
  425. _bbox = [(_bbox[0] + _bbox[2]) / 2, max(_bbox[1] - 2, 0), (_bbox[0] + _bbox[2]) / 2, _bbox[3] + 2]
  426. _line["bbox"] = _bbox
  427. h_lines = lines_cluster(h_lines, line_width=line_width)
  428. v_lines = lines_cluster(v_lines, line_width=line_width)
  429. list_line = []
  430. for _line in h_lines:
  431. _bbox = _line["bbox"]
  432. _bbox = [max(_bbox[0] - 1, 0), (_bbox[1] + _bbox[3]) / 2, _bbox[2] + 1, (_bbox[1] + _bbox[3]) / 2]
  433. list_line.append(_bbox)
  434. for _line in v_lines:
  435. _bbox = _line["bbox"]
  436. _bbox = [(_bbox[0] + _bbox[2]) / 2, max(_bbox[1] - 1, 0), (_bbox[0] + _bbox[2]) / 2, _bbox[3] + 1]
  437. list_line.append(_bbox)
  438. log("points2lines cost %.2fs" % (time.time() - _time))
  439. # import matplotlib.pyplot as plt
  440. # plt.figure()
  441. # for _line in list_line:
  442. # x0,y0,x1,y1 = _line
  443. # plt.plot([x0,x1],[y0,y1])
  444. # for _line in list_line:
  445. # x0,y0,x1,y1 = _line.bbox
  446. # plt.plot([x0,x1],[y0,y1])
  447. # for point in list_crosspoints:
  448. # plt.scatter(point.get("point")[0],point.get("point")[1])
  449. # plt.show()
  450. return list_line
  451. def lines_cluster(list_lines, line_width):
  452. after_len = 0
  453. prelength = len(list_lines)
  454. append_width = line_width // 2
  455. while 1:
  456. c_lines = []
  457. first_len = after_len
  458. for _line in list_lines:
  459. bbox = _line["bbox"]
  460. _find = False
  461. for c_l_i in range(len(c_lines)):
  462. c_l = c_lines[len(c_lines) - c_l_i - 1]
  463. bbox1 = c_l["bbox"]
  464. bboxa = [max(0, bbox[0] - append_width), max(0, bbox[1] - append_width), bbox[2] + append_width,
  465. bbox[3] + append_width]
  466. bboxb = [max(0, bbox1[0] - append_width), max(0, bbox1[1] - append_width), bbox1[2] + append_width,
  467. bbox1[3] + append_width]
  468. _iou = getIOU(bboxa, bboxb)
  469. if _iou > 0:
  470. new_bbox = [min(bbox[0], bbox[2], bbox1[0], bbox1[2]), min(bbox[1], bbox[3], bbox1[1], bbox1[3]),
  471. max(bbox[0], bbox[2], bbox1[0], bbox1[2]), max(bbox[1], bbox[3], bbox1[1], bbox1[3])]
  472. _find = True
  473. c_l["bbox"] = new_bbox
  474. break
  475. if not _find:
  476. c_lines.append(_line)
  477. after_len = len(c_lines)
  478. if first_len == after_len:
  479. break
  480. list_lines = c_lines
  481. log("cluster lines from %d to %d" % (prelength, len(list_lines)))
  482. return c_lines
  483. def getIOU(bbox0, bbox1):
  484. width = abs(max(bbox0[2], bbox1[2]) - min(bbox0[0], bbox1[0])) - (
  485. abs(bbox0[2] - bbox0[0]) + abs(bbox1[2] - bbox1[0]))
  486. height = abs(max(bbox0[3], bbox1[3]) - min(bbox0[1], bbox1[1])) - (
  487. abs(bbox0[3] - bbox0[1]) + abs(bbox1[3] - bbox1[1]))
  488. if width <= 0 and height <= 0:
  489. iou = abs(width * height / min(abs((bbox0[2] - bbox0[0]) * (bbox0[3] - bbox0[1])),
  490. abs((bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))))
  491. # print("getIOU", iou)
  492. return iou + 0.1
  493. return 0
  494. def delete_short_lines(list_lines, image_shape, scale=100):
  495. # 排除太短的线
  496. x_min_len = max(5, int(image_shape[0] / scale))
  497. y_min_len = max(5, int(image_shape[1] / scale))
  498. new_list_lines = []
  499. for line in list_lines:
  500. if line[0] == line[2]:
  501. if abs(line[3] - line[1]) >= y_min_len:
  502. # print("y_min_len", abs(line[3] - line[1]), y_min_len)
  503. new_list_lines.append(line)
  504. else:
  505. if abs(line[2] - line[0]) >= x_min_len:
  506. # print("x_min_len", abs(line[2] - line[0]), x_min_len)
  507. new_list_lines.append(line)
  508. return new_list_lines
  509. def delete_single_lines(row_line_list, col_line_list, point_list):
  510. new_col_line_list = []
  511. min_point_cnt = 2
  512. for line in col_line_list:
  513. p_cnt = 0
  514. for p in point_list:
  515. # if line[0] == p[0] and line[1] <= p[1] <= line[3]:
  516. if line[0] == p[0]:
  517. p_cnt += 1
  518. if p_cnt >= min_point_cnt:
  519. new_col_line_list.append(line)
  520. break
  521. new_row_line_list = []
  522. for line in row_line_list:
  523. p_cnt = 0
  524. for p in point_list:
  525. # if line[1] == p[1] and line[0] <= p[0] <= line[2]:
  526. if line[1] == p[1]:
  527. p_cnt += 1
  528. if p_cnt >= min_point_cnt:
  529. new_row_line_list.append(line)
  530. break
  531. return new_row_line_list, new_col_line_list
  532. @memory_decorator
  533. def merge_line(lines, axis, threshold=5):
  534. """
  535. 解决模型预测一条直线错开成多条直线,合并成一条直线
  536. :param lines: 线条列表
  537. :param axis: 0:横线 1:竖线
  538. :param threshold: 两条线间像素差阈值
  539. :return: 合并后的线条列表
  540. """
  541. # 任意一条line获取该合并的line,横线往下找,竖线往右找
  542. start_time = time.time()
  543. lines.sort(key=lambda x: (x[axis], x[1 - axis]))
  544. merged_lines = []
  545. used_lines = []
  546. for line1 in lines:
  547. if line1 in used_lines:
  548. continue
  549. merged_line = [line1]
  550. used_lines.append(line1)
  551. for line2 in lines:
  552. if line2 in used_lines:
  553. continue
  554. if line1[1 - axis] - threshold <= line2[1 - axis] <= line1[1 - axis] + threshold:
  555. # 计算基准长度
  556. min_axis = 10000
  557. max_axis = 0
  558. for line3 in merged_line:
  559. if line3[axis] < min_axis:
  560. min_axis = line3[axis]
  561. if line3[axis + 2] > max_axis:
  562. max_axis = line3[axis + 2]
  563. # 判断两条线有无交集
  564. if min_axis <= line2[axis] <= max_axis \
  565. or min_axis <= line2[axis + 2] <= max_axis:
  566. merged_line.append(line2)
  567. used_lines.append(line2)
  568. if merged_line:
  569. merged_lines.append(merged_line)
  570. # 合并line
  571. result_lines = []
  572. for merged_line in merged_lines:
  573. # 获取line宽的平均值
  574. axis_average = 0
  575. for line in merged_line:
  576. axis_average += line[1 - axis]
  577. axis_average = int(axis_average / len(merged_line))
  578. # 获取最长line两端
  579. merged_line.sort(key=lambda x: (x[axis]))
  580. axis_start = merged_line[0][axis]
  581. merged_line.sort(key=lambda x: (x[axis + 2]))
  582. axis_end = merged_line[-1][axis + 2]
  583. if axis:
  584. result_lines.append([axis_average, axis_start, axis_average, axis_end])
  585. else:
  586. result_lines.append([axis_start, axis_average, axis_end, axis_average])
  587. log('merge_line2 cost: ' + str(time.time()-start_time))
  588. return result_lines
  589. def get_points(row_lines, col_lines, image_size, threshold=5):
  590. # 创建空图
  591. row_img = np.zeros(image_size, np.uint8)
  592. col_img = np.zeros(image_size, np.uint8)
  593. # 画线
  594. # threshold = 5
  595. for row in row_lines:
  596. cv2.line(row_img, (int(row[0] - threshold), int(row[1])), (int(row[2] + threshold), int(row[3])), (255, 255, 255), 1)
  597. for col in col_lines:
  598. cv2.line(col_img, (int(col[0]), int(col[1] - threshold)), (int(col[2]), int(col[3] + threshold)), (255, 255, 255), 1)
  599. # cv2.imshow('get_points', row_img+col_img)
  600. # cv2.waitKey(0)
  601. # 求出交点
  602. point_img = np.bitwise_and(row_img, col_img)
  603. # cv2.imwrite("get_points.jpg", row_img+col_img)
  604. # cv2.imshow("get_points", row_img+col_img)
  605. # cv2.waitKey(0)
  606. # 识别黑白图中的白色交叉点,将横纵坐标取出
  607. ys, xs = np.where(point_img > 0)
  608. points = []
  609. for i in range(len(xs)):
  610. points.append((xs[i], ys[i]))
  611. points.sort(key=lambda x: (x[0], x[1]))
  612. return points
  613. def fix_outline(image, row_line_list, col_line_list, point_list, scale=25, pdf_line_mode=0):
  614. log("into fix_outline")
  615. x_min_len = max(10, int(image.shape[0] / scale))
  616. y_min_len = max(10, int(image.shape[1] / scale))
  617. if len(row_line_list) <= 1 or len(col_line_list) <= 1:
  618. return [], [], row_line_list, col_line_list
  619. # 预测线取上下左右4个边(会有超出表格部分) [(), ()]
  620. row_line_list.sort(key=lambda x: (x[1], x[0]))
  621. up_line = row_line_list[0]
  622. bottom_line = row_line_list[-1]
  623. col_line_list.sort(key=lambda x: x[0])
  624. left_line = col_line_list[0]
  625. right_line = col_line_list[-1]
  626. # 计算单格高度宽度
  627. if len(row_line_list) > 1:
  628. height_dict = {}
  629. for j in range(len(row_line_list)):
  630. if j + 1 > len(row_line_list) - 1:
  631. break
  632. height = abs(int(row_line_list[j][3] - row_line_list[j + 1][3]))
  633. if height >= 10:
  634. if height in height_dict.keys():
  635. height_dict[height] = height_dict[height] + 1
  636. else:
  637. height_dict[height] = 1
  638. height_list = [[x, height_dict[x]] for x in height_dict.keys()]
  639. if height_list:
  640. height_list.sort(key=lambda x: (x[1], -x[0]), reverse=True)
  641. # print("box_height", height_list)
  642. box_height = height_list[0][0]
  643. else:
  644. box_height = y_min_len
  645. else:
  646. box_height = y_min_len
  647. if len(col_line_list) > 1:
  648. box_width = abs(col_line_list[1][2] - col_line_list[0][2])
  649. else:
  650. box_width = x_min_len
  651. # 设置轮廓线需超出阈值
  652. if box_height >= 2 * y_min_len:
  653. fix_h_len = y_min_len
  654. else:
  655. fix_h_len = box_height * 2 / 3
  656. if pdf_line_mode:
  657. fix_h_len = 15
  658. if box_width >= 2 * x_min_len:
  659. fix_w_len = x_min_len
  660. else:
  661. fix_w_len = box_width * 2 / 3
  662. # 判断超出部分的长度,超出一定长度就补线
  663. new_row_lines = []
  664. new_col_lines = []
  665. all_longer_row_lines = []
  666. all_longer_col_lines = []
  667. # print('box_height, box_width, fix_h_len, fix_w_len', box_height, box_width, fix_h_len, fix_w_len)
  668. # print('bottom_line, left_line, right_line', bottom_line, left_line, right_line)
  669. # 补左右两条竖线超出来的线的row
  670. if up_line[1] - left_line[1] >= fix_h_len and up_line[1] - right_line[1] >= fix_h_len:
  671. if up_line[1] - left_line[1] >= up_line[1] - right_line[1]:
  672. new_row_lines.append([left_line[0], left_line[1], right_line[0], left_line[1]])
  673. new_col_y = left_line[1]
  674. # 补了row,要将其他短的col连到row上
  675. for j in range(len(col_line_list)):
  676. col = col_line_list[j]
  677. if abs(new_col_y - col[1]) <= box_height:
  678. col_line_list[j][1] = min([new_col_y, col[1]])
  679. else:
  680. new_row_lines.append([left_line[0], right_line[1], right_line[0], right_line[1]])
  681. new_col_y = right_line[1]
  682. # 补了row,要将其他短的col连到row上
  683. for j in range(len(col_line_list)):
  684. col = col_line_list[j]
  685. # 且距离不能相差太大
  686. if abs(new_col_y - col[1]) <= box_height:
  687. col_line_list[j][1] = min([new_col_y, col[1]])
  688. if left_line[3] - bottom_line[3] >= fix_h_len and right_line[3] - bottom_line[3] >= fix_h_len:
  689. if left_line[3] - bottom_line[3] >= right_line[3] - bottom_line[3]:
  690. new_row_lines.append([left_line[2], left_line[3], right_line[2], left_line[3]])
  691. new_col_y = left_line[3]
  692. # 补了row,要将其他短的col连到row上
  693. for j in range(len(col_line_list)):
  694. col = col_line_list[j]
  695. # 且距离不能相差太大
  696. if abs(new_col_y - col[3]) <= box_height:
  697. col_line_list[j][3] = max([new_col_y, col[3]])
  698. else:
  699. new_row_lines.append([left_line[2], right_line[3], right_line[2], right_line[3]])
  700. new_col_y = right_line[3]
  701. # 补了row,要将其他短的col连到row上
  702. for j in range(len(col_line_list)):
  703. col = col_line_list[j]
  704. # 且距离不能相差太大
  705. if abs(new_col_y - col[3]) <= box_height:
  706. col_line_list[j][3] = max([new_col_y, col[3]])
  707. # 补上下两条横线超出来的线的col
  708. if left_line[0] - up_line[0] >= fix_w_len and left_line[0] - bottom_line[0] >= fix_w_len:
  709. if left_line[0] - up_line[0] >= left_line[0] - bottom_line[0]:
  710. new_col_lines.append([up_line[0], up_line[1], up_line[0], bottom_line[1]])
  711. new_row_x = up_line[0]
  712. # 补了col,要将其他短的row连到col上
  713. for j in range(len(row_line_list)):
  714. row = row_line_list[j]
  715. # 且距离不能相差太大
  716. if abs(new_row_x - row[0]) <= box_width:
  717. row_line_list[j][0] = min([new_row_x, row[0]])
  718. else:
  719. new_col_lines.append([bottom_line[0], up_line[1], bottom_line[0], bottom_line[1]])
  720. new_row_x = bottom_line[0]
  721. # 补了col,要将其他短的row连到col上
  722. for j in range(len(row_line_list)):
  723. row = row_line_list[j]
  724. # 且距离不能相差太大
  725. if abs(new_row_x - row[0]) <= box_width:
  726. row_line_list[j][0] = min([new_row_x, row[0]])
  727. if up_line[2] - right_line[2] >= fix_w_len and bottom_line[2] - right_line[2] >= fix_w_len:
  728. if up_line[2] - right_line[2] >= bottom_line[2] - right_line[2]:
  729. new_col_lines.append([up_line[2], up_line[3], up_line[2], bottom_line[3]])
  730. new_row_x = up_line[2]
  731. # 补了col,要将其他短的row连到col上
  732. for j in range(len(row_line_list)):
  733. row = row_line_list[j]
  734. # 且距离不能相差太大
  735. if abs(new_row_x - row[2]) <= box_width:
  736. row_line_list[j][2] = max([new_row_x, row[2]])
  737. else:
  738. new_col_lines.append([bottom_line[2], up_line[3], bottom_line[2], bottom_line[3]])
  739. new_row_x = bottom_line[2]
  740. # 补了col,要将其他短的row连到col上
  741. for j in range(len(row_line_list)):
  742. row = row_line_list[j]
  743. # 且距离不能相差太大
  744. if abs(new_row_x - row[2]) <= box_width:
  745. row_line_list[j][2] = max([new_row_x, row[2]])
  746. all_longer_row_lines += row_line_list
  747. all_longer_col_lines += col_line_list
  748. # print('new_row_lines, new_col_lines', new_row_lines, new_col_lines)
  749. # print('all_longer_row_lines, all_longer_col_lines', all_longer_row_lines, all_longer_col_lines)
  750. return new_row_lines, new_col_lines, all_longer_row_lines, all_longer_col_lines
  751. def fix_inner(row_line_list, col_line_list, point_list):
  752. def fix(fix_lines, assist_lines, split_points, axis):
  753. new_line_point_list = []
  754. delete_line_point_list = []
  755. for line1 in fix_lines:
  756. min_assist_line = [[], []]
  757. min_distance = [1000, 1000]
  758. if_find = [0, 0]
  759. # 获取fix_line中的所有col point,里面可能不包括两个顶点,col point是交点,顶点可能不是交点
  760. fix_line_points = []
  761. for point in split_points:
  762. if abs(point[1 - axis] - line1[1 - axis]) <= 2:
  763. if line1[axis] <= point[axis] <= line1[axis + 2]:
  764. fix_line_points.append(point)
  765. # 找出离两个顶点最近的assist_line, 并且assist_line与fix_line不相交
  766. line1_point = [line1[:2], line1[2:]]
  767. for i in range(2):
  768. point = line1_point[i]
  769. for line2 in assist_lines:
  770. if not if_find[i] and abs(point[axis] - line2[axis]) <= 2:
  771. if line1[1 - axis] <= point[1 - axis] <= line2[1 - axis + 2]:
  772. # print("line1, match line2", line1, line2)
  773. if_find[i] = 1
  774. break
  775. else:
  776. if abs(point[axis] - line2[axis]) < min_distance[i] and line2[1 - axis] <= point[1 - axis] <= \
  777. line2[1 - axis + 2]:
  778. if line1[axis] <= line2[axis] <= line1[axis + 2]:
  779. continue
  780. min_distance[i] = abs(point[axis] - line2[axis])
  781. min_assist_line[i] = line2
  782. if len(min_assist_line[0]) == 0 and len(min_assist_line[1]) == 0:
  783. continue
  784. # 找出离assist_line最近的交点
  785. min_distance = [1000, 1000]
  786. min_col_point = [[], []]
  787. for i in range(2):
  788. # print("顶点", i, line1_point[i])
  789. if min_assist_line[i]:
  790. for point in fix_line_points:
  791. if abs(point[axis] - min_assist_line[i][axis]) < min_distance[i]:
  792. min_distance[i] = abs(point[axis] - min_assist_line[i][axis])
  793. min_col_point[i] = point
  794. if len(min_col_point[0]) == 0 and len(min_col_point[1]) == 0:
  795. continue
  796. # print('line1', line1)
  797. # print("min_col_point", min_col_point)
  798. # print("min_assist_line", min_assist_line)
  799. # 顶点到交点的距离(多出来的线)需大于assist_line到交点的距离(bbox的边)的1/3
  800. # print("line1_point", line1_point)
  801. if min_assist_line[0] and min_assist_line[0] == min_assist_line[1]:
  802. if min_assist_line[0][axis] < line1_point[0][axis]:
  803. bbox_len = abs(min_col_point[0][axis] - min_assist_line[0][axis])
  804. line_distance = abs(min_col_point[0][axis] - line1_point[0][axis])
  805. if bbox_len / 3 <= line_distance <= bbox_len:
  806. if axis == 1:
  807. add_point = (line1_point[0][1 - axis], min_assist_line[0][axis])
  808. else:
  809. add_point = (min_assist_line[0][axis], line1_point[0][1 - axis])
  810. new_line_point_list.append([line1, add_point])
  811. elif min_assist_line[1][axis] > line1_point[1][axis]:
  812. bbox_len = abs(min_col_point[1][axis] - min_assist_line[1][axis])
  813. line_distance = abs(min_col_point[1][axis] - line1_point[1][axis])
  814. if bbox_len / 3 <= line_distance <= bbox_len:
  815. if axis == 1:
  816. add_point = (line1_point[1][1 - axis], min_assist_line[1][axis])
  817. else:
  818. add_point = (min_assist_line[1][axis], line1_point[1][1 - axis])
  819. new_line_point_list.append([line1, add_point])
  820. else:
  821. for i in range(2):
  822. if min_col_point[i]:
  823. bbox_len = abs(min_col_point[i][axis] - min_assist_line[i][axis])
  824. line_distance = abs(min_col_point[i][axis] - line1_point[i][axis])
  825. # print("bbox_len, line_distance", bbox_len, line_distance)
  826. if bbox_len / 3 <= line_distance <= bbox_len:
  827. if axis == 1:
  828. add_point = (line1_point[i][1 - axis], min_assist_line[i][axis])
  829. else:
  830. add_point = (min_assist_line[i][axis], line1_point[i][1 - axis])
  831. new_line_point_list.append([line1, add_point])
  832. return new_line_point_list
  833. row_line_list_copy = copy.deepcopy(row_line_list)
  834. col_line_list_copy = copy.deepcopy(col_line_list)
  835. try:
  836. new_point_list = fix(col_line_list, row_line_list, point_list, axis=1)
  837. for line, new_point in new_point_list:
  838. if line in col_line_list:
  839. index = col_line_list.index(line)
  840. point1 = line[:2]
  841. point2 = line[2:]
  842. if new_point[1] >= point2[1]:
  843. col_line_list[index] = [point1[0], point1[1], new_point[0], new_point[1]]
  844. elif new_point[1] <= point1[1]:
  845. col_line_list[index] = [new_point[0], new_point[1], point2[0], point2[1]]
  846. new_point_list = fix(row_line_list, col_line_list, point_list, axis=0)
  847. for line, new_point in new_point_list:
  848. if line in row_line_list:
  849. index = row_line_list.index(line)
  850. point1 = line[:2]
  851. point2 = line[2:]
  852. if new_point[0] >= point2[0]:
  853. row_line_list[index] = [point1[0], point1[1], new_point[0], new_point[1]]
  854. elif new_point[0] <= point1[0]:
  855. row_line_list[index] = [new_point[0], new_point[1], point2[0], point2[1]]
  856. return row_line_list, col_line_list
  857. except:
  858. traceback.print_exc()
  859. return row_line_list_copy, col_line_list_copy
  860. def fix_4_points(cross_points, row_line_list, col_line_list):
  861. if not (len(row_line_list) >= 2 and len(col_line_list) >= 2):
  862. return row_line_list, col_line_list
  863. cross_points.sort(key=lambda x: (x[0], x[1]))
  864. left_up_p = cross_points[0]
  865. right_down_p = cross_points[-1]
  866. cross_points.sort(key=lambda x: (-x[0], x[1]))
  867. right_up_p = cross_points[0]
  868. left_down_p = cross_points[-1]
  869. # print('left_up_p', left_up_p, 'left_down_p', left_down_p)
  870. # print('right_up_p', right_up_p, 'right_down_p', right_down_p)
  871. min_x = min(left_up_p[0], left_down_p[0], right_down_p[0], right_up_p[0])
  872. max_x = max(left_up_p[0], left_down_p[0], right_down_p[0], right_up_p[0])
  873. min_y = min(left_up_p[1], left_down_p[1], right_down_p[1], right_up_p[1])
  874. max_y = max(left_up_p[1], left_down_p[1], right_down_p[1], right_up_p[1])
  875. if left_up_p[0] != min_x or left_up_p[1] != min_y:
  876. log('轮廓左上角交点有问题')
  877. row_line_list.append([min_x, min_y, max_x, min_y])
  878. col_line_list.append([min_x, min_y, min_x, max_y])
  879. if left_down_p[0] != min_x or left_down_p[1] != max_y:
  880. log('轮廓左下角交点有问题')
  881. row_line_list.append([min_x, max_y, max_x, max_y])
  882. col_line_list.append([min_x, min_y, min_x, max_y])
  883. if right_up_p[0] != max_x or right_up_p[1] != min_y:
  884. log('轮廓右上角交点有问题')
  885. row_line_list.append([min_x, max_y, max_x, max_y])
  886. col_line_list.append([max_x, min_y, max_x, max_y])
  887. if right_down_p[0] != max_x or right_down_p[1] != max_y:
  888. log('轮廓右下角交点有问题')
  889. row_line_list.append([min_x, max_y, max_x, max_y])
  890. col_line_list.append([max_x, min_y, max_x, max_y])
  891. return row_line_list, col_line_list
  892. def get_split_line(points, col_lines, image_np, threshold=5):
  893. # 线贴着边缘无法得到split_y,导致无法分区
  894. for _col in col_lines:
  895. if _col[3] >= image_np.shape[0] - 5:
  896. _col[3] = image_np.shape[0] - 6
  897. if _col[1] <= 0 + 5:
  898. _col[1] = 6
  899. # print("get_split_line", image_np.shape)
  900. points.sort(key=lambda x: (x[1], x[0]))
  901. # 遍历y坐标,并判断y坐标与上一个y坐标是否存在连接线
  902. i = 0
  903. split_line_y = []
  904. for point in points:
  905. # 从已分开的线下面开始判断
  906. if split_line_y:
  907. if point[1] <= split_line_y[-1] + threshold:
  908. last_y = point[1]
  909. continue
  910. if last_y <= split_line_y[-1] + threshold:
  911. last_y = point[1]
  912. continue
  913. if i == 0:
  914. last_y = point[1]
  915. i += 1
  916. continue
  917. current_line = (last_y, point[1])
  918. split_flag = 1
  919. for col in col_lines:
  920. # 只要找到一条col包含就不是分割线
  921. if current_line[0] >= col[1] - 3 and current_line[1] <= col[3] + 3:
  922. split_flag = 0
  923. break
  924. if split_flag:
  925. split_line_y.append(current_line[0] + 5)
  926. split_line_y.append(current_line[1] - 5)
  927. last_y = point[1]
  928. # 加上收尾分割线
  929. points.sort(key=lambda x: (x[1], x[0]))
  930. y_min = points[0][1]
  931. y_max = points[-1][1]
  932. if y_min - threshold < 0:
  933. split_line_y.append(0)
  934. else:
  935. split_line_y.append(y_min - threshold)
  936. if y_max + threshold > image_np.shape[0]:
  937. split_line_y.append(image_np.shape[0])
  938. else:
  939. split_line_y.append(y_max + threshold)
  940. split_line_y = list(set(split_line_y))
  941. # 剔除两条相隔太近分割线
  942. temp_split_line_y = []
  943. split_line_y.sort(key=lambda x: x)
  944. last_y = -20
  945. for y in split_line_y:
  946. if y - last_y >= 20:
  947. temp_split_line_y.append(y)
  948. last_y = y
  949. split_line_y = temp_split_line_y
  950. # 生成分割线
  951. split_line = []
  952. for y in split_line_y:
  953. split_line.append([(0, y), (image_np.shape[1], y)])
  954. split_line.append([(0, 0), (image_np.shape[1], 0)])
  955. split_line.append([(0, image_np.shape[0]), (image_np.shape[1], image_np.shape[0])])
  956. split_line.sort(key=lambda x: x[0][1])
  957. return split_line, split_line_y
  958. def get_split_area(split_y, row_line_list, col_line_list, cross_points):
  959. # 分割线纵坐标
  960. if len(split_y) < 2:
  961. return [], [], []
  962. split_y.sort(key=lambda x: x)
  963. # new_split_y = []
  964. # for i in range(1, len(split_y), 2):
  965. # new_split_y.append(int((split_y[i] + split_y[i - 1]) / 2))
  966. area_row_line_list = []
  967. area_col_line_list = []
  968. area_point_list = []
  969. for i in range(1, len(split_y)):
  970. y = split_y[i]
  971. last_y = split_y[i - 1]
  972. split_row = []
  973. for row in row_line_list:
  974. if last_y <= row[3] <= y:
  975. split_row.append(row)
  976. split_col = []
  977. for col in col_line_list:
  978. if last_y <= col[1] <= y or last_y <= col[3] <= y or col[1] < last_y < y < col[3]:
  979. split_col.append(col)
  980. split_point = []
  981. for point in cross_points:
  982. if last_y <= point[1] <= y:
  983. split_point.append(point)
  984. # 满足条件才能形成表格区域
  985. if len(split_row) >= 2 and len(split_col) >= 2 and len(split_point) >= 4:
  986. # print('len(split_row), len(split_col), len(split_point)', len(split_row), len(split_col), len(split_point))
  987. area_row_line_list.append(split_row)
  988. area_col_line_list.append(split_col)
  989. area_point_list.append(split_point)
  990. return area_row_line_list, area_col_line_list, area_point_list
  991. def get_standard_lines(row_line_list, col_line_list):
  992. new_row_line_list = []
  993. for row in row_line_list:
  994. w1 = row[0]
  995. w2 = row[2]
  996. # 横线的两个顶点分别找到最近的竖线
  997. min_distance = [10000, 10000]
  998. min_dis_w = [None, None]
  999. for col in col_line_list:
  1000. if abs(col[0] - w1) < min_distance[0]:
  1001. min_distance[0] = abs(col[0] - w1)
  1002. min_dis_w[0] = col[0]
  1003. if abs(col[0] - w2) < min_distance[1]:
  1004. min_distance[1] = abs(col[0] - w2)
  1005. min_dis_w[1] = col[0]
  1006. if min_dis_w[0] is not None:
  1007. row[0] = min_dis_w[0]
  1008. if min_dis_w[1] is not None:
  1009. row[2] = min_dis_w[1]
  1010. new_row_line_list.append(row)
  1011. new_col_line_list = []
  1012. for col in col_line_list:
  1013. h1 = col[1]
  1014. h2 = col[3]
  1015. # 横线的两个顶点分别找到最近的竖线
  1016. min_distance = [10000, 10000]
  1017. min_dis_w = [None, None]
  1018. for row in row_line_list:
  1019. if abs(row[1] - h1) < min_distance[0]:
  1020. min_distance[0] = abs(row[1] - h1)
  1021. min_dis_w[0] = row[1]
  1022. if abs(row[1] - h2) < min_distance[1]:
  1023. min_distance[1] = abs(row[1] - h2)
  1024. min_dis_w[1] = row[1]
  1025. if min_dis_w[0] is not None:
  1026. col[1] = min_dis_w[0]
  1027. if min_dis_w[1] is not None:
  1028. col[3] = min_dis_w[1]
  1029. new_col_line_list.append(col)
  1030. # all_line_list = []
  1031. # # 横线竖线两个维度
  1032. # for i in range(2):
  1033. # axis = i
  1034. # cross_points.sort(key=lambda x: (x[axis], x[1-axis]))
  1035. # current_axis = cross_points[0][axis]
  1036. # points = []
  1037. # line_list = []
  1038. # for p in cross_points:
  1039. # if p[axis] == current_axis:
  1040. # points.append(p)
  1041. # else:
  1042. # if points:
  1043. # line_list.append([points[0][0], points[0][1], points[-1][0], points[-1][1]])
  1044. # points = [p]
  1045. # current_axis = p[axis]
  1046. # if points:
  1047. # line_list.append([points[0][0], points[0][1], points[-1][0], points[-1][1]])
  1048. # all_line_list.append(line_list)
  1049. # new_col_line_list, new_row_line_list = all_line_list
  1050. return new_col_line_list, new_row_line_list
  1051. def add_outline(cross_points, row_line_list, col_line_list):
  1052. cross_points.sort(key=lambda x: (x[0], x[1]))
  1053. left_up_p = cross_points[0]
  1054. right_down_p = cross_points[-1]
  1055. row_line_list.append([left_up_p[0], left_up_p[1], right_down_p[0], left_up_p[1]])
  1056. row_line_list.append([left_up_p[0], right_down_p[1], right_down_p[0], right_down_p[1]])
  1057. col_line_list.append([left_up_p[0], left_up_p[1], left_up_p[0], right_down_p[1]])
  1058. col_line_list.append([right_down_p[0], left_up_p[1], right_down_p[0], right_down_p[1]])
  1059. return row_line_list, col_line_list
  1060. def fix_one_row_outline(row_line_list, col_line_list, cross_points):
  1061. # 确保交点只有一行,且都在同一行
  1062. xs = [x[0] for x in cross_points]
  1063. ys = [x[1] for x in cross_points]
  1064. if abs(min(ys) - max(ys)) > 3:
  1065. # print('ys', ys)
  1066. return row_line_list
  1067. # print('col_line_list', col_line_list)
  1068. # print('ys', ys)
  1069. # 获取交点另一端的y值
  1070. lines = []
  1071. for line in col_line_list:
  1072. if line[0] in xs:
  1073. ys.append(line[3])
  1074. lines.append(line)
  1075. elif line[2] in xs:
  1076. ys.append(line[1])
  1077. lines.append(line)
  1078. # print('lines', lines)
  1079. # 根据长度剔除干扰线
  1080. lines.sort(key=lambda x: abs(x[1]-x[3]))
  1081. current_len = abs(lines[0][1] - lines[0][3])
  1082. len_group = []
  1083. temp_group = []
  1084. for line in lines:
  1085. if (abs(line[1] - line[3]) - current_len) <= 10:
  1086. temp_group.append(line)
  1087. else:
  1088. len_group.append(temp_group)
  1089. temp_group = []
  1090. current_len = abs(line[1] - line[3])
  1091. if temp_group:
  1092. len_group.append(temp_group)
  1093. len_group.sort(key=lambda x: len(x))
  1094. lines = len_group[-1]
  1095. #
  1096. if abs(lines[0][1] - cross_points[0][1]) <= 10:
  1097. lines.sort(key=lambda x: x[3])
  1098. y = lines[0][3]
  1099. else:
  1100. lines.sort(key=lambda x: x[1])
  1101. y = lines[-1][1]
  1102. row_line_list.append([min(xs), y, max(xs), y])
  1103. return row_line_list