table_line_rec_utils.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import math
  2. import cv2
  3. import numpy as np
  4. from scipy.spatial import distance as dist
  5. from skimage import measure
  6. def get_table_line(binimg, axis=0, lineW=10):
  7. ##获取表格线
  8. ##axis=0 横线
  9. ##axis=1 竖线
  10. labels = measure.label(binimg > 0, connectivity=2) # 8连通区域标记
  11. regions = measure.regionprops(labels)
  12. if axis == 1:
  13. lineboxes = [
  14. min_area_rect(line.coords)
  15. for line in regions
  16. if line.bbox[2] - line.bbox[0] > lineW
  17. ]
  18. else:
  19. lineboxes = [
  20. min_area_rect(line.coords)
  21. for line in regions
  22. if line.bbox[3] - line.bbox[1] > lineW
  23. ]
  24. return lineboxes
  25. def min_area_rect(coords):
  26. """
  27. 多边形外接矩形
  28. """
  29. rect = cv2.minAreaRect(coords[:, ::-1])
  30. box = cv2.boxPoints(rect)
  31. box = box.reshape((8,)).tolist()
  32. box = image_location_sort_box(box)
  33. x1, y1, x2, y2, x3, y3, x4, y4 = box
  34. degree, w, h, cx, cy = calculate_center_rotate_angle(box)
  35. if w < h:
  36. xmin = (x1 + x2) / 2
  37. xmax = (x3 + x4) / 2
  38. ymin = (y1 + y2) / 2
  39. ymax = (y3 + y4) / 2
  40. else:
  41. xmin = (x1 + x4) / 2
  42. xmax = (x2 + x3) / 2
  43. ymin = (y1 + y4) / 2
  44. ymax = (y2 + y3) / 2
  45. # degree,w,h,cx,cy = solve(box)
  46. # x1,y1,x2,y2,x3,y3,x4,y4 = box
  47. # return {'degree':degree,'w':w,'h':h,'cx':cx,'cy':cy}
  48. return [xmin, ymin, xmax, ymax]
  49. def image_location_sort_box(box):
  50. x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
  51. pts = (x1, y1), (x2, y2), (x3, y3), (x4, y4)
  52. pts = np.array(pts, dtype="float32")
  53. (x1, y1), (x2, y2), (x3, y3), (x4, y4) = _order_points(pts)
  54. return [x1, y1, x2, y2, x3, y3, x4, y4]
  55. def calculate_center_rotate_angle(box):
  56. """
  57. 绕 cx,cy点 w,h 旋转 angle 的坐标,能一定程度缓解图片的内部倾斜,但是还是依赖模型稳妥
  58. x = cx-w/2
  59. y = cy-h/2
  60. x1-cx = -w/2*cos(angle) +h/2*sin(angle)
  61. y1 -cy= -w/2*sin(angle) -h/2*cos(angle)
  62. h(x1-cx) = -wh/2*cos(angle) +hh/2*sin(angle)
  63. w(y1 -cy)= -ww/2*sin(angle) -hw/2*cos(angle)
  64. (hh+ww)/2sin(angle) = h(x1-cx)-w(y1 -cy)
  65. """
  66. x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
  67. cx = (x1 + x3 + x2 + x4) / 4.0
  68. cy = (y1 + y3 + y4 + y2) / 4.0
  69. w = (
  70. np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
  71. + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)
  72. ) / 2
  73. h = (
  74. np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2)
  75. + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)
  76. ) / 2
  77. # x = cx-w/2
  78. # y = cy-h/2
  79. sinA = (h * (x1 - cx) - w * (y1 - cy)) * 1.0 / (h * h + w * w) * 2
  80. angle = np.arcsin(sinA)
  81. return angle, w, h, cx, cy
  82. def _order_points(pts):
  83. # 根据x坐标对点进行排序
  84. """
  85. ---------------------
  86. 本项目中是为了排序后得到[(xmin,ymin),(xmax,ymin),(xmax,ymax),(xmin,ymax)]
  87. 作者:Tong_T
  88. 来源:CSDN
  89. 原文:https://blog.csdn.net/Tong_T/article/details/81907132
  90. 版权声明:本文为博主原创文章,转载请附上博文链接!
  91. """
  92. x_sorted = pts[np.argsort(pts[:, 0]), :]
  93. left_most = x_sorted[:2, :]
  94. right_most = x_sorted[2:, :]
  95. left_most = left_most[np.argsort(left_most[:, 1]), :]
  96. (tl, bl) = left_most
  97. distance = dist.cdist(tl[np.newaxis], right_most, "euclidean")[0]
  98. (br, tr) = right_most[np.argsort(distance)[::-1], :]
  99. return np.array([tl, tr, br, bl], dtype="float32")
  100. def sqrt(p1, p2):
  101. return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  102. def adjust_lines(lines, alph=50, angle=50):
  103. lines_n = len(lines)
  104. new_lines = []
  105. for i in range(lines_n):
  106. x1, y1, x2, y2 = lines[i]
  107. cx1, cy1 = (x1 + x2) / 2, (y1 + y2) / 2
  108. for j in range(lines_n):
  109. if i != j:
  110. x3, y3, x4, y4 = lines[j]
  111. cx2, cy2 = (x3 + x4) / 2, (y3 + y4) / 2
  112. if (x3 < cx1 < x4 or y3 < cy1 < y4) or (
  113. x1 < cx2 < x2 or y1 < cy2 < y2
  114. ): # 判断两个横线在y方向的投影重不重合
  115. continue
  116. else:
  117. r = sqrt((x1, y1), (x3, y3))
  118. k = abs((y3 - y1) / (x3 - x1 + 1e-10))
  119. a = math.atan(k) * 180 / math.pi
  120. if r < alph and a < angle:
  121. new_lines.append((x1, y1, x3, y3))
  122. r = sqrt((x1, y1), (x4, y4))
  123. k = abs((y4 - y1) / (x4 - x1 + 1e-10))
  124. a = math.atan(k) * 180 / math.pi
  125. if r < alph and a < angle:
  126. new_lines.append((x1, y1, x4, y4))
  127. r = sqrt((x2, y2), (x3, y3))
  128. k = abs((y3 - y2) / (x3 - x2 + 1e-10))
  129. a = math.atan(k) * 180 / math.pi
  130. if r < alph and a < angle:
  131. new_lines.append((x2, y2, x3, y3))
  132. r = sqrt((x2, y2), (x4, y4))
  133. k = abs((y4 - y2) / (x4 - x2 + 1e-10))
  134. a = math.atan(k) * 180 / math.pi
  135. if r < alph and a < angle:
  136. new_lines.append((x2, y2, x4, y4))
  137. return new_lines
  138. def final_adjust_lines(rowboxes, colboxes):
  139. nrow = len(rowboxes)
  140. ncol = len(colboxes)
  141. for i in range(nrow):
  142. for j in range(ncol):
  143. rowboxes[i] = line_to_line(rowboxes[i], colboxes[j], alpha=20, angle=30)
  144. colboxes[j] = line_to_line(colboxes[j], rowboxes[i], alpha=20, angle=30)
  145. return rowboxes, colboxes
  146. def draw_lines(im, bboxes, color=(0, 0, 0), lineW=3):
  147. """
  148. boxes: bounding boxes
  149. """
  150. tmp = np.copy(im)
  151. c = color
  152. h, w = im.shape[:2]
  153. for box in bboxes:
  154. x1, y1, x2, y2 = box[:4]
  155. cv2.line(
  156. tmp, (int(x1), int(y1)), (int(x2), int(y2)), c, lineW, lineType=cv2.LINE_AA
  157. )
  158. return tmp
  159. def line_to_line(points1, points2, alpha=10, angle=30):
  160. """
  161. 线段之间的距离
  162. """
  163. x1, y1, x2, y2 = points1
  164. ox1, oy1, ox2, oy2 = points2
  165. xy = np.array([(x1, y1), (x2, y2)], dtype="float32")
  166. A1, B1, C1 = fit_line(xy)
  167. oxy = np.array([(ox1, oy1), (ox2, oy2)], dtype="float32")
  168. A2, B2, C2 = fit_line(oxy)
  169. flag1 = point_line_cor(np.array([x1, y1], dtype="float32"), A2, B2, C2)
  170. flag2 = point_line_cor(np.array([x2, y2], dtype="float32"), A2, B2, C2)
  171. if (flag1 > 0 and flag2 > 0) or (flag1 < 0 and flag2 < 0): # 横线或者竖线在竖线或者横线的同一侧
  172. if (A1 * B2 - A2 * B1) != 0:
  173. x = (B1 * C2 - B2 * C1) / (A1 * B2 - A2 * B1)
  174. y = (A2 * C1 - A1 * C2) / (A1 * B2 - A2 * B1)
  175. # x, y = round(x, 2), round(y, 2)
  176. p = (x, y) # 横线与竖线的交点
  177. r0 = sqrt(p, (x1, y1))
  178. r1 = sqrt(p, (x2, y2))
  179. if min(r0, r1) < alpha: # 若交点与线起点或者终点的距离小于alpha,则延长线到交点
  180. if r0 < r1:
  181. k = abs((y2 - p[1]) / (x2 - p[0] + 1e-10))
  182. a = math.atan(k) * 180 / math.pi
  183. if a < angle or abs(90 - a) < angle:
  184. points1 = np.array([p[0], p[1], x2, y2], dtype="float32")
  185. else:
  186. k = abs((y1 - p[1]) / (x1 - p[0] + 1e-10))
  187. a = math.atan(k) * 180 / math.pi
  188. if a < angle or abs(90 - a) < angle:
  189. points1 = np.array([x1, y1, p[0], p[1]], dtype="float32")
  190. return points1
  191. def min_area_rect_box(
  192. regions, flag=True, W=0, H=0, filtersmall=False, adjust_box=False
  193. ):
  194. """
  195. 多边形外接矩形
  196. """
  197. boxes = []
  198. for region in regions:
  199. if region.bbox_area > H * W * 3 / 4: # 过滤大的单元格
  200. continue
  201. rect = cv2.minAreaRect(region.coords[:, ::-1])
  202. box = cv2.boxPoints(rect)
  203. box = box.reshape((8,)).tolist()
  204. box = image_location_sort_box(box)
  205. x1, y1, x2, y2, x3, y3, x4, y4 = box
  206. angle, w, h, cx, cy = calculate_center_rotate_angle(box)
  207. # if adjustBox:
  208. # x1, y1, x2, y2, x3, y3, x4, y4 = xy_rotate_box(cx, cy, w + 5, h + 5, angle=0, degree=None)
  209. # x1, x4 = max(x1, 0), max(x4, 0)
  210. # y1, y2 = max(y1, 0), max(y2, 0)
  211. # if w > 32 and h > 32 and flag:
  212. # if abs(angle / np.pi * 180) < 20:
  213. # if filtersmall and (w < 10 or h < 10):
  214. # continue
  215. # boxes.append([x1, y1, x2, y2, x3, y3, x4, y4])
  216. # else:
  217. if w * h < 0.5 * W * H:
  218. if filtersmall and (
  219. w < 15 or h < 15
  220. ): # or w / h > 30 or h / w > 30): # 过滤小的单元格
  221. continue
  222. boxes.append([x1, y1, x2, y2, x3, y3, x4, y4])
  223. return boxes
  224. def point_line_cor(p, A, B, C):
  225. ##判断点与线之间的位置关系
  226. # 一般式直线方程(Ax+By+c)=0
  227. x, y = p
  228. r = A * x + B * y + C
  229. return r
  230. def fit_line(p):
  231. """A = Y2 - Y1
  232. B = X1 - X2
  233. C = X2*Y1 - X1*Y2
  234. AX+BY+C=0
  235. 直线一般方程
  236. """
  237. x1, y1 = p[0]
  238. x2, y2 = p[1]
  239. A = y2 - y1
  240. B = x1 - x2
  241. C = x2 * y1 - x1 * y2
  242. return A, B, C