table_line.py 112 KB

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