table_line.py 125 KB

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