table_line.py 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Thu Sep 9 23:11:51 2020
  5. table line detect
  6. @author: chineseocr
  7. """
  8. import copy
  9. import logging
  10. import tensorflow as tf
  11. import tensorflow.keras.backend as K
  12. from tensorflow.keras.models import Model
  13. from tensorflow.keras.layers import Input, concatenate, Conv2D, MaxPooling2D, BatchNormalization, UpSampling2D
  14. from tensorflow.keras.layers import LeakyReLU
  15. from otr.utils import letterbox_image, get_table_line, adjust_lines, line_to_line, draw_boxes
  16. import numpy as np
  17. import cv2
  18. import time
  19. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  20. def dice_coef(y_true, y_pred, smooth=1e-5):
  21. y_true_f = K.flatten(y_true)
  22. y_pred_f = K.flatten(y_pred)
  23. intersection = K.sum(y_true_f * y_pred_f)
  24. return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
  25. def dice_coef_loss():
  26. def dice_coef_loss_fixed(y_true, y_pred):
  27. return -dice_coef(y_true, y_pred)
  28. return dice_coef_loss_fixed
  29. def focal_loss(gamma=3., alpha=.5):
  30. # 3 0.85 2000e acc-0.6 p-0.99 r-0.99 val_acc-0.56 val_p-0.86 val_r-0.95
  31. # 2 0.85 double_gpu acc-
  32. # 3 0.25 gpu 50e acc-0.5 p-0.99 r-0.99 val_acc-0.45 val_p-0.96 val_r-0.88
  33. # 2 0.25 gpu acc-
  34. # 3 0.5 double_gpu acc-0.6 p-0.99 r-0.99 val_acc-0.60 val_p-0.93 val_r-0.93
  35. def focal_loss_fixed(y_true, y_pred):
  36. pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
  37. pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
  38. return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(K.epsilon()+pt_1))-K.sum((1-alpha) * K.pow( pt_0, gamma) * K.log(1. - pt_0 + K.epsilon()))
  39. return focal_loss_fixed
  40. def table_net(input_shape=(1152, 896, 3), num_classes=1):
  41. inputs = Input(shape=input_shape)
  42. # 512
  43. use_bias = False
  44. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(inputs)
  45. down0a = BatchNormalization()(down0a)
  46. down0a = LeakyReLU(alpha=0.1)(down0a)
  47. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(down0a)
  48. down0a = BatchNormalization()(down0a)
  49. down0a = LeakyReLU(alpha=0.1)(down0a)
  50. down0a_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0a)
  51. # 256
  52. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0a_pool)
  53. down0 = BatchNormalization()(down0)
  54. down0 = LeakyReLU(alpha=0.1)(down0)
  55. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0)
  56. down0 = BatchNormalization()(down0)
  57. down0 = LeakyReLU(alpha=0.1)(down0)
  58. down0_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0)
  59. # 128
  60. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down0_pool)
  61. down1 = BatchNormalization()(down1)
  62. down1 = LeakyReLU(alpha=0.1)(down1)
  63. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down1)
  64. down1 = BatchNormalization()(down1)
  65. down1 = LeakyReLU(alpha=0.1)(down1)
  66. down1_pool = MaxPooling2D((2, 2), strides=(2, 2))(down1)
  67. # 64
  68. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down1_pool)
  69. down2 = BatchNormalization()(down2)
  70. down2 = LeakyReLU(alpha=0.1)(down2)
  71. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down2)
  72. down2 = BatchNormalization()(down2)
  73. down2 = LeakyReLU(alpha=0.1)(down2)
  74. down2_pool = MaxPooling2D((2, 2), strides=(2, 2))(down2)
  75. # 32
  76. down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down2_pool)
  77. down3 = BatchNormalization()(down3)
  78. down3 = LeakyReLU(alpha=0.1)(down3)
  79. down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down3)
  80. down3 = BatchNormalization()(down3)
  81. down3 = LeakyReLU(alpha=0.1)(down3)
  82. down3_pool = MaxPooling2D((2, 2), strides=(2, 2))(down3)
  83. # 16
  84. down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down3_pool)
  85. down4 = BatchNormalization()(down4)
  86. down4 = LeakyReLU(alpha=0.1)(down4)
  87. down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down4)
  88. down4 = BatchNormalization()(down4)
  89. down4 = LeakyReLU(alpha=0.1)(down4)
  90. down4_pool = MaxPooling2D((2, 2), strides=(2, 2))(down4)
  91. # 8
  92. center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(down4_pool)
  93. center = BatchNormalization()(center)
  94. center = LeakyReLU(alpha=0.1)(center)
  95. center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(center)
  96. center = BatchNormalization()(center)
  97. center = LeakyReLU(alpha=0.1)(center)
  98. # center
  99. up4 = UpSampling2D((2, 2))(center)
  100. up4 = concatenate([down4, up4], axis=3)
  101. up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
  102. up4 = BatchNormalization()(up4)
  103. up4 = LeakyReLU(alpha=0.1)(up4)
  104. up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
  105. up4 = BatchNormalization()(up4)
  106. up4 = LeakyReLU(alpha=0.1)(up4)
  107. up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
  108. up4 = BatchNormalization()(up4)
  109. up4 = LeakyReLU(alpha=0.1)(up4)
  110. # 16
  111. up3 = UpSampling2D((2, 2))(up4)
  112. up3 = concatenate([down3, up3], axis=3)
  113. up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
  114. up3 = BatchNormalization()(up3)
  115. up3 = LeakyReLU(alpha=0.1)(up3)
  116. up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
  117. up3 = BatchNormalization()(up3)
  118. up3 = LeakyReLU(alpha=0.1)(up3)
  119. up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
  120. up3 = BatchNormalization()(up3)
  121. up3 = LeakyReLU(alpha=0.1)(up3)
  122. # 32
  123. up2 = UpSampling2D((2, 2))(up3)
  124. up2 = concatenate([down2, up2], axis=3)
  125. up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
  126. up2 = BatchNormalization()(up2)
  127. up2 = LeakyReLU(alpha=0.1)(up2)
  128. up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
  129. up2 = BatchNormalization()(up2)
  130. up2 = LeakyReLU(alpha=0.1)(up2)
  131. up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
  132. up2 = BatchNormalization()(up2)
  133. up2 = LeakyReLU(alpha=0.1)(up2)
  134. # 64
  135. up1 = UpSampling2D((2, 2))(up2)
  136. up1 = concatenate([down1, up1], axis=3)
  137. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  138. up1 = BatchNormalization()(up1)
  139. up1 = LeakyReLU(alpha=0.1)(up1)
  140. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  141. up1 = BatchNormalization()(up1)
  142. up1 = LeakyReLU(alpha=0.1)(up1)
  143. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  144. up1 = BatchNormalization()(up1)
  145. up1 = LeakyReLU(alpha=0.1)(up1)
  146. # 128
  147. up0 = UpSampling2D((2, 2))(up1)
  148. up0 = concatenate([down0, up0], axis=3)
  149. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  150. up0 = BatchNormalization()(up0)
  151. up0 = LeakyReLU(alpha=0.1)(up0)
  152. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  153. up0 = BatchNormalization()(up0)
  154. up0 = LeakyReLU(alpha=0.1)(up0)
  155. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  156. up0 = BatchNormalization()(up0)
  157. up0 = LeakyReLU(alpha=0.1)(up0)
  158. # 256
  159. up0a = UpSampling2D((2, 2))(up0)
  160. up0a = concatenate([down0a, up0a], axis=3)
  161. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  162. up0a = BatchNormalization()(up0a)
  163. up0a = LeakyReLU(alpha=0.1)(up0a)
  164. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  165. up0a = BatchNormalization()(up0a)
  166. up0a = LeakyReLU(alpha=0.1)(up0a)
  167. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  168. up0a = BatchNormalization()(up0a)
  169. up0a = LeakyReLU(alpha=0.1)(up0a)
  170. # 512
  171. classify = Conv2D(num_classes, (1, 1), activation='sigmoid')(up0a)
  172. model = Model(inputs=inputs, outputs=classify)
  173. return model
  174. model = table_net((None, None, 3), 2)
  175. def table_line(img, model, size=(512, 1024), hprob=0.5, vprob=0.5, row=50, col=30, alph=15):
  176. sizew, sizeh = size
  177. # [..., ::-1] 最后一维内部反向输出
  178. # inputBlob, fx, fy = letterbox_image(img[..., ::-1], (sizew, sizeh))
  179. # pred = model.predict(np.array([np.array(inputBlob)]))
  180. # pred = model.predict(np.array([np.array(inputBlob)/255.0]))
  181. img_new = cv2.resize(img, (sizew, sizeh), interpolation=cv2.INTER_AREA)
  182. # logging.info("into table_line 1")
  183. pred = model.predict(np.array([img_new]))
  184. # logging.info("into table_line 2")
  185. pred = pred[0]
  186. vpred = pred[..., 1] > vprob # 横线
  187. hpred = pred[..., 0] > hprob # 竖线
  188. vpred = vpred.astype(int)
  189. hpred = hpred.astype(int)
  190. # print("vpred shape", vpred)
  191. # print("hpred shape", hpred)
  192. colboxes = get_table_line(vpred, axis=1, lineW=col)
  193. rowboxes = get_table_line(hpred, axis=0, lineW=row)
  194. # logging.info("into table_line 3")
  195. # if len(rowboxes) > 0:
  196. # rowboxes = np.array(rowboxes)
  197. # rowboxes[:, [0, 2]] = rowboxes[:, [0, 2]]/fx
  198. # rowboxes[:, [1, 3]] = rowboxes[:, [1, 3]]/fy
  199. # rowboxes = rowboxes.tolist()
  200. # if len(colboxes) > 0:
  201. # colboxes = np.array(colboxes)
  202. # colboxes[:, [0, 2]] = colboxes[:, [0, 2]]/fx
  203. # colboxes[:, [1, 3]] = colboxes[:, [1, 3]]/fy
  204. # colboxes = colboxes.tolist()
  205. nrow = len(rowboxes)
  206. ncol = len(colboxes)
  207. for i in range(nrow):
  208. for j in range(ncol):
  209. rowboxes[i] = line_to_line(rowboxes[i], colboxes[j], 10)
  210. colboxes[j] = line_to_line(colboxes[j], rowboxes[i], 10)
  211. # logging.info("into table_line 4")
  212. # 删掉贴着边框的line
  213. temp_list = []
  214. threshold = 5
  215. for line in rowboxes:
  216. if line[1]-0 <= threshold or size[1]-line[1] <= threshold:
  217. continue
  218. # 内部排序
  219. if line[0] > line[2]:
  220. line = [line[2], line[3], line[0], line[1]]
  221. temp_list.append(line)
  222. rowboxes = temp_list
  223. temp_list = []
  224. for line in colboxes:
  225. if line[0]-0 <= threshold or size[0]-line[0] <= threshold:
  226. continue
  227. # 内部排序
  228. if line[1] > line[3]:
  229. line = [line[2], line[3], line[0], line[1]]
  230. temp_list.append(line)
  231. colboxes = temp_list
  232. return rowboxes, colboxes, img_new
  233. def get_outline(points, image_np):
  234. # 取出x, y的最大值最小值
  235. x_min = points[0][0]
  236. x_max = points[-1][0]
  237. points.sort(key=lambda x: (x[1], x[0]))
  238. y_min = points[0][1]
  239. y_max = points[-1][1]
  240. # 创建空图
  241. # outline_img = np.zeros(image_size, np.uint8)
  242. outline_img = np.copy(image_np)
  243. cv2.rectangle(outline_img, (x_min-5, y_min-5), (x_max+5, y_max+5), (0, 0, 0), 2)
  244. # cv2.imshow("outline_img", outline_img)
  245. # cv2.waitKey(0)
  246. return outline_img
  247. def get_split_line(points, col_lines, image_np):
  248. # print("get_split_line", image_np.shape)
  249. points.sort(key=lambda x: (x[1], x[0]))
  250. # 遍历y坐标,并判断y坐标与上一个y坐标是否存在连接线
  251. i = 0
  252. split_line_y = []
  253. for point in points:
  254. # 从已分开的线下面开始判断
  255. if split_line_y:
  256. if point[1] <= split_line_y[-1] + 5:
  257. last_y = point[1]
  258. continue
  259. if last_y <= split_line_y[-1] + 5:
  260. last_y = point[1]
  261. continue
  262. if i == 0:
  263. last_y = point[1]
  264. i += 1
  265. continue
  266. current_line = (last_y, point[1])
  267. split_flag = 1
  268. for col in col_lines:
  269. # 只要找到一条col包含就不是分割线
  270. if current_line[0] >= col[1]-3 and current_line[1] <= col[3]+3:
  271. split_flag = 0
  272. # print("img", img.shape)
  273. # print("col", col)
  274. # print("current_line", current_line)
  275. break
  276. if split_flag:
  277. split_line_y.append(current_line[0]+5)
  278. split_line_y.append(current_line[1]-5)
  279. last_y = point[1]
  280. # 加上收尾分割线
  281. points.sort(key=lambda x: (x[1], x[0]))
  282. y_min = points[0][1]
  283. y_max = points[-1][1]
  284. # print("加上收尾分割线", y_min, y_max)
  285. if y_min-5 < 0:
  286. split_line_y.append(0)
  287. else:
  288. split_line_y.append(y_min-5)
  289. if y_max+5 > image_np.shape[0]:
  290. split_line_y.append(image_np.shape[0])
  291. else:
  292. split_line_y.append(y_max+5)
  293. split_line_y = list(set(split_line_y))
  294. # 剔除两条相隔太近分割线
  295. temp_split_line_y = []
  296. split_line_y.sort(key=lambda x: x)
  297. last_y = -20
  298. for y in split_line_y:
  299. # print(y)
  300. if y - last_y >= 20:
  301. # print(y, last_y)
  302. temp_split_line_y.append(y)
  303. last_y = y
  304. split_line_y = temp_split_line_y
  305. # print("split_line_y", split_line_y)
  306. # 生成分割线
  307. split_line = []
  308. last_y = 0
  309. for y in split_line_y:
  310. # if y - last_y <= 15:
  311. # continue
  312. split_line.append([(0, y), (image_np.shape[1], y)])
  313. last_y = y
  314. split_line.append([(0, 0), (image_np.shape[1], 0)])
  315. split_line.append([(0, image_np.shape[0]), (image_np.shape[1], image_np.shape[0])])
  316. split_line.sort(key=lambda x: x[0][1])
  317. # print("split_line", split_line)
  318. # 画图画线
  319. # split_line_img = np.copy(image_np)
  320. # for y in split_line_y:
  321. # cv2.line(split_line_img, (0, y), (image_np.shape[1], y), (0, 0, 0), 1)
  322. # cv2.imshow("split_line_img", split_line_img)
  323. # cv2.waitKey(0)
  324. return split_line, split_line_y
  325. def get_points(row_lines, col_lines, image_size):
  326. # 创建空图
  327. row_img = np.zeros(image_size, np.uint8)
  328. col_img = np.zeros(image_size, np.uint8)
  329. # 画线
  330. thresh = 3
  331. for row in row_lines:
  332. cv2.line(row_img, (int(row[0]-thresh), int(row[1])), (int(row[2]+thresh), int(row[3])), (255, 255, 255), 1)
  333. for col in col_lines:
  334. cv2.line(col_img, (int(col[0]), int(col[1]-thresh)), (int(col[2]), int(col[3]+thresh)), (255, 255, 255), 1)
  335. # 求出交点
  336. point_img = np.bitwise_and(row_img, col_img)
  337. # cv2.imshow("point_img", np.bitwise_not(point_img))
  338. # cv2.waitKey(0)
  339. # 识别黑白图中的白色交叉点,将横纵坐标取出
  340. ys, xs = np.where(point_img > 0)
  341. points = []
  342. for i in range(len(xs)):
  343. points.append((xs[i], ys[i]))
  344. points.sort(key=lambda x: (x[0], x[1]))
  345. return points
  346. def get_minAreaRect(image):
  347. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  348. gray = cv2.bitwise_not(gray)
  349. thresh = cv2.threshold(gray, 0, 255,
  350. cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  351. coords = np.column_stack(np.where(thresh > 0))
  352. return cv2.minAreaRect(coords)
  353. def get_contours(image):
  354. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  355. ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
  356. contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  357. cv2.drawContours(image, contours, -1, (0, 0, 255), 3)
  358. cv2.imshow("get contours", image)
  359. cv2.waitKey(0)
  360. def merge_line(lines, axis, threshold=5):
  361. """
  362. 解决模型预测一条直线错开成多条直线,合并成一条直线
  363. :param lines: 线条列表
  364. :param axis: 0:横线 1:竖线
  365. :param threshold: 两条线间像素差阈值
  366. :return: 合并后的线条列表
  367. """
  368. # 任意一条line获取该合并的line,横线往下找,竖线往右找
  369. lines.sort(key=lambda x: (x[axis], x[1-axis]))
  370. merged_lines = []
  371. used_lines = []
  372. for line1 in lines:
  373. if line1 in used_lines:
  374. continue
  375. merged_line = [line1]
  376. used_lines.append(line1)
  377. for line2 in lines:
  378. if line2 in used_lines:
  379. continue
  380. if line1[1-axis]-threshold <= line2[1-axis] <= line1[1-axis]+threshold:
  381. # 计算基准长度
  382. min_axis = 10000
  383. max_axis = 0
  384. for line3 in merged_line:
  385. if line3[axis] < min_axis:
  386. min_axis = line3[axis]
  387. if line3[axis+2] > max_axis:
  388. max_axis = line3[axis+2]
  389. # 判断两条线有无交集
  390. if min_axis <= line2[axis] <= max_axis \
  391. or min_axis <= line2[axis+2] <= max_axis:
  392. merged_line.append(line2)
  393. used_lines.append(line2)
  394. if merged_line:
  395. merged_lines.append(merged_line)
  396. # 合并line
  397. result_lines = []
  398. for merged_line in merged_lines:
  399. # 获取line宽的平均值
  400. axis_average = 0
  401. for line in merged_line:
  402. axis_average += line[1-axis]
  403. axis_average = int(axis_average/len(merged_line))
  404. # 获取最长line两端
  405. merged_line.sort(key=lambda x: (x[axis]))
  406. axis_start = merged_line[0][axis]
  407. merged_line.sort(key=lambda x: (x[axis+2]))
  408. axis_end = merged_line[-1][axis+2]
  409. if axis:
  410. result_lines.append([axis_average, axis_start, axis_average, axis_end])
  411. else:
  412. result_lines.append([axis_start, axis_average, axis_end, axis_average])
  413. return result_lines
  414. def fix_inner2(row_points, col_points, row_lines, col_lines, threshold=3):
  415. for i in range(len(row_points)):
  416. row = row_points[i]
  417. row.sort(key=lambda x: (x[1], x[0]))
  418. for j in range(len(row)):
  419. # 当前点
  420. point = row[j]
  421. # 获取当前点在所在行的下个点
  422. if j >= len(row) - 1:
  423. next_row_point = []
  424. else:
  425. next_row_point = row[j+1]
  426. if next_row_point:
  427. for k in range(len(row_lines)):
  428. line = row_lines[k]
  429. if line[1] - threshold <= point[1] <= line[1] + threshold:
  430. if not line[0] <= point[0] <= next_row_point[0] <= line[2]:
  431. if point[0] <= line[2] < next_row_point[0]:
  432. if line[2] - point[0] >= 1/3 * (next_row_point[0] - point[0]):
  433. row_lines[k][2] = next_row_point[0]
  434. if point[0] < line[0] <= next_row_point[0]:
  435. if next_row_point[0] - line[0] >= 1/3 * (next_row_point[0] - point[0]):
  436. row_lines[k][0] = point[0]
  437. # 获取当前点所在列的下个点
  438. next_col_point = []
  439. for col in col_points:
  440. if point in col:
  441. col.sort(key=lambda x: (x[0], x[1]))
  442. if col.index(point) < len(col) - 1:
  443. next_col_point = col[col.index(point)+1]
  444. break
  445. # 获取当前点的对角线点,通过该列下个点所在行的下个点获得
  446. next_row_next_col_point = []
  447. if next_col_point:
  448. for row2 in row_points:
  449. if next_col_point in row2:
  450. row2.sort(key=lambda x: (x[1], x[0]))
  451. if row2.index(next_col_point) < len(row2) - 1:
  452. next_row_next_col_point = row2[row2.index(next_col_point)+1]
  453. break
  454. # 有该列下一点但没有该列下一点所在行的下个点
  455. if not next_row_next_col_point:
  456. # 如果有该行下个点
  457. if next_row_point:
  458. next_row_next_col_point = [next_row_point[0], next_col_point[1]]
  459. if next_col_point:
  460. for k in range(len(col_lines)):
  461. line = col_lines[k]
  462. if line[0] - threshold <= point[0] <= line[0] + threshold:
  463. if not line[1] <= point[1] <= next_col_point[1] <= line[3]:
  464. if point[1] <= line[3] < next_col_point[1]:
  465. if line[3] - point[1] >= 1/3 * (next_col_point[1] - point[1]):
  466. col_lines[k][3] = next_col_point[1]
  467. if point[1] < line[1] <= next_col_point[1]:
  468. if next_col_point[1] - line[1] >= 1/3 * (next_col_point[1] - point[1]):
  469. col_lines[k][1] = point[1]
  470. if next_row_next_col_point:
  471. for k in range(len(col_lines)):
  472. line = col_lines[k]
  473. if line[0] - threshold <= next_row_next_col_point[0] <= line[0] + threshold:
  474. if not line[1] <= point[1] <= next_row_next_col_point[1] <= line[3]:
  475. if point[1] < line[1] <= next_row_next_col_point[1]:
  476. if next_row_next_col_point[1] - line[1] >= 1/3 * (next_row_next_col_point[1] - point[1]):
  477. col_lines[k][1] = point[1]
  478. return row_lines, col_lines
  479. def fix_inner(row_lines, col_lines, points, split_y):
  480. def fix(fix_lines, assist_lines, split_points, axis):
  481. new_points = []
  482. for line1 in fix_lines:
  483. min_assist_line = [[], []]
  484. min_distance = [1000, 1000]
  485. if_find = [0, 0]
  486. # 获取fix_line中的所有col point,里面可能不包括两个顶点,col point是交点,顶点可能不是交点
  487. fix_line_points = []
  488. for point in split_points:
  489. if abs(point[1-axis] - line1[1-axis]) <= 2:
  490. if line1[axis] <= point[axis] <= line1[axis+2]:
  491. fix_line_points.append(point)
  492. # 找出离两个顶点最近的assist_line, 并且assist_line与fix_line不相交
  493. line1_point = [line1[:2], line1[2:]]
  494. for i in range(2):
  495. point = line1_point[i]
  496. for line2 in assist_lines:
  497. if not if_find[i] and abs(point[axis] - line2[axis]) <= 2:
  498. if line1[1-axis] <= point[1-axis] <= line2[1-axis+2]:
  499. # print("line1, match line2", line1, line2)
  500. if_find[i] = 1
  501. break
  502. else:
  503. if abs(point[axis] - line2[axis]) < min_distance[i] and line2[1-axis] <= point[1-axis] <= line2[1-axis+2]:
  504. if line1[axis] <= line2[axis] <= line1[axis+2]:
  505. continue
  506. min_distance[i] = abs(line1[axis] - line2[axis])
  507. min_assist_line[i] = line2
  508. # 找出离assist_line最近的交点
  509. # 顶点到交点的距离(多出来的线)需大于assist_line到交点的距离(bbox的边)的1/3
  510. min_distance = [1000, 1000]
  511. min_col_point = [[], []]
  512. for i in range(2):
  513. # print("顶点", i, line1_point[i])
  514. if not if_find[i]:
  515. if min_assist_line[i]:
  516. for point in fix_line_points:
  517. if abs(point[axis] - min_assist_line[i][axis]) < min_distance[i]:
  518. min_distance[i] = abs(point[axis] - min_assist_line[i][axis])
  519. min_col_point[i] = point
  520. if min_col_point[i]:
  521. if abs(min_col_point[i][axis] - line1_point[i][axis]) >= abs(min_col_point[i][axis] - min_assist_line[i][axis])/3:
  522. add_point = (line1_point[i][1-axis], min_assist_line[i][axis])
  523. # print("fix_inner add point", add_point)
  524. # print("line1, line2", line1, min_assist_line[i])
  525. new_points.append(add_point)
  526. return new_points
  527. new_points = []
  528. for i in range(1, len(split_y)):
  529. last_y = split_y[i-1]
  530. y = split_y[i]
  531. # 先对点线进行分区
  532. split_row_lines = []
  533. split_col_lines = []
  534. split_points = []
  535. for row in row_lines:
  536. if last_y <= row[1] <= y:
  537. split_row_lines.append(row)
  538. for col in col_lines:
  539. if last_y <= col[1] <= y:
  540. split_col_lines.append(col)
  541. for point in points:
  542. if last_y <= point[1] <= y:
  543. split_points.append(point)
  544. new_points += fix(split_col_lines, split_row_lines, split_points, axis=1)
  545. new_points += fix(split_row_lines, split_col_lines, split_points, axis=0)
  546. # 找出所有col的顶点不在row上的、row的顶点不在col上的
  547. # for col in split_col_lines:
  548. # print("*"*30)
  549. #
  550. # # 获取该line中的所有point
  551. # col_points = []
  552. # for point in split_points:
  553. # if abs(point[0] - col[0]) <= 2:
  554. # if col[1] <= point[1] <= col[3]:
  555. # col_points.append(point)
  556. #
  557. # # 比较顶点
  558. # min_row_1 = []
  559. # min_row_2 = []
  560. # min_distance_1 = 1000
  561. # min_distance_2 = 1000
  562. # if_find_1 = 0
  563. # if_find_2 = 0
  564. # for row in split_row_lines:
  565. # # 第一个顶点
  566. # if not if_find_1 and abs(col[1] - row[1]) <= 2:
  567. # if row[0] <= col[0] <= row[2]:
  568. # print("col, match row", col, row)
  569. # if_find_1 = 1
  570. # break
  571. # else:
  572. # if abs(col[1] - row[1]) < min_distance_1 and row[0] <= col[0] <= row[2]:
  573. # if col[1] <= row[1] <= col[3]:
  574. # continue
  575. # min_distance_1 = abs(col[1] - row[1])
  576. # min_row_1 = row
  577. #
  578. # # 第二个顶点
  579. # if not if_find_2 and abs(col[3] - row[1]) <= 2:
  580. # if row[0] <= col[2] <= row[2]:
  581. # if_find_2 = 1
  582. # break
  583. # else:
  584. # if abs(col[3] - row[1]) < min_distance_2 and row[0] <= col[2] <= row[2]:
  585. # min_distance_2 = abs(col[3] - row[1])
  586. # min_row_2 = row
  587. #
  588. # if not if_find_1:
  589. # print("col", col)
  590. # print("min_row_1", min_row_1)
  591. # if min_row_1:
  592. # min_distance_1 = 1000
  593. # min_col_point = []
  594. # for point in col_points:
  595. # if abs(point[1] - min_row_1[1]) < min_distance_1:
  596. # min_distance_1 = abs(point[1] - min_row_1[1])
  597. # min_col_point = point
  598. #
  599. # if abs(min_col_point[1] - col[1]) >= abs(min_col_point[1] - min_row_1[1])/3:
  600. #
  601. # add_point = (col[0], min_row_1[1])
  602. # print("fix_inner add point", add_point)
  603. # new_points.append(add_point)
  604. # else:
  605. # print("distance too long", min_col_point, min_row_1)
  606. # print(abs(min_col_point[1] - col[1]), abs(min_col_point[1] - min_row_1[1])/3)
  607. return points+new_points
  608. def fix_corner(row_lines, col_lines, split_y):
  609. new_row_lines = []
  610. new_col_lines = []
  611. last_y = split_y[0]
  612. for y in split_y:
  613. if y == last_y:
  614. continue
  615. split_row_lines = []
  616. split_col_lines = []
  617. for row in row_lines:
  618. if last_y <= row[1] <= y or last_y <= row[3] <= y:
  619. split_row_lines.append(row)
  620. for col in col_lines:
  621. if last_y <= col[1] <= y or last_y <= col[3] <= y:
  622. split_col_lines.append(col)
  623. if not split_row_lines or not split_col_lines:
  624. last_y = y
  625. continue
  626. split_row_lines.sort(key=lambda x: (x[1], x[0]))
  627. split_col_lines.sort(key=lambda x: (x[0], x[1]))
  628. up_line = split_row_lines[0]
  629. bottom_line = split_row_lines[-1]
  630. left_line = split_col_lines[0]
  631. right_line = split_col_lines[-1]
  632. # 左上角
  633. if up_line[0:2] != left_line[0:2]:
  634. # print("up_line, left_line", up_line, left_line)
  635. add_corner = [left_line[0], up_line[1]]
  636. split_row_lines[0][0] = add_corner[0]
  637. split_col_lines[0][1] = add_corner[1]
  638. # 右上角
  639. if up_line[2:] != right_line[:2]:
  640. # print("up_line, right_line", up_line, right_line)
  641. add_corner = [right_line[0], up_line[1]]
  642. split_row_lines[0][2] = add_corner[0]
  643. split_col_lines[-1][1] = add_corner[1]
  644. new_row_lines = new_row_lines + split_row_lines
  645. new_col_lines = new_col_lines + split_col_lines
  646. last_y = y
  647. return new_row_lines, new_col_lines
  648. def delete_outline(row_lines, col_lines, points):
  649. row_lines.sort(key=lambda x: (x[1], x[0]))
  650. col_lines.sort(key=lambda x: (x[0], x[1]))
  651. line = [row_lines[0], row_lines[-1], col_lines[0], col_lines[-1]]
  652. threshold = 2
  653. point_cnt = [0, 0, 0, 0]
  654. for point in points:
  655. for i in range(4):
  656. if i < 2:
  657. if line[i][1]-threshold <= point[1] <= line[i][1]+threshold:
  658. if line[i][0] <= point[0] <= line[i][2]:
  659. point_cnt[i] += 1
  660. else:
  661. if line[i][0]-threshold <= point[0] <= line[i][0]+threshold:
  662. if line[i][1] <= point[1] <= line[i][3]:
  663. point_cnt[i] += 1
  664. # if line[0][1]-threshold <= point[1] <= line[0][1]+threshold:
  665. # if line[0][0] <= point[0] <= line[0][2]:
  666. # point_cnt[0] += 1
  667. # elif line[1][1]-threshold <= point[1] <= line[1][1]+threshold:
  668. # if line[1][0] <= point[0] <= line[1][2]:
  669. # point_cnt[1] += 1
  670. # elif line[2][0]-threshold <= point[0] <= line[2][0]+threshold:
  671. # if line[2][1] <= point[1] <= line[2][3]:
  672. # point_cnt[2] += 1
  673. # elif line[3][0]-threshold <= point[0] <= line[3][0]+threshold:
  674. # if line[3][1] <= point[1] <= line[3][3]:
  675. # point_cnt[3] += 1
  676. # 轮廓line至少包含3个交点
  677. for i in range(4):
  678. if point_cnt[i] < 3:
  679. if i < 2:
  680. if line[i] in row_lines:
  681. row_lines.remove(line[i])
  682. else:
  683. if line[i] in col_lines:
  684. col_lines.remove(line[i])
  685. return row_lines, col_lines
  686. def fix_outline(image, row_lines, col_lines, points, split_y):
  687. print("split_y", split_y)
  688. # 分割线纵坐标
  689. if len(split_y) < 2:
  690. return [], [], [], []
  691. # elif len(split_y) == 2:
  692. # split_y = [2000., 2000., 2000., 2000.]
  693. split_y.sort(key=lambda x: x)
  694. new_split_y = []
  695. for i in range(1, len(split_y), 2):
  696. new_split_y.append(int((split_y[i]+split_y[i-1])/2))
  697. # # 查看是否正确输出区域分割线
  698. # for line in split_y:
  699. # cv2.line(image, (0, int(line)), (int(image.shape[1]), int(line)), (0, 0, 255), 2)
  700. # cv2.imshow("split_y", image)
  701. # cv2.waitKey(0)
  702. # 预测线根据分割线纵坐标分为多个分割区域
  703. # row_lines.sort(key=lambda x: (x[3], x[2], x[1], x[0]))
  704. # col_lines.sort(key=lambda x: (x[3], x[2], x[1], x[0]))
  705. # points.sort(key=lambda x: (x[1], x[0]))
  706. # row_count = 0
  707. # col_count = 0
  708. # point_count = 0
  709. split_row_list = []
  710. split_col_list = []
  711. split_point_list = []
  712. # for i in range(1, len(split_y)):
  713. # y = split_y[i]
  714. # last_y = split_y[i-1]
  715. # row_lines = row_lines[row_count:]
  716. # col_lines = col_lines[col_count:]
  717. # points = points[point_count:]
  718. # row_count = 0
  719. # col_count = 0
  720. # point_count = 0
  721. #
  722. # if not row_lines:
  723. # split_row_list.append([])
  724. # for row in row_lines:
  725. # if last_y <= row[3] <= y:
  726. # row_count += 1
  727. # else:
  728. # split_row_list.append(row_lines[:row_count])
  729. # break
  730. # if row_count == len(row_lines):
  731. # split_row_list.append(row_lines[:row_count])
  732. # break
  733. #
  734. # if not col_lines:
  735. # split_col_list.append([])
  736. #
  737. # for col in col_lines:
  738. # # if last_y <= col[3] <= y:
  739. # if col[1] <= last_y <= y <= col[3] or last_y <= col[3] <= y:
  740. # # if last_y <= col[1] <= y or last_y <= col[3] <= y:
  741. # col_count += 1
  742. # else:
  743. # split_col_list.append(col_lines[:col_count])
  744. # break
  745. # if col_count == len(col_lines):
  746. # split_col_list.append(col_lines[:col_count])
  747. # break
  748. #
  749. # if not points:
  750. # split_point_list.append([])
  751. # for point in points:
  752. # if last_y <= point[1] <= y:
  753. # point_count += 1
  754. # else:
  755. # split_point_list.append(points[:point_count])
  756. # break
  757. # if point_count == len(points):
  758. # split_point_list.append(points[:point_count])
  759. # break
  760. #
  761. # # print("len(split_row_list)", len(split_row_list))
  762. # # print("len(split_col_list)", len(split_col_list))
  763. # if row_count < len(row_lines) - 1 and col_count < len(col_lines) - 1:
  764. # row_lines = row_lines[row_count:]
  765. # split_row_list.append(row_lines)
  766. # col_lines = col_lines[col_count:]
  767. # split_col_list.append(col_lines)
  768. #
  769. # if point_count < len(points) - 1:
  770. # points = points[point_count:len(points)]
  771. # split_point_list.append(points)
  772. for i in range(1, len(split_y)):
  773. y = split_y[i]
  774. last_y = split_y[i-1]
  775. split_row = []
  776. for row in row_lines:
  777. if last_y <= row[3] <= y:
  778. split_row.append(row)
  779. split_row_list.append(split_row)
  780. split_col = []
  781. for col in col_lines:
  782. if last_y <= col[1] <= y or last_y <= col[3] <= y or col[1] < last_y < y < col[3]:
  783. split_col.append(col)
  784. split_col_list.append(split_col)
  785. split_point = []
  786. for point in points:
  787. if last_y <= point[1] <= y:
  788. split_point.append(point)
  789. split_point_list.append(split_point)
  790. # 预测线取上下左右4个边(会有超出表格部分) [(), ()]
  791. area_row_line = []
  792. area_col_line = []
  793. for area in split_row_list:
  794. if not area:
  795. area_row_line.append([])
  796. continue
  797. area.sort(key=lambda x: (x[1], x[0]))
  798. up_line = area[0]
  799. bottom_line = area[-1]
  800. area_row_line.append([up_line, bottom_line])
  801. for area in split_col_list:
  802. if not area:
  803. area_col_line.append([])
  804. continue
  805. area.sort(key=lambda x: x[0])
  806. left_line = area[0]
  807. right_line = area[-1]
  808. area_col_line.append([left_line, right_line])
  809. # 线交点根据分割线纵坐标分为多个分割区域
  810. # points.sort(key=lambda x: (x[1], x[0]))
  811. # point_count = 0
  812. # split_point_list = []
  813. # for y in new_split_y:
  814. # points = points[point_count:len(points)]
  815. # point_count = 0
  816. # for point in points:
  817. # if point[1] <= y:
  818. # point_count += 1
  819. # else:
  820. # split_point_list.append(points[:point_count])
  821. # break
  822. # if point_count == len(points):
  823. # split_point_list.append(points[:point_count])
  824. # break
  825. # if point_count < len(points) - 1:
  826. # points = points[point_count:len(points)]
  827. # split_point_list.append(points)
  828. # print("len(split_point_list)", len(split_point_list))
  829. # 取每个分割区域的4条线(无超出表格部分)
  830. area_row_line2 = []
  831. area_col_line2 = []
  832. for area in split_point_list:
  833. if not area:
  834. area_row_line2.append([])
  835. area_col_line2.append([])
  836. continue
  837. area.sort(key=lambda x: (x[0], x[1]))
  838. left_up = area[0]
  839. right_bottom = area[-1]
  840. up_line = [left_up[0], left_up[1], right_bottom[0], left_up[1]]
  841. bottom_line = [left_up[0], right_bottom[1], right_bottom[0], right_bottom[1]]
  842. left_line = [left_up[0], left_up[1], left_up[0], right_bottom[1]]
  843. right_line = [right_bottom[0], left_up[1], right_bottom[0], right_bottom[1]]
  844. area_row_line2.append([up_line, bottom_line])
  845. area_col_line2.append([left_line, right_line])
  846. # 判断超出部分的长度,超出一定长度就补线
  847. new_row_lines = []
  848. new_col_lines = []
  849. longer_row_lines = []
  850. longer_col_lines = []
  851. all_longer_row_lines = []
  852. all_longer_col_lines = []
  853. # print("split_y", split_y)
  854. # print("split_row_list", split_row_list, len(split_row_list))
  855. # print("split_row_list", split_col_list, len(split_col_list))
  856. # print("area_row_line", area_row_line, len(area_row_line))
  857. # print("area_col_line", area_col_line, len(area_col_line))
  858. for i in range(len(area_row_line)):
  859. if not area_row_line[i] or not area_col_line[i]:
  860. continue
  861. up_line = area_row_line[i][0]
  862. up_line2 = area_row_line2[i][0]
  863. bottom_line = area_row_line[i][1]
  864. bottom_line2 = area_row_line2[i][1]
  865. left_line = area_col_line[i][0]
  866. left_line2 = area_col_line2[i][0]
  867. right_line = area_col_line[i][1]
  868. right_line2 = area_col_line2[i][1]
  869. # 计算单格高度宽度
  870. if len(split_row_list[i]) > 1:
  871. height_dict = {}
  872. for j in range(len(split_row_list[i])):
  873. if j + 1 > len(split_row_list[i]) - 1:
  874. break
  875. height = abs(int(split_row_list[i][j][3] - split_row_list[i][j+1][3]))
  876. if height in height_dict.keys():
  877. height_dict[height] = height_dict[height] + 1
  878. else:
  879. height_dict[height] = 1
  880. height_list = [[x, height_dict[x]] for x in height_dict.keys()]
  881. height_list.sort(key=lambda x: (x[1], -x[0]), reverse=True)
  882. # print("height_list", height_list)
  883. box_height = height_list[0][0]
  884. else:
  885. box_height = 10
  886. if len(split_col_list[i]) > 1:
  887. box_width = abs(split_col_list[i][1][2] - split_col_list[i][0][2])
  888. else:
  889. box_width = 10
  890. print("box_height", box_height, "box_width", box_width)
  891. # cv2.line(image, (int(up_line[0]), int(up_line[1])),
  892. # (int(up_line[2]), int(up_line[3])),
  893. # (255, 255, 0), 2)
  894. # cv2.line(image, (int(right_line[0]), int(right_line[1])),
  895. # (int(right_line[2]), int(right_line[3])),
  896. # (0, 255, 255), 2)
  897. # cv2.imshow("right_line", image)
  898. # cv2.waitKey(0)
  899. # 补左右两条竖线超出来的线的row
  900. if (up_line[1] - left_line[1] >= 10 and up_line[1] - right_line[1] >= 2) or \
  901. (up_line[1] - left_line[1] >= 2 and up_line[1] - right_line[1] >= 10):
  902. if up_line[1] - left_line[1] >= up_line[1] - right_line[1]:
  903. new_row_lines.append([left_line[0], left_line[1], right_line[0], left_line[1]])
  904. new_col_y = left_line[1]
  905. # 补了row,要将其他短的col连到row上
  906. for j in range(len(split_col_list[i])):
  907. col = split_col_list[i][j]
  908. # 且距离不能相差大于一格
  909. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  910. if abs(new_col_y - col[1]) <= box_height:
  911. split_col_list[i][j][1] = min([new_col_y, col[1]])
  912. longer_col_lines.append([col[0], min([new_col_y, col[1]]), col[2], col[3]])
  913. else:
  914. new_row_lines.append([left_line[0], right_line[1], right_line[0], right_line[1]])
  915. new_col_y = right_line[1]
  916. # 补了row,要将其他短的col连到row上
  917. for j in range(len(split_col_list[i])):
  918. # 需判断该线在这个区域中
  919. # if up_line2[1]-3 <= col[1] <= col[3] <= bottom_line2[1]+3:
  920. col = split_col_list[i][j]
  921. # 且距离不能相差太大
  922. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  923. if abs(new_col_y - col[1]) <= box_height:
  924. split_col_list[i][j][1] = min([new_col_y, col[1]])
  925. if (left_line[3] - bottom_line[3] >= 10 and right_line[3] - bottom_line[3] >= 2) or \
  926. (left_line[3] - bottom_line[3] >= 2 and right_line[3] - bottom_line[3] >= 10):
  927. if left_line[3] - bottom_line[3] >= right_line[3] - bottom_line[3]:
  928. new_row_lines.append([left_line[2], left_line[3], right_line[2], left_line[3]])
  929. new_col_y = left_line[3]
  930. # 补了row,要将其他短的col连到row上
  931. for j in range(len(split_col_list[i])):
  932. col = split_col_list[i][j]
  933. # 且距离不能相差太大
  934. if abs(new_col_y - col[3]) <= box_height:
  935. split_col_list[i][j][3] = max([new_col_y, col[3]])
  936. else:
  937. new_row_lines.append([left_line[2], right_line[3], right_line[2], right_line[3]])
  938. new_col_y = right_line[3]
  939. # 补了row,要将其他短的col连到row上
  940. for j in range(len(split_col_list[i])):
  941. col = split_col_list[i][j]
  942. # 且距离不能相差太大
  943. if abs(new_col_y - col[3]) <= box_height:
  944. split_col_list[i][j][3] = max([new_col_y, col[3]])
  945. # 补上下两条横线超出来的线的col
  946. if (left_line[0] - up_line[0] >= 10 and left_line[0] - bottom_line[0] >= 2) or \
  947. (left_line[0] - up_line[0] >= 2 and left_line[0] - bottom_line[0] >= 10):
  948. if left_line[0] - up_line[0] >= left_line[0] - bottom_line[0]:
  949. new_col_lines.append([up_line[0], up_line[1], up_line[0], bottom_line[1]])
  950. new_row_x = up_line[0]
  951. # 补了col,要将其他短的row连到col上
  952. for j in range(len(split_row_list[i])):
  953. row = split_row_list[i][j]
  954. # 且距离不能相差太大
  955. if abs(new_row_x - row[0]) <= box_width:
  956. split_row_list[i][j][0] = min([new_row_x, row[0]])
  957. else:
  958. new_col_lines.append([bottom_line[0], up_line[1], bottom_line[0], bottom_line[1]])
  959. new_row_x = bottom_line[0]
  960. # 补了col,要将其他短的row连到col上
  961. for j in range(len(split_row_list[i])):
  962. row = split_row_list[i][j]
  963. # 且距离不能相差太大
  964. if abs(new_row_x - row[0]) <= box_width:
  965. split_row_list[i][j][0] = min([new_row_x, row[0]])
  966. if (up_line[2] - right_line[2] >= 10 and bottom_line[2] - right_line[2] >= 2) or \
  967. (up_line[2] - right_line[2] >= 2 and bottom_line[2] - right_line[2] >= 10):
  968. if up_line[2] - right_line[2] >= bottom_line[2] - right_line[2]:
  969. new_col_lines.append([up_line[2], up_line[3], up_line[2], bottom_line[3]])
  970. new_row_x = up_line[2]
  971. # 补了col,要将其他短的row连到col上
  972. for j in range(len(split_row_list[i])):
  973. row = split_row_list[i][j]
  974. # 且距离不能相差太大
  975. if abs(new_row_x - row[2]) <= box_width:
  976. split_row_list[i][j][2] = max([new_row_x, row[2]])
  977. else:
  978. new_col_lines.append([bottom_line[2], up_line[3], bottom_line[2], bottom_line[3]])
  979. new_row_x = bottom_line[2]
  980. # 补了col,要将其他短的row连到col上
  981. for j in range(len(split_row_list[i])):
  982. # 需判断该线在这个区域中
  983. # if up_line2[1]-3 <= row[1] <= bottom_line2[1]+3:
  984. row = split_row_list[i][j]
  985. # 且距离不能相差太大
  986. if abs(new_row_x - row[2]) <= box_width:
  987. split_row_list[i][j][2] = max([new_row_x, row[2]])
  988. all_longer_row_lines += split_row_list[i]
  989. all_longer_col_lines += split_col_list[i]
  990. # print("all_longer_row_lines", len(all_longer_row_lines), i)
  991. # print("all_longer_col_lines", len(all_longer_col_lines), i)
  992. # print("new_row_lines", len(new_row_lines), i)
  993. # print("new_col_lines", len(new_col_lines), i)
  994. # 删除表格内部的补线
  995. # temp_list = []
  996. # for row in new_row_lines:
  997. # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
  998. # continue
  999. # temp_list.append(row)
  1000. # print("fix_outline", new_row_lines)
  1001. # new_row_lines = temp_list
  1002. # print("fix_outline", new_row_lines)
  1003. # temp_list = []
  1004. # for col in new_col_lines:
  1005. # if left_line[0]-5 <= col[0] <= right_line[0]+5:
  1006. # continue
  1007. # temp_list.append(col)
  1008. #
  1009. # new_col_lines = temp_list
  1010. # print("fix_outline", new_col_lines)
  1011. # print("fix_outline", new_row_lines)
  1012. # 删除重复包含的补线
  1013. # temp_list = []
  1014. # for row in new_row_lines:
  1015. # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
  1016. # continue
  1017. # temp_list.append(row)
  1018. # new_row_lines = temp_list
  1019. # 展示上下左右边框线
  1020. # for i in range(len(area_row_line)):
  1021. # print("row1", area_row_line[i])
  1022. # print("row2", area_row_line2[i])
  1023. # print("col1", area_col_line[i])
  1024. # print("col2", area_col_line2[i])
  1025. # cv2.line(image, (int(area_row_line[i][0][0]), int(area_row_line[i][0][1])),
  1026. # (int(area_row_line[i][0][2]), int(area_row_line[i][0][3])), (0, 255, 0), 2)
  1027. # cv2.line(image, (int(area_row_line2[i][1][0]), int(area_row_line2[i][1][1])),
  1028. # (int(area_row_line2[i][1][2]), int(area_row_line2[i][1][3])), (0, 0, 255), 2)
  1029. # cv2.imshow("fix_outline", image)
  1030. # cv2.waitKey(0)
  1031. # 展示所有线
  1032. # for line in all_longer_col_lines:
  1033. # cv2.line(image, (int(line[0]), int(line[1])),
  1034. # (int(line[2]), int(line[3])),
  1035. # (0, 255, 0), 2)
  1036. # cv2.imshow("fix_outline", image)
  1037. # cv2.waitKey(0)
  1038. # for line in all_longer_row_lines:
  1039. # cv2.line(image, (int(line[0]), int(line[1])),
  1040. # (int(line[2]), int(line[3])),
  1041. # (0, 0, 255), 2)
  1042. # cv2.imshow("fix_outline", image)
  1043. # cv2.waitKey(0)
  1044. return new_row_lines, new_col_lines, all_longer_row_lines, all_longer_col_lines
  1045. def fix_table(row_point_list, col_point_list, split_y, row_lines, col_lines):
  1046. # 分割线纵坐标
  1047. if len(split_y) < 2:
  1048. return []
  1049. # 获取bbox
  1050. bbox = []
  1051. # 每个点获取与其x最相近和y最相近的点
  1052. for i in range(1, len(split_y)):
  1053. # 循环每行
  1054. for row in row_point_list:
  1055. row.sort(key=lambda x: (x[0], x[1]))
  1056. # 行不在该区域跳过
  1057. if row[0][1] <= split_y[i-1] or row[0][1] >= split_y[i]:
  1058. continue
  1059. # print("len(row)", len(row))
  1060. # print("row", row)
  1061. # 循环行中的点
  1062. for j in range(len(row)):
  1063. if j == len(row) - 1:
  1064. break
  1065. current_point = row[j]
  1066. next_point_in_row_list = row[j+1:]
  1067. # 循环这一行的下一个点
  1068. for next_point_in_row in next_point_in_row_list:
  1069. # 是否在这一行点找到,找不到就这一行的下个点
  1070. not_found = 1
  1071. # 查询下个点所在列
  1072. next_col = []
  1073. for col in col_point_list:
  1074. col.sort(key=lambda x: (x[1], x[0]))
  1075. # 列不在该区域跳过
  1076. if col[0][1] <= split_y[i-1] or col[-1][1] >= split_y[i]:
  1077. continue
  1078. if col[0][0]-3 <= next_point_in_row[0] <= col[0][0]+3:
  1079. next_col = col
  1080. break
  1081. # 循环匹配当前点和下一列点
  1082. next_col.sort(key=lambda x: (x[1], x[0]))
  1083. for point1 in next_col:
  1084. # 同一行的就跳过
  1085. if current_point[1]-3 <= point1[1] <= current_point[1]+3:
  1086. continue
  1087. if point1[1] <= current_point[1]-3:
  1088. continue
  1089. # 候选bbox
  1090. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  1091. # print("candidate_bbox", candidate_bbox)
  1092. # 判断该bbox是否存在,判断bbox的上下两条边是否有包含在row中
  1093. contain_flag1 = 0
  1094. contain_flag2 = 0
  1095. for row1 in row_lines:
  1096. # 行不在该区域跳过
  1097. if row1[1] <= split_y[i-1] or row1[1] >= split_y[i]:
  1098. continue
  1099. # bbox上边框 y一样
  1100. if not contain_flag1:
  1101. if row1[1]-3 <= candidate_bbox[1] <= row1[1]+3:
  1102. # 格子里的断开线段
  1103. row1_break = (max([row1[0], candidate_bbox[0]]),
  1104. row1[1],
  1105. min([row1[2], candidate_bbox[2]]),
  1106. row1[3])
  1107. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1108. contain_flag1 = 1
  1109. # bbox下边框 y一样
  1110. if not contain_flag2:
  1111. if row1[1]-3 <= candidate_bbox[3] <= row1[1]+3:
  1112. # 格子里的断开线段
  1113. row1_break = (max([row1[0], candidate_bbox[0]]),
  1114. row1[1],
  1115. min([row1[2], candidate_bbox[2]]),
  1116. row1[3])
  1117. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1118. contain_flag2 = 1
  1119. # 判断该bbox是否存在,判断bbox的左右两条边是否有包含在col中
  1120. contain_flag3 = 0
  1121. contain_flag4 = 0
  1122. for col1 in col_lines:
  1123. # 列不在该区域跳过
  1124. if col1[1] <= split_y[i-1] or col1[3] >= split_y[i]:
  1125. continue
  1126. # bbox左边线 x一样
  1127. if not contain_flag3:
  1128. if col1[0]-3 <= candidate_bbox[0] <= col1[0]+3:
  1129. # 格子里的断开线段
  1130. col1_break = (col1[0],
  1131. max([col1[1], candidate_bbox[1]]),
  1132. col1[2],
  1133. min([col1[3], candidate_bbox[3]]))
  1134. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1135. contain_flag3 = 1
  1136. # bbox右边框 x一样
  1137. if not contain_flag4:
  1138. if col1[0]-3 <= candidate_bbox[2] <= col1[0]+3:
  1139. # 格子里的断开线段
  1140. col1_break = (col1[0],
  1141. max([col1[1], candidate_bbox[1]]),
  1142. col1[2],
  1143. min([col1[3], candidate_bbox[3]]))
  1144. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1145. contain_flag4 = 1
  1146. # 找到了该bbox,并且是存在的
  1147. if contain_flag1 and contain_flag2 and contain_flag3 and contain_flag4:
  1148. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  1149. (candidate_bbox[2], candidate_bbox[3])])
  1150. not_found = 0
  1151. break
  1152. if not not_found:
  1153. break
  1154. return bbox
  1155. def delete_close_points(point_list, row_point_list, col_point_list, threshold=5):
  1156. new_point_list = []
  1157. delete_point_list = []
  1158. point_list.sort(key=lambda x: (x[1], x[0]))
  1159. for i in range(len(point_list)):
  1160. point1 = point_list[i]
  1161. if point1 in delete_point_list:
  1162. continue
  1163. if i == len(point_list) - 1:
  1164. new_point_list.append(point1)
  1165. break
  1166. point2 = point_list[i+1]
  1167. # 判断坐标
  1168. if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
  1169. new_point_list.append(point1)
  1170. else:
  1171. # 看两个点上的相同坐标点哪个多,就保留哪个
  1172. count1 = 0
  1173. count2 = 0
  1174. for col in col_point_list:
  1175. if point1[0] == col[0][0]:
  1176. count1 += len(col)
  1177. elif point2[0] == col[0][0]:
  1178. count2 += len(col)
  1179. if count1 >= count2:
  1180. new_point_list.append(point1)
  1181. delete_point_list.append(point2)
  1182. else:
  1183. new_point_list.append(point2)
  1184. delete_point_list.append(point1)
  1185. point_list = new_point_list
  1186. new_point_list = []
  1187. delete_point_list = []
  1188. point_list.sort(key=lambda x: (x[0], x[1]))
  1189. for i in range(len(point_list)):
  1190. point1 = point_list[i]
  1191. if point1 in delete_point_list:
  1192. continue
  1193. if i == len(point_list) - 1:
  1194. new_point_list.append(point1)
  1195. break
  1196. point2 = point_list[i+1]
  1197. # 判断坐标
  1198. if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
  1199. new_point_list.append(point1)
  1200. else:
  1201. count1 = 0
  1202. count2 = 0
  1203. for row in row_point_list:
  1204. if point1[0] == row[0][0]:
  1205. count1 += len(row)
  1206. elif point2[0] == row[0][0]:
  1207. count2 += len(row)
  1208. if count1 >= count2:
  1209. new_point_list.append(point1)
  1210. delete_point_list.append(point2)
  1211. else:
  1212. new_point_list.append(point2)
  1213. delete_point_list.append(point1)
  1214. return new_point_list
  1215. def get_bbox2(image_np, points):
  1216. # # 坐标点按行分
  1217. # row_point_list = []
  1218. # row_point = []
  1219. # points.sort(key=lambda x: (x[0], x[1]))
  1220. # for p in points:
  1221. # if len(row_point) == 0:
  1222. # x = p[0]
  1223. # if x-5 <= p[0] <= x+5:
  1224. # row_point.append(p)
  1225. # else:
  1226. # row_point_list.append(row_point)
  1227. # row_point = []
  1228. # # 坐标点按列分
  1229. # col_point_list = []
  1230. # col_point = []
  1231. # points.sort(key=lambda x: (x[1], x[0]))
  1232. # for p in points:
  1233. # if len(col_point) == 0:
  1234. # y = p[1]
  1235. # if y-5 <= p[1] <= y+5:
  1236. # col_point.append(p)
  1237. # else:
  1238. # col_point_list.append(col_point)
  1239. # col_point = []
  1240. row_point_list = get_points_row(points)
  1241. col_point_list = get_points_col(points)
  1242. print("len(points)", len(points))
  1243. for point in points:
  1244. cv2.circle(image_np, point, 1, (0, 255, 0), 1)
  1245. cv2.imshow("points_deleted", image_np)
  1246. points = delete_close_points(points, row_point_list, col_point_list)
  1247. print("len(points)", len(points))
  1248. for point in points:
  1249. cv2.circle(image_np, point, 1, (255, 0, 0), 3)
  1250. cv2.imshow("points_deleted", image_np)
  1251. cv2.waitKey(0)
  1252. row_point_list = get_points_row(points, 5)
  1253. col_point_list = get_points_col(points, 5)
  1254. print("len(row_point_list)", len(row_point_list))
  1255. for row in row_point_list:
  1256. print("row", len(row))
  1257. print("col_point_list", len(col_point_list))
  1258. for col in col_point_list:
  1259. print("col", len(col))
  1260. bbox = []
  1261. for i in range(len(row_point_list)):
  1262. if i == len(row_point_list) - 1:
  1263. break
  1264. # 遍历每个row的point,找到其所在列的下一个点和所在行的下一个点
  1265. current_row = row_point_list[i]
  1266. for j in range(len(current_row)):
  1267. current_point = current_row[j]
  1268. if j == len(current_row) - 1:
  1269. break
  1270. next_row_point = current_row[j+1]
  1271. # 找出当前点所在的col,得到该列下一个point
  1272. current_col = col_point_list[j]
  1273. for k in range(len(current_col)):
  1274. if current_col[k][1] > current_point[1] + 10:
  1275. next_col_point = current_col[k]
  1276. break
  1277. next_row = row_point_list[k]
  1278. for k in range(len(next_row)):
  1279. if next_row[k][0] >= next_row_point[0] + 5:
  1280. next_point = next_row[k]
  1281. break
  1282. # 得到bbox
  1283. bbox.append([(current_point[0], current_point[1]), (next_point[0], next_point[1])])
  1284. # bbox = []
  1285. # for p in points:
  1286. # # print("p", p)
  1287. # p_row = []
  1288. # p_col = []
  1289. # for row in row_point_list:
  1290. # if p[0] == row[0][0]:
  1291. # for p1 in row:
  1292. # if abs(p[1]-p1[1]) <= 5:
  1293. # continue
  1294. # p_row.append([p1, abs(p[1]-p1[1])])
  1295. # p_row.sort(key=lambda x: x[1])
  1296. # for col in col_point_list:
  1297. # if p[1] == col[0][1]:
  1298. # for p2 in col:
  1299. # if abs(p[0]-p2[0]) <= 5:
  1300. # continue
  1301. # p_col.append([p2, abs(p[0]-p2[0])])
  1302. # p_col.sort(key=lambda x: x[1])
  1303. # if len(p_row) == 0 or len(p_col) == 0:
  1304. # continue
  1305. # break_flag = 0
  1306. # for i in range(len(p_row)):
  1307. # for j in range(len(p_col)):
  1308. # # print(p_row[i][0])
  1309. # # print(p_col[j][0])
  1310. # another_point = (p_col[j][0][0], p_row[i][0][1])
  1311. # # print("another_point", another_point)
  1312. # if abs(p[0]-another_point[0]) <= 5 or abs(p[1]-another_point[1]) <= 5:
  1313. # continue
  1314. # if p[0] >= another_point[0] or p[1] >= another_point[1]:
  1315. # continue
  1316. # if another_point in points:
  1317. # box = [p, another_point]
  1318. # box.sort(key=lambda x: x[0])
  1319. # if box not in bbox:
  1320. # bbox.append(box)
  1321. # break_flag = 1
  1322. # break
  1323. # if break_flag:
  1324. # break
  1325. #
  1326. # # delete duplicate
  1327. # delete_bbox = []
  1328. # for i in range(len(bbox)):
  1329. # for j in range(i+1, len(bbox)):
  1330. # if bbox[i][0] == bbox[j][0]:
  1331. # if bbox[i][1][0] - bbox[j][1][0] <= 3 \
  1332. # and bbox[i][1][1] - bbox[j][1][1] <= 3:
  1333. # delete_bbox.append(bbox[j])
  1334. # if bbox[i][1] == bbox[j][1]:
  1335. # if bbox[i][0][0] - bbox[j][0][0] <= 3 \
  1336. # and bbox[i][0][1] - bbox[j][0][1] <= 3:
  1337. # delete_bbox.append(bbox[j])
  1338. # # delete too small area
  1339. # # for box in bbox:
  1340. # # if box[1][0] - box[0][0] <=
  1341. # for d_box in delete_bbox:
  1342. # if d_box in bbox:
  1343. # bbox.remove(d_box)
  1344. # print bbox
  1345. bbox.sort(key=lambda x: (x[0][0], x[0][1], x[1][0], x[1][1]))
  1346. # origin bbox
  1347. # origin_bbox = []
  1348. # for box in bbox:
  1349. # origin_bbox.append([(box[0][0], box[0][1] - 40), (box[1][0], box[1][1] - 40)])
  1350. # for box in origin_bbox:
  1351. # cv2.rectangle(origin_image, box[0], box[1], (0, 0, 255), 2, 8)
  1352. # cv2.imshow('AlanWang', origin_image)
  1353. # cv2.waitKey(0)
  1354. for box in bbox:
  1355. cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
  1356. cv2.imshow('bboxes', image_np)
  1357. cv2.waitKey(0)
  1358. # for point in points:
  1359. # print(point)
  1360. # cv2.circle(image_np, point, 1, (0, 0, 255), 3)
  1361. # cv2.imshow('points', image_np)
  1362. # cv2.waitKey(0)
  1363. return bbox
  1364. def get_bbox1(image_np, points, split_y):
  1365. # 分割线纵坐标
  1366. # print("split_y", split_y)
  1367. if len(split_y) < 2:
  1368. return []
  1369. # 计算行列,剔除相近交点
  1370. row_point_list = get_points_row(points)
  1371. col_point_list = get_points_col(points)
  1372. print("len(row_point_list)", row_point_list)
  1373. print("len(col_point_list)", len(col_point_list))
  1374. # for point in points:
  1375. # cv2.circle(image_np, point, 1, (0, 255, 0), 1)
  1376. # cv2.imshow("points", image_np)
  1377. points = delete_close_points(points, row_point_list, col_point_list)
  1378. # print("len(points)", len(points))
  1379. # for point in points:
  1380. # cv2.circle(image_np, point, 1, (255, 0, 0), 3)
  1381. # cv2.imshow("points_deleted", image_np)
  1382. # cv2.waitKey(0)
  1383. # 获取bbox
  1384. bbox = []
  1385. # 每个点获取与其x最相近和y最相近的点
  1386. for i in range(1, len(split_y)):
  1387. for point1 in points:
  1388. if point1[1] <= split_y[i-1] or point1[1] >= split_y[i]:
  1389. continue
  1390. distance_x = 10000
  1391. distance_y = 10000
  1392. x = 0
  1393. y = 0
  1394. threshold = 10
  1395. for point2 in points:
  1396. if point2[1] <= split_y[i-1] or point2[1] >= split_y[i]:
  1397. continue
  1398. # 最近 x y
  1399. if 2 < point2[0] - point1[0] < distance_x and point2[1] - point1[1] <= threshold:
  1400. distance_x = point2[0] - point1[0]
  1401. x = point2[0]
  1402. if 2 < point2[1] - point1[1] < distance_y and point2[0] - point1[0] <= threshold:
  1403. distance_y = point2[1] - point1[1]
  1404. y = point2[1]
  1405. if not x or not y:
  1406. continue
  1407. bbox.append([(point1[0], point1[1]), (x, y)])
  1408. # 删除包含关系bbox
  1409. temp_list = []
  1410. for i in range(len(bbox)):
  1411. box1 = bbox[i]
  1412. for j in range(len(bbox)):
  1413. if i == j:
  1414. continue
  1415. box2 = bbox[j]
  1416. contain_flag = 0
  1417. if box2[0][0] <= box1[0][0] <= box1[1][0] <= box2[1][0] and \
  1418. box2[0][1] <= box1[0][1] <= box1[1][1] <= box2[1][1]:
  1419. contain_flag = 1
  1420. break
  1421. temp_list.append(box1)
  1422. bbox = temp_list
  1423. # 展示
  1424. for box in bbox:
  1425. # print(box[0], box[1])
  1426. # if abs(box[0][1] - box[1][1]) > abs(box[0][0] - box[1][0]):
  1427. # continue
  1428. cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
  1429. cv2.imshow('bboxes', image_np)
  1430. cv2.waitKey(0)
  1431. return bbox
  1432. def get_bbox0(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  1433. # 分割线纵坐标
  1434. if len(split_y) < 2:
  1435. return []
  1436. # 计算行列,剔除相近交点
  1437. # row_point_list = get_points_row(points)
  1438. # col_point_list = get_points_col(points)
  1439. # points = delete_close_points(points, row_point_list, col_point_list)
  1440. # row_point_list = get_points_row(points)
  1441. # col_point_list = get_points_col(points)
  1442. # 获取bbox
  1443. bbox = []
  1444. # print("get_bbox split_y", split_y)
  1445. # 每个点获取与其x最相近和y最相近的点
  1446. for i in range(1, len(split_y)):
  1447. # 循环每行
  1448. for row in row_point_list:
  1449. row.sort(key=lambda x: (x[0], x[1]))
  1450. # 行不在该区域跳过
  1451. if row[0][1] <= split_y[i-1] or row[0][1] >= split_y[i]:
  1452. continue
  1453. # 循环行中的点
  1454. for j in range(len(row)):
  1455. if j == len(row) - 1:
  1456. break
  1457. current_point = row[j]
  1458. next_point_in_row = row[j+1]
  1459. # 查询下个点所在列
  1460. next_col = []
  1461. for col in col_point_list:
  1462. col.sort(key=lambda x: (x[1], x[0]))
  1463. # 列不在该区域跳过
  1464. if col[0][1] <= split_y[i-1] or col[-1][1] >= split_y[i]:
  1465. continue
  1466. if col[0][0]-3 <= next_point_in_row[0] <= col[0][0]+3:
  1467. next_col = col
  1468. break
  1469. # 循环匹配当前点和下一列点
  1470. for point1 in next_col:
  1471. # 同一行的就跳过
  1472. if current_point[1]-3 <= point1[1] <= current_point[1]+3:
  1473. continue
  1474. if point1[1] <= current_point[1]-3:
  1475. continue
  1476. # 候选bbox
  1477. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  1478. # 判断该bbox是否存在,线条包含关系
  1479. contain_flag1 = 0
  1480. contain_flag2 = 0
  1481. for row1 in row_lines:
  1482. # 行不在该区域跳过
  1483. if row1[1] <= split_y[i-1] or row1[1] >= split_y[i]:
  1484. continue
  1485. # bbox上边框 y一样
  1486. if not contain_flag1:
  1487. if row1[1]-3 <= candidate_bbox[1] <= row1[1]+3:
  1488. # candidate的x1,x2需被包含在row线中
  1489. if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  1490. contain_flag1 = 1
  1491. # bbox下边框 y一样
  1492. if not contain_flag2:
  1493. if row1[1]-3 <= candidate_bbox[3] <= row1[1]+3:
  1494. # candidate的x1,x2需被包含在row线中
  1495. if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  1496. contain_flag2 = 1
  1497. # 找到了该bbox,并且是存在的
  1498. if contain_flag1 and contain_flag2:
  1499. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  1500. (candidate_bbox[2], candidate_bbox[3])])
  1501. break
  1502. return bbox
  1503. def get_bbox3(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  1504. # 分割线纵坐标
  1505. if len(split_y) < 2:
  1506. return []
  1507. # 获取bbox
  1508. bbox = []
  1509. # 每个点获取与其x最相近和y最相近的点
  1510. for i in range(1, len(split_y)):
  1511. # 循环每行
  1512. for row in row_point_list:
  1513. row.sort(key=lambda x: (x[0], x[1]))
  1514. # 行不在该区域跳过
  1515. if row[0][1] <= split_y[i-1] or row[0][1] >= split_y[i]:
  1516. continue
  1517. # print("len(row)", len(row))
  1518. # print("row", row)
  1519. # 循环行中的点
  1520. for j in range(len(row)):
  1521. if j == len(row) - 1:
  1522. break
  1523. current_point = row[j]
  1524. # print("current_point", current_point)
  1525. next_point_in_row_list = row[j+1:]
  1526. # 循环这一行的下一个点
  1527. for next_point_in_row in next_point_in_row_list:
  1528. # 是否在这一行点找到,找不到就这一行的下个点
  1529. not_found = 1
  1530. # 查询下个点所在列
  1531. next_col = []
  1532. for col in col_point_list:
  1533. col.sort(key=lambda x: (x[1], x[0]))
  1534. # 列不在该区域跳过
  1535. if col[0][1] <= split_y[i-1] or col[-1][1] >= split_y[i]:
  1536. continue
  1537. if col[0][0]-3 <= next_point_in_row[0] <= col[0][0]+3:
  1538. next_col = col
  1539. break
  1540. # 循环匹配当前点和下一列点
  1541. next_col.sort(key=lambda x: (x[1], x[0]))
  1542. for point1 in next_col:
  1543. # 同一行的就跳过
  1544. if current_point[1]-3 <= point1[1] <= current_point[1]+3:
  1545. continue
  1546. if point1[1] <= current_point[1]-3:
  1547. continue
  1548. # 候选bbox
  1549. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  1550. # print("candidate_bbox", candidate_bbox)
  1551. # 判断该bbox是否存在,判断bbox的上下两条边是否有包含在row中
  1552. contain_flag1 = 0
  1553. contain_flag2 = 0
  1554. for row1 in row_lines:
  1555. # 行不在该区域跳过
  1556. if row1[1] <= split_y[i-1] or row1[1] >= split_y[i]:
  1557. continue
  1558. # bbox上边框 y一样
  1559. if not contain_flag1:
  1560. if row1[1]-3 <= candidate_bbox[1] <= row1[1]+3:
  1561. # 格子里的断开线段
  1562. row1_break = (max([row1[0], candidate_bbox[0]]),
  1563. row1[1],
  1564. min([row1[2], candidate_bbox[2]]),
  1565. row1[3])
  1566. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1567. contain_flag1 = 1
  1568. # # candidate的x1,x2需被包含在row线中
  1569. # if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  1570. # contain_flag1 = 1
  1571. #
  1572. # # 判断线条有无端点在格子中
  1573. # elif candidate_bbox[0] < row1[0] < candidate_bbox[2] \
  1574. # or candidate_bbox[0] < row1[2] < candidate_bbox[2]:
  1575. # # 线条会有缺一点情况,判断长度超过格子一半
  1576. # if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1577. # contain_flag1 = 1
  1578. # bbox下边框 y一样
  1579. if not contain_flag2:
  1580. if row1[1]-3 <= candidate_bbox[3] <= row1[1]+3:
  1581. # 格子里的断开线段
  1582. row1_break = (max([row1[0], candidate_bbox[0]]),
  1583. row1[1],
  1584. min([row1[2], candidate_bbox[2]]),
  1585. row1[3])
  1586. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1587. contain_flag2 = 1
  1588. # # candidate的x1,x2需被包含在row线中
  1589. # if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  1590. # contain_flag2 = 1
  1591. #
  1592. # # 判断线条有无端点在格子中
  1593. # elif candidate_bbox[0] < row1[0] < candidate_bbox[2] \
  1594. # or candidate_bbox[0] < row1[2] < candidate_bbox[2]:
  1595. # # 线条会有缺一点情况,判断长度超过格子一半
  1596. # if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  1597. # contain_flag2 = 1
  1598. # 判断该bbox是否存在,判断bbox的左右两条边是否有包含在col中
  1599. contain_flag3 = 0
  1600. contain_flag4 = 0
  1601. for col1 in col_lines:
  1602. # 列不在该区域跳过
  1603. if col1[1] <= split_y[i-1] or col1[3] >= split_y[i]:
  1604. continue
  1605. # bbox左边线 x一样
  1606. if not contain_flag3:
  1607. if col1[0]-3 <= candidate_bbox[0] <= col1[0]+3:
  1608. # 格子里的断开线段
  1609. col1_break = (col1[0],
  1610. max([col1[1], candidate_bbox[1]]),
  1611. col1[2],
  1612. min([col1[3], candidate_bbox[3]]))
  1613. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1614. contain_flag3 = 1
  1615. # # candidate的y1,y2需被包含在col线中
  1616. # if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
  1617. # contain_flag3 = 1
  1618. #
  1619. # # 判断线条有无端点在格子中
  1620. # elif candidate_bbox[1] < col1[1] < candidate_bbox[3] \
  1621. # or candidate_bbox[1] < col1[3] < candidate_bbox[3]:
  1622. # # 线条会有缺一点情况,判断长度超过格子一半
  1623. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1624. # contain_flag3 = 1
  1625. # bbox右边框 x一样
  1626. if not contain_flag4:
  1627. if col1[0]-3 <= candidate_bbox[2] <= col1[0]+3:
  1628. # 格子里的断开线段
  1629. # col1_break = (col1[0],
  1630. # max([col1[1], candidate_bbox[1]]),
  1631. # col1[2],
  1632. # min([col1[3], candidate_bbox[3]]))
  1633. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1634. # contain_flag4 = 1
  1635. # 如果候选bbox的边的上1/3或下1/3包含在col中
  1636. candidate_bbox_line1 = [candidate_bbox[1],
  1637. candidate_bbox[1] + (candidate_bbox[3]-candidate_bbox[1])/3]
  1638. candidate_bbox_line2 = [candidate_bbox[3] - (candidate_bbox[3]-candidate_bbox[1])/3,
  1639. candidate_bbox[3]]
  1640. if col1[1] <= candidate_bbox_line1[0] <= candidate_bbox_line1[1] <= col1[3] \
  1641. or col1[1] <= candidate_bbox_line2[0] <= candidate_bbox_line2[1] <= col1[3]:
  1642. # print("candidate_bbox", candidate_bbox)
  1643. # print("col1", col1)
  1644. contain_flag4 = 1
  1645. # # candidate的y1,y2需被包含在col线中
  1646. # if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
  1647. # contain_flag4 = 1
  1648. #
  1649. # # 判断线条有无端点在格子中
  1650. # elif candidate_bbox[1] < col1[1] < candidate_bbox[3] \
  1651. # or candidate_bbox[1] < col1[3] < candidate_bbox[3]:
  1652. # # 线条会有缺一点情况,判断长度超过格子一半
  1653. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  1654. # contain_flag4 = 1
  1655. # 找到了该bbox,并且是存在的
  1656. if contain_flag1 and contain_flag2 and contain_flag3 and contain_flag4:
  1657. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  1658. (candidate_bbox[2], candidate_bbox[3])])
  1659. not_found = 0
  1660. # print("exist candidate_bbox", candidate_bbox)
  1661. # print(contain_flag1, contain_flag2, contain_flag3, contain_flag4)
  1662. break
  1663. # else:
  1664. # print("candidate_bbox", candidate_bbox)
  1665. # print(contain_flag1, contain_flag2, contain_flag3, contain_flag4)
  1666. if not not_found:
  1667. break
  1668. return bbox
  1669. def get_bbox(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  1670. # 分割线纵坐标
  1671. if len(split_y) < 2:
  1672. return []
  1673. # 获取bbox
  1674. bbox_list = []
  1675. for i in range(1, len(split_y)):
  1676. last_y = split_y[i-1]
  1677. y = split_y[i]
  1678. # 先对点线进行分区
  1679. split_row_point_list = []
  1680. split_col_point_list = []
  1681. split_row_lines = []
  1682. split_col_lines = []
  1683. for row in row_point_list:
  1684. if last_y <= row[0][1] <= y:
  1685. row.sort(key=lambda x: (x[1], x[0]))
  1686. split_row_point_list.append(row)
  1687. for col in col_point_list:
  1688. if last_y <= col[0][1] <= y:
  1689. split_col_point_list.append(col)
  1690. for row in row_lines:
  1691. if last_y <= row[1] <= y:
  1692. split_row_lines.append(row)
  1693. for col in col_lines:
  1694. if last_y <= col[1] <= y:
  1695. split_col_lines.append(col)
  1696. # 每个点获取其对角线点,以便形成bbox,按行循环
  1697. for i in range(len(split_row_point_list)-1):
  1698. row = split_row_point_list[i]
  1699. # 循环该行的点
  1700. for k in range(len(row)-1):
  1701. point1 = row[k]
  1702. next_point1 = row[k+1]
  1703. # print("*"*30)
  1704. # print("point1", point1)
  1705. # 有三种对角线点
  1706. # 1. 该点下一行的下一列的点
  1707. # 2. 该点下一列的下一行的点
  1708. # 3. 上述两个点是同一个点
  1709. # 下一行没找到就循环后面的行
  1710. if_find = 0
  1711. for j in range(i+1, len(split_row_point_list)):
  1712. if if_find:
  1713. break
  1714. next_row = split_row_point_list[j]
  1715. # print("next_row", next_row)
  1716. # 循环下一行的点
  1717. for point2 in next_row:
  1718. if abs(point1[0] - point2[0]) <= 2:
  1719. continue
  1720. if point2[0] < point1[0]:
  1721. continue
  1722. bbox = [point1[0], point1[1], point2[0], point2[1]]
  1723. if abs(bbox[0] - bbox[2]) <= 10:
  1724. continue
  1725. if abs(bbox[1] - bbox[3]) <= 10:
  1726. continue
  1727. # bbox的四条边都需要验证是否在line上
  1728. if check_bbox(bbox, split_row_lines, split_col_lines):
  1729. bbox_list.append([(bbox[0], bbox[1]), (bbox[2], bbox[3])])
  1730. if_find = 1
  1731. # print("check bbox", bbox)
  1732. break
  1733. return bbox_list
  1734. def check_bbox(bbox, rows, cols, threshold=5):
  1735. def check(check_line, lines, limit_axis, axis):
  1736. # 需检查的线的1/2段,1/3段,2/3段,1/4段,3/4段
  1737. line_1_2 = [check_line[0], (check_line[0]+check_line[1])/2]
  1738. line_2_2 = [(check_line[0]+check_line[1])/2, check_line[1]]
  1739. line_1_3 = [check_line[0], check_line[0]+(check_line[1]-check_line[0])/3]
  1740. line_2_3 = [check_line[1]-(check_line[1]-check_line[0])/3, check_line[1]]
  1741. line_1_4 = [check_line[0], check_line[0]+(check_line[1]-check_line[0])/4]
  1742. line_3_4 = [check_line[1]-(check_line[1]-check_line[0])/4, check_line[1]]
  1743. # 限制row相同y,col相同x
  1744. if_line = 0
  1745. for line1 in lines:
  1746. if not if_line and abs(line1[1-axis] - limit_axis) <= threshold:
  1747. # check_line完全包含在line中
  1748. if line1[axis] <= check_line[0] <= check_line[1] <= line1[axis+2]:
  1749. if_line = 1
  1750. # check_line的1/2包含在line
  1751. elif line1[axis] <= line_1_2[0] <= line_1_2[1] <= line1[axis+2] \
  1752. or line1[axis] <= line_2_2[0] <= line_2_2[1] <= line1[axis+2]:
  1753. if_line = 1
  1754. # check_line两个1/3段被包含在不同line中
  1755. elif line1[axis] <= line_1_3[0] <= line_1_3[1] <= line1[axis+2]:
  1756. # check_line另一边的1/4被包含
  1757. for line2 in lines:
  1758. if abs(line1[1-axis] - limit_axis) <= threshold:
  1759. if line2[axis] <= line_3_4[0] <= line_3_4[1] <= line2[axis+2]:
  1760. if_line = 1
  1761. break
  1762. elif line1[axis] <= line_2_3[0] <= line_2_3[1] <= line1[axis+2]:
  1763. # check_line另一边的1/4被包含
  1764. for line2 in lines:
  1765. if abs(line1[1-axis] - limit_axis) <= threshold:
  1766. if line2[axis] <= line_1_4[0] <= line_1_4[1] <= line2[axis+2]:
  1767. if_line = 1
  1768. break
  1769. return if_line
  1770. up_down_line = [bbox[0], bbox[2]]
  1771. up_y, down_y = bbox[1], bbox[3]
  1772. left_right_line = [bbox[1], bbox[3]]
  1773. left_x, right_x = bbox[0], bbox[2]
  1774. # 检查bbox四条边是否存在
  1775. if_up = check(up_down_line, rows, up_y, 0)
  1776. if_down = check(up_down_line, rows, down_y, 0)
  1777. if_left = check(left_right_line, cols, left_x, 1)
  1778. if_right = check(left_right_line, cols, right_x, 1)
  1779. # 检查bbox内部除了四条边,是否有其它line在bbox内部
  1780. if_col = 0
  1781. if_row = 0
  1782. if if_up and if_down and if_left and if_right:
  1783. for col in cols:
  1784. if not if_col and left_x+threshold <= col[0] <= right_x-threshold:
  1785. if col[1] <= left_right_line[0] <= left_right_line[1] <= col[3]:
  1786. if_col = 1
  1787. elif left_right_line[0] <= col[1] <= left_right_line[1]:
  1788. if left_right_line[1] - col[1] >= (left_right_line[1] + left_right_line[0])/2:
  1789. if_col = 1
  1790. elif left_right_line[0] <= col[3] <= left_right_line[1]:
  1791. if col[3] - left_right_line[0] >= (left_right_line[1] + left_right_line[0])/2:
  1792. if_col = 1
  1793. for row in rows:
  1794. if not if_row and up_y+threshold <= row[1] <= down_y-threshold:
  1795. if row[0] <= up_down_line[0] <= up_down_line[1] <= row[2]:
  1796. if_row = 1
  1797. elif up_down_line[0] <= row[0] <= up_down_line[1]:
  1798. if up_down_line[1] - row[0] >= (up_down_line[1] + up_down_line[0])/2:
  1799. if_row = 1
  1800. elif up_down_line[0] <= row[2] <= up_down_line[1]:
  1801. if row[2] - up_down_line[0] >= (up_down_line[1] + up_down_line[0])/2:
  1802. if_row = 1
  1803. if if_up and if_down and if_left and if_right and not if_col and not if_row:
  1804. return True
  1805. else:
  1806. return False
  1807. def add_continue_bbox(bboxes):
  1808. add_bbox_list = []
  1809. bboxes.sort(key=lambda x: (x[0][0], x[0][1]))
  1810. last_bbox = bboxes[0]
  1811. # 先对bbox分区
  1812. for i in range(1, len(split_y)):
  1813. y = split_y[i]
  1814. last_y = split_y[i-1]
  1815. split_bbox = []
  1816. for bbox in bboxes:
  1817. if last_y <= bbox[1][1] <= y:
  1818. split_bbox.append(bbox)
  1819. split_bbox.sort
  1820. for i in range(1, len(bboxes)):
  1821. bbox = bboxes[i]
  1822. if last_y <= bbox[1][1] <= y and last_y <= last_bbox[1][1] <= y:
  1823. if abs(last_bbox[1][1] - bbox[0][1]) <= 2:
  1824. last_bbox = bbox
  1825. else:
  1826. if last_bbox[1][1] > bbox[0][1]:
  1827. last_bbox = bbox
  1828. else:
  1829. add_bbox = [(last_bbox[0][0], last_bbox[1][1]),
  1830. (last_bbox[1][0], bbox[0][1])]
  1831. add_bbox_list.append(add_bbox)
  1832. last_y = y
  1833. print("add_bbox_list", add_bbox_list)
  1834. if add_bbox_list:
  1835. bboxes = [str(x) for x in bboxes + add_bbox_list]
  1836. bboxes = list(set(bboxes))
  1837. bboxes = [eval(x) for x in bboxes]
  1838. bboxes.sort(key=lambda x: (x[0][1], x[0][0]))
  1839. return bboxes
  1840. def points_to_line(points_lines, axis):
  1841. new_line_list = []
  1842. for line in points_lines:
  1843. average = 0
  1844. _min = _min = line[0][axis]
  1845. _max = line[-1][axis]
  1846. for point in line:
  1847. average += point[1-axis]
  1848. if point[axis] < _min:
  1849. _min = point[axis]
  1850. if point[axis] > _max:
  1851. _max = point[axis]
  1852. average = int(average / len(line))
  1853. if axis:
  1854. new_line = [average, _min, average, _max]
  1855. else:
  1856. new_line = [_min, average, _max, average]
  1857. new_line_list.append(new_line)
  1858. return new_line_list
  1859. def get_bbox_by_contours(image_np):
  1860. img_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  1861. ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
  1862. # 3.连通域分析
  1863. img_bin, contours, hierarchy = cv2.findContours(img_bin,
  1864. cv2.RETR_LIST,
  1865. cv2.CHAIN_APPROX_SIMPLE)
  1866. # 4.获取最小外接圆 圆心 半径
  1867. center, radius = cv2.minEnclosingTriangle(contours[0])
  1868. center = np.int0(center)
  1869. # 5.绘制最小外接圆
  1870. img_result = image_np.copy()
  1871. cv2.circle(img_result, tuple(center), int(radius), (255, 255, 255), 2)
  1872. # # 读入图片
  1873. # img = image_np
  1874. # cv2.imshow("get_bbox_by_contours ", image_np)
  1875. # # 中值滤波,去噪
  1876. # img = cv2.medianBlur(img, 3)
  1877. # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  1878. # cv2.namedWindow('original', cv2.WINDOW_AUTOSIZE)
  1879. # cv2.imshow('original', gray)
  1880. #
  1881. # # 阈值分割得到二值化图片
  1882. # ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  1883. #
  1884. # # 膨胀操作
  1885. # kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  1886. # bin_clo = cv2.dilate(binary, kernel2, iterations=2)
  1887. #
  1888. # # 连通域分析
  1889. # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(bin_clo, connectivity=8)
  1890. #
  1891. # # 查看各个返回值
  1892. # # 连通域数量
  1893. # print('num_labels = ',num_labels)
  1894. # # 连通域的信息:对应各个轮廓的x、y、width、height和面积
  1895. # print('stats = ',stats)
  1896. # # 连通域的中心点
  1897. # print('centroids = ',centroids)
  1898. # # 每一个像素的标签1、2、3.。。,同一个连通域的标签是一致的
  1899. # print('labels = ',labels)
  1900. #
  1901. # # 不同的连通域赋予不同的颜色
  1902. # output = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)
  1903. # for i in range(1, num_labels):
  1904. #
  1905. # mask = labels == i
  1906. # output[:, :, 0][mask] = np.random.randint(0, 255)
  1907. # output[:, :, 1][mask] = np.random.randint(0, 255)
  1908. # output[:, :, 2][mask] = np.random.randint(0, 255)
  1909. # cv2.imshow('oginal', output)
  1910. # cv2.waitKey()
  1911. # cv2.destroyAllWindows()
  1912. def get_points_col(points, split_y, threshold=5):
  1913. # 坐标点按行分
  1914. row_point_list = []
  1915. row_point = []
  1916. points.sort(key=lambda x: (x[0], x[1]))
  1917. # print("get_points_col points sort", points)
  1918. x = points[0][0]
  1919. for i in range(1, len(split_y)):
  1920. for p in points:
  1921. if p[1] <= split_y[i-1] or p[1] >= split_y[i]:
  1922. continue
  1923. if x-threshold <= p[0] <= x+threshold:
  1924. row_point.append(p)
  1925. else:
  1926. # print("row_point", row_point)
  1927. row_point.sort(key=lambda x: (x[1], x[0]))
  1928. if row_point:
  1929. row_point_list.append(row_point)
  1930. row_point = []
  1931. x = p[0]
  1932. row_point.append(p)
  1933. if row_point:
  1934. row_point_list.append(row_point)
  1935. return row_point_list
  1936. def get_points_row(points, split_y, threshold=5):
  1937. # 坐标点按列分
  1938. col_point_list = []
  1939. col_point = []
  1940. points.sort(key=lambda x: (x[1], x[0]))
  1941. y = points[0][1]
  1942. for i in range(len(split_y)):
  1943. for p in points:
  1944. if p[1] <= split_y[i-1] or p[1] >= split_y[i]:
  1945. continue
  1946. if y-threshold <= p[1] <= y+threshold:
  1947. col_point.append(p)
  1948. else:
  1949. col_point.sort(key=lambda x: (x[0], x[1]))
  1950. if col_point:
  1951. col_point_list.append(col_point)
  1952. col_point = []
  1953. y = p[1]
  1954. col_point.append(p)
  1955. if col_point:
  1956. col_point_list.append(col_point)
  1957. return col_point_list
  1958. def get_outline_point(points, split_y):
  1959. # 分割线纵坐标
  1960. # print("get_outline_point split_y", split_y)
  1961. if len(split_y) < 2:
  1962. return []
  1963. outline_2point = []
  1964. points.sort(key=lambda x: (x[1], x[0]))
  1965. for i in range(1, len(split_y)):
  1966. area_points = []
  1967. for point in points:
  1968. if point[1] <= split_y[i-1] or point[1] >= split_y[i]:
  1969. continue
  1970. area_points.append(point)
  1971. if area_points:
  1972. area_points.sort(key=lambda x: (x[1], x[0]))
  1973. outline_2point.append([area_points[0], area_points[-1]])
  1974. return outline_2point
  1975. # def merge_row(row_lines):
  1976. # for row in row_lines:
  1977. # for row1 in row_lines:
  1978. def get_best_predict_size(image_np):
  1979. sizes = [1280, 1152, 1024, 896, 768, 640, 512, 384, 256, 128]
  1980. min_len = 10000
  1981. best_height = sizes[0]
  1982. for height in sizes:
  1983. if abs(image_np.shape[0] - height) < min_len:
  1984. min_len = abs(image_np.shape[0] - height)
  1985. best_height = height
  1986. min_len = 10000
  1987. best_width = sizes[0]
  1988. for width in sizes:
  1989. if abs(image_np.shape[1] - width) < min_len:
  1990. min_len = abs(image_np.shape[1] - width)
  1991. best_width = width
  1992. return best_height, best_width
  1993. def choose_longer_row(lines):
  1994. new_row = []
  1995. jump_row = []
  1996. for i in range(len(lines)):
  1997. row1 = lines[i]
  1998. jump_flag = 0
  1999. if row1 in jump_row:
  2000. continue
  2001. for j in range(i+1, len(lines)):
  2002. row2 = lines[j]
  2003. if row2 in jump_row:
  2004. continue
  2005. if row2[1]-5 <= row1[1] <= row2[1]+5:
  2006. if row1[0] <= row2[0] and row1[2] >= row2[2]:
  2007. new_row.append(row1)
  2008. jump_row.append(row1)
  2009. jump_row.append(row2)
  2010. jump_flag = 1
  2011. break
  2012. elif row2[0] <= row1[0] and row2[2] >= row1[2]:
  2013. new_row.append(row2)
  2014. jump_row.append(row1)
  2015. jump_row.append(row2)
  2016. jump_flag = 1
  2017. break
  2018. if not jump_flag:
  2019. new_row.append(row1)
  2020. jump_row.append(row1)
  2021. return new_row
  2022. def choose_longer_col(lines):
  2023. new_col = []
  2024. jump_col = []
  2025. for i in range(len(lines)):
  2026. col1 = lines[i]
  2027. jump_flag = 0
  2028. if col1 in jump_col:
  2029. continue
  2030. for j in range(i+1, len(lines)):
  2031. col2 = lines[j]
  2032. if col2 in jump_col:
  2033. continue
  2034. if col2[0]-5 <= col1[0] <= col2[0]+5:
  2035. if col1[1] <= col2[1] and col1[3] >= col2[3]:
  2036. new_col.append(col1)
  2037. jump_col.append(col1)
  2038. jump_col.append(col2)
  2039. jump_flag = 1
  2040. break
  2041. elif col2[1] <= col1[1] and col2[3] >= col1[3]:
  2042. new_col.append(col2)
  2043. jump_col.append(col1)
  2044. jump_col.append(col2)
  2045. jump_flag = 1
  2046. break
  2047. if not jump_flag:
  2048. new_col.append(col1)
  2049. jump_col.append(col1)
  2050. return new_col
  2051. def delete_contain_bbox(bboxes):
  2052. # bbox互相包含,取小的bbox
  2053. delete_bbox = []
  2054. for i in range(len(bboxes)):
  2055. for j in range(i+1, len(bboxes)):
  2056. bbox1 = bboxes[i]
  2057. bbox2 = bboxes[j]
  2058. # 横坐标相等情况
  2059. if bbox1[0][0] == bbox2[0][0] and bbox1[1][0] == bbox2[1][0]:
  2060. if bbox1[0][1] <= bbox2[0][1] <= bbox2[1][1] <= bbox1[1][1]:
  2061. # print("1", bbox1, bbox2)
  2062. delete_bbox.append(bbox1)
  2063. elif bbox2[0][1] <= bbox1[0][1] <= bbox1[1][1] <= bbox2[1][1]:
  2064. # print("2", bbox1, bbox2)
  2065. delete_bbox.append(bbox2)
  2066. # 纵坐标相等情况
  2067. elif bbox1[0][1] == bbox2[0][1] and bbox1[1][1] == bbox2[1][1]:
  2068. if bbox1[0][0] <= bbox2[0][0] <= bbox2[1][0] <= bbox1[1][0]:
  2069. print("3", bbox1, bbox2)
  2070. delete_bbox.append(bbox1)
  2071. elif bbox2[0][0] <= bbox1[0][0] <= bbox1[1][0] <= bbox2[1][0]:
  2072. print("4", bbox1, bbox2)
  2073. delete_bbox.append(bbox2)
  2074. print("delete_contain_bbox len(bboxes)", len(bboxes))
  2075. print("delete_contain_bbox len(delete_bbox)", len(delete_bbox))
  2076. for bbox in delete_bbox:
  2077. if bbox in bboxes:
  2078. bboxes.remove(bbox)
  2079. print("delete_contain_bbox len(bboxes)", len(bboxes))
  2080. return bboxes
  2081. if __name__ == '__main__':
  2082. # p = "开标记录表3_page_0.png"
  2083. # p = "train_data/label_1.jpg"
  2084. # p = "test_files/train_463.jpg"
  2085. p = "test_files/8.png"
  2086. # p = "test_files/无边框3.jpg"
  2087. # p = "test_files/part1.png"
  2088. # p = "D:\\Project\\format_conversion\\appendix_test\\temp\\00e959a0bc9011ebaf5a00163e0ae709" + \
  2089. # "\\00e95f7cbc9011ebaf5a00163e0ae709_pdf_page0.png"
  2090. # p = "D:\\Project\\format_conversion\\appendix_test\\temp\\00fb3e52bc7e11eb836000163e0ae709" + \
  2091. # "\\00fb43acbc7e11eb836000163e0ae709.png"
  2092. # p = "test_files/table.jpg"
  2093. # p = "data_process/create_data/0.jpg"
  2094. # p = "../format_conversion/temp/f1fe9c4ac8e511eb81d700163e0857b6/f1fea1e0c8e511eb81d700163e0857b6.png"
  2095. # p = "../format_conversion/1.png"
  2096. img = cv2.imread(p)
  2097. t = time.time()
  2098. model.load_weights("")
  2099. best_h, best_w = get_best_predict_size(img)
  2100. print(img.shape)
  2101. print((best_h, best_w))
  2102. # row_boxes, col_boxes = table_line(img[..., ::-1], model, size=(512, 1024), hprob=0.5, vprob=0.5)
  2103. # row_boxes, col_boxes, img = table_line(img[..., ::-1], model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
  2104. row_boxes, col_boxes, img = table_line(img, model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
  2105. print("len(row_boxes)", len(row_boxes))
  2106. print("len(col_boxes)", col_boxes)
  2107. # 创建空图
  2108. test_img = np.zeros((img.shape), np.uint8)
  2109. test_img.fill(255)
  2110. for box in row_boxes+col_boxes:
  2111. cv2.line(test_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 0), 1)
  2112. cv2.imshow("test_image", test_img)
  2113. cv2.waitKey(0)
  2114. cv2.imwrite("temp.jpg", test_img)
  2115. # 计算交点、分割线
  2116. crossover_points = get_points(row_boxes, col_boxes, (img.shape[0], img.shape[1]))
  2117. print("len(col_boxes)", len(col_boxes))
  2118. split_lines, split_y = get_split_line(crossover_points, col_boxes, img)
  2119. print("split_y", split_y)
  2120. # for point in crossover_points:
  2121. # cv2.circle(test_img, point, 1, (0, 255, 0), 3)
  2122. # cv2.imshow("point image1", test_img)
  2123. # cv2.waitKey(0)
  2124. # 计算行列,剔除相近交点
  2125. row_point_list = get_points_row(crossover_points, split_y, 0)
  2126. col_point_list = get_points_col(crossover_points, split_y, 0)
  2127. crossover_points = delete_close_points(crossover_points, row_point_list, col_point_list)
  2128. row_point_list = get_points_row(crossover_points, split_y)
  2129. col_point_list = get_points_col(crossover_points, split_y)
  2130. for point in crossover_points:
  2131. cv2.circle(test_img, point, 1, (0, 0, 255), 3)
  2132. cv2.imshow("point image1", test_img)
  2133. cv2.waitKey(0)
  2134. print("len(row_boxes)", len(row_boxes))
  2135. print("len(col_boxes)", len(col_boxes))
  2136. # 修复边框
  2137. new_row_boxes, new_col_boxes, long_row_boxes, long_col_boxes = \
  2138. fix_outline(img, row_boxes, col_boxes, crossover_points, split_y)
  2139. if new_row_boxes or new_col_boxes:
  2140. if long_row_boxes:
  2141. print("long_row_boxes", long_row_boxes)
  2142. row_boxes = long_row_boxes
  2143. if long_col_boxes:
  2144. print("long_col_boxes", long_col_boxes)
  2145. col_boxes = long_col_boxes
  2146. if new_row_boxes:
  2147. row_boxes += new_row_boxes
  2148. print("new_row_boxes", new_row_boxes)
  2149. if new_col_boxes:
  2150. print("new_col_boxes", new_col_boxes)
  2151. col_boxes += new_col_boxes
  2152. # print("len(row_boxes)", len(row_boxes))
  2153. # print("len(col_boxes)", len(col_boxes))
  2154. # row_boxes += new_row_boxes
  2155. # col_boxes += new_col_boxes
  2156. # row_boxes = choose_longer_row(row_boxes)
  2157. # col_boxes = choose_longer_col(col_boxes)
  2158. # 创建空图
  2159. test_img = np.zeros((img.shape), np.uint8)
  2160. test_img.fill(255)
  2161. for box in row_boxes+col_boxes:
  2162. cv2.line(test_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 0), 1)
  2163. cv2.imshow("test_image2", test_img)
  2164. cv2.waitKey(0)
  2165. # 展示补线
  2166. for row in new_row_boxes:
  2167. cv2.line(test_img, (int(row[0]), int(row[1])),
  2168. (int(row[2]), int(row[3])), (0, 0, 255), 1)
  2169. for col in new_col_boxes:
  2170. cv2.line(test_img, (int(col[0]), int(col[1])),
  2171. (int(col[2]), int(col[3])), (0, 0, 255), 1)
  2172. cv2.imshow("fix_outline", test_img)
  2173. cv2.waitKey(0)
  2174. cv2.imwrite("temp.jpg", test_img)
  2175. # 修复边框后重新计算交点、分割线
  2176. print("crossover_points", len(crossover_points))
  2177. crossover_points = get_points(row_boxes, col_boxes, (img.shape[0], img.shape[1]))
  2178. print("crossover_points new", len(crossover_points))
  2179. split_lines, split_y = get_split_line(crossover_points, col_boxes, img)
  2180. # 计算行列,剔除相近交点
  2181. row_point_list = get_points_row(crossover_points, split_y, 0)
  2182. col_point_list = get_points_col(crossover_points, split_y, 0)
  2183. print(len(crossover_points), len(row_point_list), len(col_point_list))
  2184. crossover_points = delete_close_points(crossover_points, row_point_list, col_point_list)
  2185. print(len(crossover_points), len(row_point_list), len(col_point_list))
  2186. row_point_list = get_points_row(crossover_points, split_y)
  2187. col_point_list = get_points_col(crossover_points, split_y)
  2188. for point in crossover_points:
  2189. cv2.circle(test_img, point, 1, (0, 255, 0), 3)
  2190. cv2.imshow("point image2", test_img)
  2191. cv2.waitKey(0)
  2192. # 获取每个表格的左上右下两个点
  2193. outline_point = get_outline_point(crossover_points, split_y)
  2194. # print(outline_point)
  2195. for outline in outline_point:
  2196. cv2.circle(test_img, outline[0], 1, (255, 0, 0), 5)
  2197. cv2.circle(test_img, outline[1], 1, (255, 0, 0), 5)
  2198. cv2.imshow("outline point", test_img)
  2199. cv2.waitKey(0)
  2200. # 获取bbox
  2201. # get_bbox(img, crossover_points, split_y)
  2202. # for point in crossover_points:
  2203. # cv2.circle(test_img, point, 1, (0, 255, 0), 3)
  2204. # cv2.imshow("point image3", test_img)
  2205. # cv2.waitKey(0)
  2206. # split_y = []
  2207. # for outline in outline_point:
  2208. # split_y.extend([outline[0][1]-5, outline[1][1]+5])
  2209. print("len(row_boxes)", len(row_boxes))
  2210. print("len(col_boxes)", len(col_boxes))
  2211. bboxes = get_bbox(img, row_point_list, col_point_list, split_y, row_boxes, col_boxes)
  2212. # 展示
  2213. for box in bboxes:
  2214. # print(box[0], box[1])
  2215. # if abs(box[0][1] - box[1][1]) > abs(box[0][0] - box[1][0]):
  2216. # continue
  2217. cv2.rectangle(test_img, box[0], box[1], (0, 0, 255), 2, 8)
  2218. cv2.imshow('bboxes', test_img)
  2219. cv2.waitKey(0)
  2220. # img = draw_lines(img, row_boxes+col_boxes, color=(255, 0, 0), lineW=2)
  2221. # img = draw_boxes(img, rowboxes+colboxes, color=(0, 0, 255))
  2222. print(time.time()-t, len(row_boxes), len(col_boxes))
  2223. cv2.imwrite('temp.jpg', test_img)
  2224. # cv2.imshow('main', img)
  2225. # cv2.waitKey(0)