table_line.py 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797
  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 io
  10. import logging
  11. import pickle
  12. import sys
  13. import traceback
  14. import tensorflow as tf
  15. import tensorflow.keras.backend as K
  16. from tensorflow.keras.models import Model
  17. from tensorflow.keras.layers import Input, concatenate, Conv2D, MaxPooling2D, BatchNormalization, UpSampling2D
  18. from tensorflow.keras.layers import LeakyReLU
  19. from otr.utils import letterbox_image, get_table_line, adjust_lines, line_to_line, draw_boxes
  20. import numpy as np
  21. import cv2
  22. import time
  23. from format_convert import _global
  24. from format_convert.utils import log
  25. def dice_coef(y_true, y_pred, smooth=1e-5):
  26. y_true_f = K.flatten(y_true)
  27. y_pred_f = K.flatten(y_pred)
  28. intersection = K.sum(y_true_f * y_pred_f)
  29. return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
  30. def dice_coef_loss():
  31. def dice_coef_loss_fixed(y_true, y_pred):
  32. return -dice_coef(y_true, y_pred)
  33. return dice_coef_loss_fixed
  34. def focal_loss(gamma=3., alpha=.5):
  35. # 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
  36. # 2 0.85 double_gpu acc-
  37. # 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
  38. # 2 0.25 gpu acc-
  39. # 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
  40. def focal_loss_fixed(y_true, y_pred):
  41. pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
  42. pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
  43. return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(K.epsilon() + pt_1)) - K.sum(
  44. (1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0 + K.epsilon()))
  45. return focal_loss_fixed
  46. def table_net_large(input_shape=(1152, 896, 3), num_classes=1):
  47. inputs = Input(shape=input_shape)
  48. # 512
  49. use_bias = False
  50. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(inputs)
  51. down0a = BatchNormalization()(down0a)
  52. down0a = LeakyReLU(alpha=0.1)(down0a)
  53. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(down0a)
  54. down0a = BatchNormalization()(down0a)
  55. down0a = LeakyReLU(alpha=0.1)(down0a)
  56. down0a_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0a)
  57. # 256
  58. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0a_pool)
  59. down0 = BatchNormalization()(down0)
  60. down0 = LeakyReLU(alpha=0.1)(down0)
  61. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0)
  62. down0 = BatchNormalization()(down0)
  63. down0 = LeakyReLU(alpha=0.1)(down0)
  64. down0_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0)
  65. # 128
  66. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down0_pool)
  67. down1 = BatchNormalization()(down1)
  68. down1 = LeakyReLU(alpha=0.1)(down1)
  69. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down1)
  70. down1 = BatchNormalization()(down1)
  71. down1 = LeakyReLU(alpha=0.1)(down1)
  72. down1_pool = MaxPooling2D((2, 2), strides=(2, 2))(down1)
  73. # 64
  74. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down1_pool)
  75. down2 = BatchNormalization()(down2)
  76. down2 = LeakyReLU(alpha=0.1)(down2)
  77. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down2)
  78. down2 = BatchNormalization()(down2)
  79. down2 = LeakyReLU(alpha=0.1)(down2)
  80. down2_pool = MaxPooling2D((2, 2), strides=(2, 2))(down2)
  81. # 32
  82. down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down2_pool)
  83. down3 = BatchNormalization()(down3)
  84. down3 = LeakyReLU(alpha=0.1)(down3)
  85. down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down3)
  86. down3 = BatchNormalization()(down3)
  87. down3 = LeakyReLU(alpha=0.1)(down3)
  88. down3_pool = MaxPooling2D((2, 2), strides=(2, 2))(down3)
  89. # 16
  90. down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down3_pool)
  91. down4 = BatchNormalization()(down4)
  92. down4 = LeakyReLU(alpha=0.1)(down4)
  93. down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down4)
  94. down4 = BatchNormalization()(down4)
  95. down4 = LeakyReLU(alpha=0.1)(down4)
  96. down4_pool = MaxPooling2D((2, 2), strides=(2, 2))(down4)
  97. # 8
  98. center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(down4_pool)
  99. center = BatchNormalization()(center)
  100. center = LeakyReLU(alpha=0.1)(center)
  101. center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(center)
  102. center = BatchNormalization()(center)
  103. center = LeakyReLU(alpha=0.1)(center)
  104. # center
  105. up4 = UpSampling2D((2, 2))(center)
  106. up4 = concatenate([down4, up4], axis=3)
  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. up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
  111. up4 = BatchNormalization()(up4)
  112. up4 = LeakyReLU(alpha=0.1)(up4)
  113. up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
  114. up4 = BatchNormalization()(up4)
  115. up4 = LeakyReLU(alpha=0.1)(up4)
  116. # 16
  117. up3 = UpSampling2D((2, 2))(up4)
  118. up3 = concatenate([down3, up3], axis=3)
  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. up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
  123. up3 = BatchNormalization()(up3)
  124. up3 = LeakyReLU(alpha=0.1)(up3)
  125. up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
  126. up3 = BatchNormalization()(up3)
  127. up3 = LeakyReLU(alpha=0.1)(up3)
  128. # 32
  129. up2 = UpSampling2D((2, 2))(up3)
  130. up2 = concatenate([down2, up2], axis=3)
  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. up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
  135. up2 = BatchNormalization()(up2)
  136. up2 = LeakyReLU(alpha=0.1)(up2)
  137. up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
  138. up2 = BatchNormalization()(up2)
  139. up2 = LeakyReLU(alpha=0.1)(up2)
  140. # 64
  141. up1 = UpSampling2D((2, 2))(up2)
  142. up1 = concatenate([down1, up1], axis=3)
  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. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  147. up1 = BatchNormalization()(up1)
  148. up1 = LeakyReLU(alpha=0.1)(up1)
  149. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  150. up1 = BatchNormalization()(up1)
  151. up1 = LeakyReLU(alpha=0.1)(up1)
  152. # 128
  153. up0 = UpSampling2D((2, 2))(up1)
  154. up0 = concatenate([down0, up0], axis=3)
  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. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  159. up0 = BatchNormalization()(up0)
  160. up0 = LeakyReLU(alpha=0.1)(up0)
  161. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  162. up0 = BatchNormalization()(up0)
  163. up0 = LeakyReLU(alpha=0.1)(up0)
  164. # 256
  165. up0a = UpSampling2D((2, 2))(up0)
  166. up0a = concatenate([down0a, up0a], axis=3)
  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. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  171. up0a = BatchNormalization()(up0a)
  172. up0a = LeakyReLU(alpha=0.1)(up0a)
  173. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  174. up0a = BatchNormalization()(up0a)
  175. up0a = LeakyReLU(alpha=0.1)(up0a)
  176. # 512
  177. classify = Conv2D(num_classes, (1, 1), activation='sigmoid')(up0a)
  178. model = Model(inputs=inputs, outputs=classify)
  179. return model
  180. def table_net(input_shape=(1152, 896, 3), num_classes=1):
  181. inputs = Input(shape=input_shape)
  182. # 512
  183. use_bias = False
  184. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(inputs)
  185. down0a = BatchNormalization()(down0a)
  186. down0a = LeakyReLU(alpha=0.1)(down0a)
  187. down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(down0a)
  188. down0a = BatchNormalization()(down0a)
  189. down0a = LeakyReLU(alpha=0.1)(down0a)
  190. down0a_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0a)
  191. # 256
  192. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0a_pool)
  193. down0 = BatchNormalization()(down0)
  194. down0 = LeakyReLU(alpha=0.1)(down0)
  195. down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0)
  196. down0 = BatchNormalization()(down0)
  197. down0 = LeakyReLU(alpha=0.1)(down0)
  198. down0_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0)
  199. # 128
  200. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down0_pool)
  201. down1 = BatchNormalization()(down1)
  202. down1 = LeakyReLU(alpha=0.1)(down1)
  203. down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down1)
  204. down1 = BatchNormalization()(down1)
  205. down1 = LeakyReLU(alpha=0.1)(down1)
  206. down1_pool = MaxPooling2D((2, 2), strides=(2, 2))(down1)
  207. # 64
  208. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down1_pool)
  209. down2 = BatchNormalization()(down2)
  210. down2 = LeakyReLU(alpha=0.1)(down2)
  211. down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down2)
  212. down2 = BatchNormalization()(down2)
  213. down2 = LeakyReLU(alpha=0.1)(down2)
  214. down2_pool = MaxPooling2D((2, 2), strides=(2, 2))(down2)
  215. # 32
  216. up1 = UpSampling2D((2, 2))(down2)
  217. up1 = concatenate([down1, up1], axis=3)
  218. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  219. up1 = BatchNormalization()(up1)
  220. up1 = LeakyReLU(alpha=0.1)(up1)
  221. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  222. up1 = BatchNormalization()(up1)
  223. up1 = LeakyReLU(alpha=0.1)(up1)
  224. up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
  225. up1 = BatchNormalization()(up1)
  226. up1 = LeakyReLU(alpha=0.1)(up1)
  227. # 128
  228. up0 = UpSampling2D((2, 2))(up1)
  229. up0 = concatenate([down0, up0], axis=3)
  230. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  231. up0 = BatchNormalization()(up0)
  232. up0 = LeakyReLU(alpha=0.1)(up0)
  233. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  234. up0 = BatchNormalization()(up0)
  235. up0 = LeakyReLU(alpha=0.1)(up0)
  236. up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
  237. up0 = BatchNormalization()(up0)
  238. up0 = LeakyReLU(alpha=0.1)(up0)
  239. # 256
  240. up0a = UpSampling2D((2, 2))(up0)
  241. up0a = concatenate([down0a, up0a], axis=3)
  242. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  243. up0a = BatchNormalization()(up0a)
  244. up0a = LeakyReLU(alpha=0.1)(up0a)
  245. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  246. up0a = BatchNormalization()(up0a)
  247. up0a = LeakyReLU(alpha=0.1)(up0a)
  248. up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
  249. up0a = BatchNormalization()(up0a)
  250. up0a = LeakyReLU(alpha=0.1)(up0a)
  251. # 512
  252. classify = Conv2D(num_classes, (1, 1), activation='sigmoid')(up0a)
  253. model = Model(inputs=inputs, outputs=classify)
  254. return model
  255. model = table_net((None, None, 3), 2)
  256. def draw_pixel(pred, prob=0.2, is_test=1):
  257. if not is_test:
  258. return
  259. else:
  260. import matplotlib.pyplot as plt
  261. _array = []
  262. for _h in range(len(pred)):
  263. _line = []
  264. for _w in range(len(pred[_h])):
  265. _prob = pred[_h][_w]
  266. if _prob[0] > prob:
  267. _line.append((0, 0, 255))
  268. elif _prob[1] > prob:
  269. _line.append((255, 0, 0))
  270. else:
  271. _line.append((255, 255, 255))
  272. _array.append(_line)
  273. plt.axis('off')
  274. plt.imshow(np.array(_array))
  275. plt.show()
  276. return
  277. def expansionAndShrinkage(pred, width=3):
  278. pred_array = np.array(pred)
  279. print("pred_array=====", pred_array.shape)
  280. _array = pred_array[..., 0]
  281. _l = [_array]
  282. for _i in range(width):
  283. tmp_array = np.pad(_array[:-(_i + 1), ...], ((_i + 1, 0), (0, 0)))
  284. _l.append(tmp_array)
  285. for _i in range(width):
  286. tmp_array = np.pad(_array[_i + 1:, ...], ((0, _i + 1), (0, 0)))
  287. _l.append(tmp_array)
  288. for _i in range(width):
  289. tmp_array = np.pad(_array[..., :-(_i + 1)], ((0, 0), (_i + 1, 0)))
  290. _l.append(tmp_array)
  291. for _i in range(width):
  292. tmp_array = np.pad(_array[..., _i + 1:], ((0, 0), (0, _i + 1)))
  293. _l.append(tmp_array)
  294. for _a in _l:
  295. print(_a.shape)
  296. h_array = np.stack(_l, axis=0)
  297. h_array = np.max(h_array, axis=0, keepdims=False)
  298. _array = pred_array[..., 1]
  299. _l = [_array]
  300. for _i in range(width):
  301. tmp_array = np.pad(_array[:-(_i + 1), ...], ((_i + 1, 0), (0, 0)))
  302. _l.append(tmp_array)
  303. for _i in range(width):
  304. tmp_array = np.pad(_array[_i + 1:, ...], ((0, _i + 1), (0, 0)))
  305. _l.append(tmp_array)
  306. for _i in range(width):
  307. tmp_array = np.pad(_array[..., :-(_i + 1)], ((0, 0), (_i + 1, 0)))
  308. _l.append(tmp_array)
  309. for _i in range(width):
  310. tmp_array = np.pad(_array[..., _i + 1:], ((0, 0), (0, _i + 1)))
  311. _l.append(tmp_array)
  312. v_array = np.stack(_l, axis=0)
  313. print("v_array=====", v_array.shape)
  314. v_array = np.max(v_array, axis=0, keepdims=False)
  315. print("h_array=====", h_array.shape)
  316. print("v_array=====", v_array.shape)
  317. last_array = np.stack([h_array, v_array], axis=-1)
  318. print("pred_array=====", last_array.shape)
  319. return last_array
  320. def getIOU(bbox0, bbox1):
  321. width = abs(max(bbox0[2], bbox1[2]) - min(bbox0[0], bbox1[0])) - (
  322. abs(bbox0[2] - bbox0[0]) + abs(bbox1[2] - bbox1[0]))
  323. height = abs(max(bbox0[3], bbox1[3]) - min(bbox0[1], bbox1[1])) - (
  324. abs(bbox0[3] - bbox0[1]) + abs(bbox1[3] - bbox1[1]))
  325. if width <= 0 and height <= 0:
  326. iou = abs(width * height / min(abs((bbox0[2] - bbox0[0]) * (bbox0[3] - bbox0[1])),
  327. abs((bbox1[2] - bbox1[0]) * (bbox1[3] - bbox1[1]))))
  328. # print("getIOU", iou)
  329. return iou + 0.1
  330. return 0
  331. def lines_cluster(list_lines, line_width):
  332. after_len = 0
  333. prelength = len(list_lines)
  334. append_width = line_width // 2
  335. while 1:
  336. c_lines = []
  337. first_len = after_len
  338. for _line in list_lines:
  339. bbox = _line["bbox"]
  340. _find = False
  341. for c_l_i in range(len(c_lines)):
  342. c_l = c_lines[len(c_lines) - c_l_i - 1]
  343. bbox1 = c_l["bbox"]
  344. bboxa = [max(0, bbox[0] - append_width), max(0, bbox[1] - append_width), bbox[2] + append_width,
  345. bbox[3] + append_width]
  346. bboxb = [max(0, bbox1[0] - append_width), max(0, bbox1[1] - append_width), bbox1[2] + append_width,
  347. bbox1[3] + append_width]
  348. _iou = getIOU(bboxa, bboxb)
  349. if _iou > 0:
  350. new_bbox = [min(bbox[0], bbox[2], bbox1[0], bbox1[2]), min(bbox[1], bbox[3], bbox1[1], bbox1[3]),
  351. max(bbox[0], bbox[2], bbox1[0], bbox1[2]), max(bbox[1], bbox[3], bbox1[1], bbox1[3])]
  352. _find = True
  353. c_l["bbox"] = new_bbox
  354. break
  355. if not _find:
  356. c_lines.append(_line)
  357. after_len = len(c_lines)
  358. if first_len == after_len:
  359. break
  360. list_lines = c_lines
  361. log("cluster lines from %d to %d" % (prelength, len(list_lines)))
  362. return c_lines
  363. def points2lines(pred, sourceP_LB=True, prob=0.2, line_width=8, padding=3, min_len=10,
  364. cell_width=13):
  365. _time = time.time()
  366. log("starting points2lines")
  367. height = len(pred)
  368. width = len(pred[0])
  369. _sum = list(np.sum(np.array((pred[..., 0] > prob)).astype(int), axis=1))
  370. h_index = -1
  371. h_lines = []
  372. v_lines = []
  373. _step = line_width
  374. while 1:
  375. h_index += 1
  376. if h_index >= height:
  377. break
  378. w_index = -1
  379. if sourceP_LB:
  380. h_i = height - 1 - h_index
  381. else:
  382. h_i = h_index
  383. _start = None
  384. if _sum[h_index] < min_len:
  385. continue
  386. last_back = 0
  387. while 1:
  388. if w_index >= width:
  389. if _start is not None:
  390. _end = w_index - 1
  391. _bbox = [_start, h_i, _end, h_i]
  392. _dict = {"bbox": _bbox}
  393. h_lines.append(_dict)
  394. _start = None
  395. break
  396. _h, _v = pred[h_i][w_index]
  397. if _h > prob:
  398. if _start is None:
  399. _start = w_index
  400. w_index += _step
  401. else:
  402. if _start is not None:
  403. _end = w_index - 1
  404. _bbox = [_start, h_i, _end, h_i]
  405. _dict = {"bbox": _bbox}
  406. h_lines.append(_dict)
  407. _start = None
  408. w_index -= _step // 2
  409. if w_index <= last_back:
  410. w_index = last_back + _step // 2
  411. last_back = w_index
  412. log("starting points2lines 1")
  413. w_index = -1
  414. _sum = list(np.sum(np.array((pred[..., 1] > prob)).astype(int), axis=0))
  415. _step = line_width
  416. while 1:
  417. w_index += 1
  418. if w_index >= width:
  419. break
  420. if _sum[w_index] < min_len:
  421. continue
  422. h_index = -1
  423. _start = None
  424. last_back = 0
  425. list_test = []
  426. list_lineprob = []
  427. while 1:
  428. if h_index >= height:
  429. if _start is not None:
  430. _end = last_h
  431. _bbox = [w_index, _start, w_index, _end]
  432. _dict = {"bbox": _bbox}
  433. v_lines.append(_dict)
  434. _start = None
  435. list_test.append(_dict)
  436. break
  437. if sourceP_LB:
  438. h_i = height - 1 - h_index
  439. else:
  440. h_i = h_index
  441. _h, _v = pred[h_index][w_index]
  442. list_lineprob.append((h_index, _v))
  443. if _v > prob:
  444. if _start is None:
  445. _start = h_i
  446. h_index += _step
  447. else:
  448. if _start is not None:
  449. _end = last_h
  450. _bbox = [w_index, _start, w_index, _end]
  451. _dict = {"bbox": _bbox}
  452. v_lines.append(_dict)
  453. _start = None
  454. list_test.append(_dict)
  455. h_index -= _step // 2
  456. if h_index <= last_back:
  457. h_index = last_back + _step // 2
  458. last_back = h_index
  459. last_h = h_i
  460. log("starting points2lines 2")
  461. for _line in h_lines:
  462. _bbox = _line["bbox"]
  463. _bbox = [max(_bbox[0] - 2, 0), (_bbox[1] + _bbox[3]) / 2, _bbox[2] + 2, (_bbox[1] + _bbox[3]) / 2]
  464. _line["bbox"] = _bbox
  465. for _line in v_lines:
  466. _bbox = _line["bbox"]
  467. _bbox = [(_bbox[0] + _bbox[2]) / 2, max(_bbox[1] - 2, 0), (_bbox[0] + _bbox[2]) / 2, _bbox[3] + 2]
  468. _line["bbox"] = _bbox
  469. h_lines = lines_cluster(h_lines, line_width=line_width)
  470. v_lines = lines_cluster(v_lines, line_width=line_width)
  471. list_line = []
  472. for _line in h_lines:
  473. _bbox = _line["bbox"]
  474. _bbox = [max(_bbox[0] - 1, 0), (_bbox[1] + _bbox[3]) / 2, _bbox[2] + 1, (_bbox[1] + _bbox[3]) / 2]
  475. list_line.append(_bbox)
  476. for _line in v_lines:
  477. _bbox = _line["bbox"]
  478. _bbox = [(_bbox[0] + _bbox[2]) / 2, max(_bbox[1] - 1, 0), (_bbox[0] + _bbox[2]) / 2, _bbox[3] + 1]
  479. list_line.append(_bbox)
  480. log("points2lines cost %.2fs" % (time.time() - _time))
  481. # import matplotlib.pyplot as plt
  482. # plt.figure()
  483. # for _line in list_line:
  484. # x0,y0,x1,y1 = _line
  485. # plt.plot([x0,x1],[y0,y1])
  486. # for _line in list_line:
  487. # x0,y0,x1,y1 = _line.bbox
  488. # plt.plot([x0,x1],[y0,y1])
  489. # for point in list_crosspoints:
  490. # plt.scatter(point.get("point")[0],point.get("point")[1])
  491. # plt.show()
  492. return list_line
  493. def points2lines_bak(pred, sourceP_LB=True, prob=0.2, line_width=7, padding=3, min_len=10,
  494. cell_width=13):
  495. def inBbox(bbox, point, line_width):
  496. x, y = point
  497. if x >= bbox[0] - line_width and x <= bbox[2] + line_width and y >= bbox[1] - line_width and y <= bbox[
  498. 3] + line_width:
  499. return True, [min(x, bbox[0]), min(y, bbox[1]), max(x, bbox[2]), max(y, bbox[3])]
  500. return False, None
  501. _time = time.time()
  502. height = len(pred)
  503. width = len(pred[0])
  504. clust_horizontal = []
  505. clust_vertical = []
  506. h_index = -1
  507. _step = line_width
  508. _sum = list(np.sum(np.array((pred[..., 1] > prob)).astype(int), axis=0))
  509. _last = False
  510. _current = False
  511. while 1:
  512. h_index += 2
  513. if h_index >= height:
  514. break
  515. w_index = -1
  516. if sourceP_LB:
  517. h_i = height - 1 - h_index
  518. else:
  519. h_i = h_index
  520. while 1:
  521. w_index += 2
  522. if w_index >= width:
  523. break
  524. if _sum[w_index] < min_len:
  525. continue
  526. _h, _v = pred[h_index][w_index]
  527. if _v > prob:
  528. _find = False
  529. _point = (w_index, h_i)
  530. for l_h_i in range(len(clust_vertical)):
  531. l_h = clust_vertical[len(clust_vertical) - l_h_i - 1]
  532. bbox = l_h.get("bbox")
  533. b_in, _bbox = inBbox(bbox, _point, line_width)
  534. if b_in:
  535. _find = True
  536. l_h.get("points").append(_point)
  537. l_h["bbox"] = _bbox
  538. break
  539. if not _find:
  540. clust_vertical.append({"points": [_point], "bbox": [w_index, h_i, w_index, h_i]})
  541. w_index = -1
  542. _sum = list(np.sum(np.array((pred[..., 0] > prob)).astype(int), axis=1))
  543. while 1:
  544. w_index += 2
  545. if w_index >= width:
  546. break
  547. h_index = -1
  548. while 1:
  549. h_index += 2
  550. if h_index >= height:
  551. break
  552. if _sum[h_index] < min_len:
  553. continue
  554. if sourceP_LB:
  555. h_i = height - 1 - h_index
  556. else:
  557. h_i = h_index
  558. _h, _v = pred[h_index][w_index]
  559. if _h > prob:
  560. _find = False
  561. _point = (w_index, h_i)
  562. for l_h_i in range(len(clust_horizontal)):
  563. l_h = clust_horizontal[len(clust_horizontal) - l_h_i - 1]
  564. bbox = l_h.get("bbox")
  565. b_in, _bbox = inBbox(bbox, _point, line_width)
  566. if b_in:
  567. _find = True
  568. l_h.get("points").append(_point)
  569. l_h["bbox"] = _bbox
  570. break
  571. if not _find:
  572. clust_horizontal.append({"points": [_point], "bbox": [w_index, h_i, w_index, h_i]})
  573. tmp_vertical = []
  574. for _dict in clust_vertical:
  575. _bbox = _dict.get("bbox")
  576. if _bbox[2] - _bbox[0] >= min_len or _bbox[3] - _bbox[1] >= min_len:
  577. tmp_vertical.append(
  578. [(_bbox[0] + _bbox[2]) / 2, _bbox[1] - padding, (_bbox[0] + _bbox[2]) / 2, _bbox[3] + padding])
  579. tmp_horizontal = []
  580. for _dict in clust_horizontal:
  581. _bbox = _dict.get("bbox")
  582. if _bbox[2] - _bbox[0] >= min_len or _bbox[3] - _bbox[1] >= min_len:
  583. tmp_horizontal.append(
  584. [_bbox[0] - padding, (_bbox[1] + _bbox[3]) / 2, _bbox[2] + padding, (_bbox[1] + _bbox[3]) / 2])
  585. # merge lines
  586. tmp_vertical.sort(key=lambda x: x[3], reverse=True)
  587. tmp_horizontal.sort(key=lambda x: x[0])
  588. pop_index = []
  589. final_vertical = []
  590. for _line in tmp_vertical:
  591. _find = False
  592. x0, y0, x1, y1 = _line
  593. for _line2 in final_vertical:
  594. x2, y2, x3, y3 = _line2
  595. if abs(x0 - x2) < line_width and abs(y0 - y3) < cell_width or abs(y1 - y2) < cell_width:
  596. _find = True
  597. final_vertical.append([x0, min(y0, y2), x1, max(y1, y3)])
  598. break
  599. if not _find:
  600. final_vertical.append(_line)
  601. final_horizontal = []
  602. for _line in tmp_horizontal:
  603. _find = False
  604. x0, y0, x1, y1 = _line
  605. for _line2 in final_horizontal:
  606. x2, y2, x3, y3 = _line2
  607. if abs(y0 - y2) < line_width and abs(x0 - x3) < cell_width or abs(x1 - x2) < cell_width:
  608. _find = True
  609. final_horizontal.append([min(x0, x2), y0, max(x1, x3), y1])
  610. break
  611. if not _find:
  612. final_horizontal.append(_line)
  613. list_line = []
  614. for _line in final_vertical:
  615. list_line.append(_line)
  616. for _line in final_horizontal:
  617. list_line.append(_line)
  618. log("points2lines cost %.2fs" % (time.time() - _time))
  619. # import matplotlib.pyplot as plt
  620. # plt.figure()
  621. # for _line in list_line:
  622. # x0,y0,x1,y1 = _line
  623. # plt.plot([x0,x1],[y0,y1])
  624. # for _line in list_line:
  625. # x0,y0,x1,y1 = _line.bbox
  626. # plt.plot([x0,x1],[y0,y1])
  627. # for point in list_crosspoints:
  628. # plt.scatter(point.get("point")[0],point.get("point")[1])
  629. # plt.show()
  630. return list_line
  631. def get_line_from_binary_image(image_np, point_value=1, axis=0):
  632. """
  633. 根据像素点的变化,将像素点为特定值的转化为line,即找出端点坐标。
  634. 需要二值化的图。
  635. 仅支持竖线横线。
  636. :param image_np: numpy格式 image
  637. :param point_value: 像素点的特定值
  638. :param axis: 是否是行,否则为列
  639. :return: line list
  640. """
  641. def get_axis_points(_list, axis=0):
  642. _list.sort(key=lambda x: (x[1 - axis], x[axis]))
  643. standard_axis = points[axis][1 - axis]
  644. axis_points = []
  645. sub_points = []
  646. for p in _list:
  647. if p[1 - axis] == standard_axis:
  648. sub_points.append(p)
  649. else:
  650. standard_axis = p[1 - axis]
  651. if sub_points:
  652. axis_points.append(sub_points)
  653. sub_points = []
  654. # 最后一行/列
  655. if sub_points:
  656. axis_points.append(sub_points)
  657. return axis_points
  658. def get_axis_lines(_list, axis=0):
  659. # 逐行/列判断,一行/列可能多条横线/竖线
  660. points_lines = []
  661. for axis_list in _list:
  662. sub_line = [axis_list[0]]
  663. for p in axis_list:
  664. # 设置基准点
  665. standard_p = sub_line[-1]
  666. # 判断连续
  667. if p[axis] - standard_p[axis] == 1:
  668. sub_line.append(p)
  669. else:
  670. points_lines.append(sub_line)
  671. sub_line = [p]
  672. # 最后一行/列
  673. if sub_line:
  674. points_lines.append(sub_line)
  675. # 许多点组成的line转为两点line
  676. lines = []
  677. for line in points_lines:
  678. line.sort(key=lambda x: (x[axis], x[1 - axis]))
  679. lines.append([line[0][0], line[0][1], line[-1][0], line[-1][1]])
  680. return lines
  681. # 取值大于point_value的点的坐标
  682. ys, xs = np.where(image_np >= point_value)
  683. points = [[xs[i], ys[i]] for i in range(len(xs))]
  684. # 提出所有相同x或相同y的点
  685. # 提取行/列
  686. axis_points = get_axis_points(points, axis)
  687. # 提取每行/列的横线/竖线
  688. axis_lines = get_axis_lines(axis_points, axis)
  689. # print("axis_lines", axis_lines)
  690. return axis_lines
  691. def table_preprocess(img_data, prob=0.2):
  692. try:
  693. log("into table_preprocess, prob is " + str(prob))
  694. start_time = time.time()
  695. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  696. img = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  697. # 将bgr转为rbg
  698. image_np = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  699. # 模型输入
  700. inputs = np.array([image_np])
  701. # # 压缩numpy
  702. # compressed_array = io.BytesIO()
  703. # np.savez_compressed(compressed_array, inputs)
  704. # compressed_array.seek(0)
  705. # inputs_compressed = compressed_array.read()
  706. log("otr preprocess time: " + str(round(float(time.time() - start_time), 4)) + "s")
  707. return image_np, inputs
  708. except Exception as e:
  709. log("table pre process failed!")
  710. traceback.print_exc()
  711. return [-1], [-1]
  712. def table_postprocess(img_new, pred, prob=0.2, is_test=0):
  713. try:
  714. # 横线预测结果
  715. # row_pred = pred[..., 0] > hprob
  716. # row_pred = row_pred.astype(np.uint8)
  717. # # 竖线预测结果
  718. # col_pred = pred[..., 1] > vprob
  719. # col_pred = col_pred.astype(np.uint8)
  720. # # 打印模型输出
  721. # cv2.imshow("predict", (col_pred+row_pred)*255)
  722. # cv2.waitKey(0)
  723. start_time = time.time()
  724. list_line = points2lines(pred, False, prob=prob)
  725. mat_plot(list_line, "points2lines", is_test)
  726. log("points2lines " + str(time.time() - start_time))
  727. # 清除短线
  728. # print(img_new.shape)
  729. start_time = time.time()
  730. list_line = delete_short_lines(list_line, img_new.shape)
  731. mat_plot(list_line, "delete_short_lines", is_test)
  732. log("delete_short_lines " + str(time.time() - start_time))
  733. # # 清除无交点线--无需清除,会影响后面的结果
  734. # start_time = time.time()
  735. # list_line = delete_no_cross_lines(list_line)
  736. # mat_plot(list_line, "delete_no_cross_lines", is_test)
  737. # log("delete_no_cross_lines " + str(time.time()-start_time))
  738. # 分成横竖线
  739. start_time = time.time()
  740. list_rows = []
  741. list_cols = []
  742. for line in list_line:
  743. if line[0] == line[2]:
  744. list_cols.append(line)
  745. elif line[1] == line[3]:
  746. list_rows.append(line)
  747. log("divide rows and cols " + str(time.time() - start_time))
  748. # 合并错开线
  749. start_time = time.time()
  750. list_rows = merge_line(list_rows, axis=0)
  751. list_cols = merge_line(list_cols, axis=1)
  752. mat_plot(list_rows + list_cols, "merge_line", is_test)
  753. log("merge_line " + str(time.time() - start_time))
  754. # 计算交点、分割线
  755. start_time = time.time()
  756. cross_points = get_points(list_rows, list_cols, (img_new.shape[0], img_new.shape[1]))
  757. if not cross_points:
  758. return []
  759. log("get_points " + str(time.time() - start_time))
  760. # 清掉外围的没用的线
  761. # list_rows, list_cols = delete_outline(list_rows, list_cols, cross_points)
  762. # mat_plot(list_rows+list_cols, "delete_outline", is_test)
  763. # 多个表格分割线
  764. start_time = time.time()
  765. list_rows, list_cols = fix_in_split_lines(list_rows, list_cols, img_new)
  766. split_lines, split_y = get_split_line(cross_points, list_cols, img_new)
  767. log("get_split_line " + str(time.time() - start_time))
  768. # 修复边框
  769. start_time = time.time()
  770. new_rows, new_cols, long_rows, long_cols = fix_outline(img_new, list_rows, list_cols, cross_points,
  771. split_y)
  772. # 如有补线
  773. if new_rows or new_cols:
  774. # 连接至补线的延长线
  775. if long_rows:
  776. list_rows = long_rows
  777. if long_cols:
  778. list_cols = long_cols
  779. # 新的补线
  780. if new_rows:
  781. list_rows += new_rows
  782. if new_cols:
  783. list_cols += new_cols
  784. list_rows, list_cols = fix_in_split_lines(list_rows, list_cols, img_new)
  785. # 修复边框后重新计算交点、分割线
  786. cross_points = get_points(list_rows, list_cols, (img_new.shape[0], img_new.shape[1]))
  787. cv_plot(cross_points, img_new.shape, 0, is_test)
  788. split_lines, split_y = get_split_line(cross_points, list_cols, img_new)
  789. print("fix new split_y", split_y)
  790. print("fix new split_lines", split_lines)
  791. # 修复内部缺线
  792. # cross_points = fix_inner(list_rows, list_cols, cross_points, split_y)
  793. # if not cross_points:
  794. # return []
  795. mat_plot(list_rows + list_cols, "fix_outline", is_test)
  796. split_lines_show = []
  797. for _l in split_lines:
  798. split_lines_show.append([_l[0][0], _l[0][1], _l[1][0], _l[1][1]])
  799. mat_plot(split_lines_show + list_cols,
  800. "split_lines", is_test)
  801. log("fix_outline " + str(time.time() - start_time))
  802. # 修复表格4个角
  803. start_time = time.time()
  804. list_rows, list_cols = fix_corner(list_rows, list_cols, split_y, threshold=0)
  805. mat_plot(list_rows + list_cols, "fix_corner", is_test)
  806. log("fix_corner " + str(time.time() - start_time))
  807. # 修复内部缺线
  808. start_time = time.time()
  809. list_rows, list_cols = fix_inner(list_rows, list_cols, cross_points, split_y)
  810. mat_plot(list_rows + list_cols, "fix_inner", is_test)
  811. log("fix_inner " + str(time.time() - start_time))
  812. # 合并错开线
  813. start_time = time.time()
  814. list_rows = merge_line(list_rows, axis=0)
  815. list_cols = merge_line(list_cols, axis=1)
  816. mat_plot(list_rows + list_cols, "merge_line", is_test)
  817. log("merge_line " + str(time.time() - start_time))
  818. list_line = list_rows + list_cols
  819. # 打印处理后线
  820. mat_plot(list_line, "all", is_test)
  821. log("otr postprocess table_line " + str(time.time() - start_time))
  822. return list_line
  823. except Exception as e:
  824. log("table post process failed!")
  825. traceback.print_exc()
  826. return [-1]
  827. def table_line(img, model, size=(512, 1024), prob=0.2, is_test=1):
  828. log("into table_line, prob is " + str(prob))
  829. sizew, sizeh = size
  830. img_new = cv2.resize(img, (sizew, sizeh), interpolation=cv2.INTER_AREA)
  831. start_time = time.time()
  832. pred = model.predict(np.array([img_new]))
  833. log("otr model predict time " + str(time.time() - start_time))
  834. pred = pred[0]
  835. draw_pixel(pred, prob, is_test)
  836. # 横线预测结果
  837. # row_pred = pred[..., 0] > hprob
  838. # row_pred = row_pred.astype(np.uint8)
  839. # # 竖线预测结果
  840. # col_pred = pred[..., 1] > vprob
  841. # col_pred = col_pred.astype(np.uint8)
  842. # # 打印模型输出
  843. # cv2.imshow("predict", (col_pred+row_pred)*255)
  844. # cv2.waitKey(0)
  845. start_time = time.time()
  846. list_line = points2lines(pred, False, prob=prob)
  847. log("points2lines " + str(time.time() - start_time))
  848. if not list_line:
  849. return []
  850. mat_plot(list_line, "points2lines", is_test)
  851. # 清除短线
  852. # print(img_new.shape)
  853. start_time = time.time()
  854. list_line = delete_short_lines(list_line, img_new.shape)
  855. mat_plot(list_line, "delete_short_lines", is_test)
  856. log("delete_short_lines " + str(time.time() - start_time))
  857. # # 清除无交点线--无需清除,会影响后面的结果
  858. # start_time = time.time()
  859. # list_line = delete_no_cross_lines(list_line)
  860. # mat_plot(list_line, "delete_no_cross_lines", is_test)
  861. # log("delete_no_cross_lines " + str(time.time()-start_time))
  862. # 分成横竖线
  863. start_time = time.time()
  864. list_rows = []
  865. list_cols = []
  866. for line in list_line:
  867. if line[0] == line[2]:
  868. list_cols.append(line)
  869. elif line[1] == line[3]:
  870. list_rows.append(line)
  871. log("divide rows and cols " + str(time.time() - start_time))
  872. # 两种线都需要存在,否则跳过
  873. if not list_cols or not list_rows:
  874. return []
  875. # 合并错开线
  876. start_time = time.time()
  877. list_rows = merge_line(list_rows, axis=0)
  878. list_cols = merge_line(list_cols, axis=1)
  879. mat_plot(list_rows + list_cols, "merge_line", is_test)
  880. log("merge_line " + str(time.time() - start_time))
  881. # 计算交点、分割线
  882. start_time = time.time()
  883. cross_points = get_points(list_rows, list_cols, (img_new.shape[0], img_new.shape[1]))
  884. if not cross_points:
  885. return []
  886. log("get_points " + str(time.time() - start_time))
  887. # 清掉外围的没用的线
  888. # list_rows, list_cols = delete_outline(list_rows, list_cols, cross_points)
  889. # mat_plot(list_rows+list_cols, "delete_outline", is_test)
  890. # 多个表格分割线
  891. start_time = time.time()
  892. list_rows, list_cols = fix_in_split_lines(list_rows, list_cols, img_new)
  893. split_lines, split_y = get_split_line(cross_points, list_cols, img_new)
  894. log("get_split_line " + str(time.time() - start_time))
  895. split_lines_show = []
  896. for _l in split_lines:
  897. split_lines_show.append([_l[0][0], _l[0][1], _l[1][0], _l[1][1]])
  898. mat_plot(split_lines_show, "split_lines", is_test)
  899. log("split_lines_show " + str(time.time() - start_time))
  900. # 修复边框
  901. start_time = time.time()
  902. new_rows, new_cols, long_rows, long_cols = fix_outline(img_new, list_rows, list_cols, cross_points,
  903. split_y)
  904. # 如有补线
  905. if new_rows or new_cols:
  906. # 连接至补线的延长线
  907. if long_rows:
  908. list_rows = long_rows
  909. if long_cols:
  910. list_cols = long_cols
  911. # 新的补线
  912. if new_rows:
  913. list_rows += new_rows
  914. if new_cols:
  915. list_cols += new_cols
  916. list_rows, list_cols = fix_in_split_lines(list_rows, list_cols, img_new)
  917. # 修复边框后重新计算交点、分割线
  918. cross_points = get_points(list_rows, list_cols, (img_new.shape[0], img_new.shape[1]))
  919. cv_plot(cross_points, img_new.shape, 0, is_test)
  920. split_lines, split_y = get_split_line(cross_points, list_cols, img_new)
  921. print("fix new split_y", split_y)
  922. print("fix new split_lines", split_lines)
  923. split_lines_show = []
  924. for _l in split_lines:
  925. split_lines_show.append([_l[0][0], _l[0][1], _l[1][0], _l[1][1]])
  926. mat_plot(split_lines_show, "split_lines", is_test)
  927. log("split_lines_show new" + str(time.time() - start_time))
  928. # 修复内部缺线
  929. # cross_points = fix_inner(list_rows, list_cols, cross_points, split_y)
  930. # if not cross_points:
  931. # return []
  932. mat_plot(list_rows + list_cols, "fix_outline", is_test)
  933. log("fix_outline " + str(time.time() - start_time))
  934. # 修复表格4个角
  935. # start_time = time.time()
  936. # list_rows, list_cols = fix_corner(list_rows, list_cols, split_y, threshold=5)
  937. # mat_plot(list_rows + list_cols, "fix_corner", is_test)
  938. # log("fix_corner " + str(time.time() - start_time))
  939. # 验证轮廓的4个交点
  940. cross_points = fix_4_points(cross_points)
  941. # 修复内部缺线
  942. start_time = time.time()
  943. list_rows, list_cols = fix_inner(list_rows, list_cols, cross_points, split_y)
  944. mat_plot(list_rows + list_cols, "fix_inner", is_test)
  945. log("fix_inner " + str(time.time() - start_time))
  946. # 合并错开线
  947. start_time = time.time()
  948. list_rows = merge_line(list_rows, axis=0)
  949. list_cols = merge_line(list_cols, axis=1)
  950. mat_plot(list_rows + list_cols, "merge_line", is_test)
  951. log("merge_line " + str(time.time() - start_time))
  952. list_line = list_rows + list_cols
  953. # 打印处理后线
  954. mat_plot(list_line, "all", is_test)
  955. log("otr postprocess table_line " + str(time.time() - start_time))
  956. return list_line
  957. def table_line2(img, model, size=(512, 1024), hprob=0.5, vprob=0.5, row=50, col=30, alph=15):
  958. sizew, sizeh = size
  959. # [..., ::-1] 最后一维内部反向输出
  960. # inputBlob, fx, fy = letterbox_image(img[..., ::-1], (sizew, sizeh))
  961. # pred = model.predict(np.array([np.array(inputBlob)]))
  962. # pred = model.predict(np.array([np.array(inputBlob)/255.0]))
  963. img_new = cv2.resize(img, (sizew, sizeh), interpolation=cv2.INTER_AREA)
  964. # log("into table_line 1")
  965. pred = model.predict(np.array([img_new]))
  966. # log("into table_line 2")
  967. pred = pred[0]
  968. draw_pixel(pred)
  969. _time = time.time()
  970. points2lines(pred)
  971. log("points2lines takes %ds" % (time.time() - _time))
  972. vpred = pred[..., 1] > vprob # 横线
  973. hpred = pred[..., 0] > hprob # 竖线
  974. vpred = vpred.astype(int)
  975. hpred = hpred.astype(int)
  976. # print("vpred shape", vpred)
  977. # print("hpred shape", hpred)
  978. colboxes = get_table_line(vpred, axis=1, lineW=col)
  979. rowboxes = get_table_line(hpred, axis=0, lineW=row)
  980. # log("into table_line 3")
  981. # if len(rowboxes) > 0:
  982. # rowboxes = np.array(rowboxes)
  983. # rowboxes[:, [0, 2]] = rowboxes[:, [0, 2]]/fx
  984. # rowboxes[:, [1, 3]] = rowboxes[:, [1, 3]]/fy
  985. # rowboxes = rowboxes.tolist()
  986. # if len(colboxes) > 0:
  987. # colboxes = np.array(colboxes)
  988. # colboxes[:, [0, 2]] = colboxes[:, [0, 2]]/fx
  989. # colboxes[:, [1, 3]] = colboxes[:, [1, 3]]/fy
  990. # colboxes = colboxes.tolist()
  991. nrow = len(rowboxes)
  992. ncol = len(colboxes)
  993. for i in range(nrow):
  994. for j in range(ncol):
  995. rowboxes[i] = line_to_line(rowboxes[i], colboxes[j], 10)
  996. colboxes[j] = line_to_line(colboxes[j], rowboxes[i], 10)
  997. # log("into table_line 4")
  998. # 删掉贴着边框的line
  999. temp_list = []
  1000. threshold = 5
  1001. for line in rowboxes:
  1002. if line[1] - 0 <= threshold or size[1] - line[1] <= threshold:
  1003. continue
  1004. # 内部排序
  1005. if line[0] > line[2]:
  1006. line = [line[2], line[3], line[0], line[1]]
  1007. temp_list.append(line)
  1008. rowboxes = temp_list
  1009. temp_list = []
  1010. for line in colboxes:
  1011. if line[0] - 0 <= threshold or size[0] - line[0] <= threshold:
  1012. continue
  1013. # 内部排序
  1014. if line[1] > line[3]:
  1015. line = [line[2], line[3], line[0], line[1]]
  1016. temp_list.append(line)
  1017. colboxes = temp_list
  1018. return rowboxes, colboxes, img_new
  1019. def fix_in_split_lines(_rows, _cols, _img):
  1020. # 补线贴着边缘无法得到split_y,导致无法分区
  1021. for _row in _rows:
  1022. if _row[1] >= _img.shape[0] - 5:
  1023. _row[1] = _img.shape[0] - 6
  1024. _row[3] = _img.shape[0] - 6
  1025. print("_row", _row)
  1026. if _row[1] <= 0 + 5:
  1027. _row[1] = 6
  1028. _row[3] = 6
  1029. for _col in _cols:
  1030. if _col[3] >= _img.shape[0] - 5:
  1031. _col[3] = _img.shape[0] - 6
  1032. if _col[1] <= 0 + 5:
  1033. _col[1] = 6
  1034. return _rows, _cols
  1035. def mat_plot(list_line, name="", is_test=1):
  1036. if not is_test:
  1037. return
  1038. from matplotlib import pyplot as plt
  1039. plt.figure()
  1040. plt.title(name)
  1041. for _line in list_line:
  1042. x0, y0, x1, y1 = _line
  1043. plt.plot([x0, x1], [y0, y1])
  1044. plt.show()
  1045. def cv_plot(_list, img_shape, line_or_point=1, is_test=1):
  1046. if is_test == 0:
  1047. return
  1048. img_print = np.zeros(img_shape, np.uint8)
  1049. img_print.fill(255)
  1050. if line_or_point:
  1051. for line in _list:
  1052. cv2.line(img_print, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  1053. (255, 0, 0))
  1054. cv2.imshow("cv_plot", img_print)
  1055. cv2.waitKey(0)
  1056. else:
  1057. for point in _list:
  1058. cv2.circle(img_print, (int(point[0]), int(point[1])), 1, (255, 0, 0), 2)
  1059. cv2.imshow("cv_plot", img_print)
  1060. cv2.waitKey(0)
  1061. def delete_no_cross_lines(list_lines):
  1062. def get_cross_point(l1, l2):
  1063. # https://www.zhihu.com/question/381406535/answer/1095948349
  1064. flag = 0
  1065. # 相交一定是一条横线一条竖线
  1066. if (l1[0] == l1[2] and l2[1] == l2[3]) or (l1[1] == l1[3] and l2[0] == l2[2]):
  1067. if l1[0] <= l2[0] <= l1[2] and l2[1] <= l1[1] <= l2[3]:
  1068. flag = 1
  1069. elif l2[0] <= l1[0] <= l2[2] and l1[1] <= l2[1] <= l1[3]:
  1070. flag = 1
  1071. return flag
  1072. new_list_lines = []
  1073. for i in range(len(list_lines)):
  1074. line1 = list_lines[i]
  1075. find_flag = 0
  1076. for j in range(i + 1, len(list_lines)):
  1077. line2 = list_lines[j]
  1078. if get_cross_point(line1, line2):
  1079. # print("delete_no_cross_lines", line1, line2)
  1080. find_flag = 1
  1081. if line2 not in new_list_lines:
  1082. new_list_lines.append(line2)
  1083. if find_flag and line1 not in new_list_lines:
  1084. new_list_lines.append(line1)
  1085. return new_list_lines
  1086. def delete_short_lines(list_lines, image_shape, scale=100):
  1087. x_min_len = max(5, int(image_shape[0] / scale))
  1088. y_min_len = max(5, int(image_shape[1] / scale))
  1089. new_list_lines = []
  1090. for line in list_lines:
  1091. if line[0] == line[2]:
  1092. if abs(line[3] - line[1]) >= y_min_len:
  1093. # print("y_min_len", abs(line[3] - line[1]), y_min_len)
  1094. new_list_lines.append(line)
  1095. else:
  1096. if abs(line[2] - line[0]) >= x_min_len:
  1097. # print("x_min_len", abs(line[2] - line[0]), x_min_len)
  1098. new_list_lines.append(line)
  1099. return new_list_lines
  1100. def get_outline(points, image_np):
  1101. # 取出x, y的最大值最小值
  1102. x_min = points[0][0]
  1103. x_max = points[-1][0]
  1104. points.sort(key=lambda x: (x[1], x[0]))
  1105. y_min = points[0][1]
  1106. y_max = points[-1][1]
  1107. # 创建空图
  1108. # outline_img = np.zeros(image_size, np.uint8)
  1109. outline_img = np.copy(image_np)
  1110. cv2.rectangle(outline_img, (x_min - 5, y_min - 5), (x_max + 5, y_max + 5), (0, 0, 0), 2)
  1111. # cv2.imshow("outline_img", outline_img)
  1112. # cv2.waitKey(0)
  1113. return outline_img
  1114. def get_split_line(points, col_lines, image_np, threshold=5):
  1115. # print("get_split_line", image_np.shape)
  1116. points.sort(key=lambda x: (x[1], x[0]))
  1117. # 遍历y坐标,并判断y坐标与上一个y坐标是否存在连接线
  1118. i = 0
  1119. split_line_y = []
  1120. for point in points:
  1121. # 从已分开的线下面开始判断
  1122. if split_line_y:
  1123. if point[1] <= split_line_y[-1] + threshold:
  1124. last_y = point[1]
  1125. continue
  1126. if last_y <= split_line_y[-1] + threshold:
  1127. last_y = point[1]
  1128. continue
  1129. if i == 0:
  1130. last_y = point[1]
  1131. i += 1
  1132. continue
  1133. current_line = (last_y, point[1])
  1134. split_flag = 1
  1135. for col in col_lines:
  1136. # 只要找到一条col包含就不是分割线
  1137. if current_line[0] >= col[1] - 3 and current_line[1] <= col[3] + 3:
  1138. split_flag = 0
  1139. # print("img", img.shape)
  1140. # print("col", col)
  1141. # print("current_line", current_line)
  1142. break
  1143. if split_flag:
  1144. split_line_y.append(current_line[0] + 5)
  1145. split_line_y.append(current_line[1] - 5)
  1146. last_y = point[1]
  1147. # 加上收尾分割线
  1148. points.sort(key=lambda x: (x[1], x[0]))
  1149. y_min = points[0][1]
  1150. y_max = points[-1][1]
  1151. # print("加上收尾分割线", y_min, y_max)
  1152. if y_min - threshold < 0:
  1153. split_line_y.append(0)
  1154. else:
  1155. split_line_y.append(y_min - threshold)
  1156. if y_max + threshold > image_np.shape[0]:
  1157. split_line_y.append(image_np.shape[0])
  1158. else:
  1159. split_line_y.append(y_max + threshold)
  1160. split_line_y = list(set(split_line_y))
  1161. # 剔除两条相隔太近分割线
  1162. temp_split_line_y = []
  1163. split_line_y.sort(key=lambda x: x)
  1164. last_y = -20
  1165. for y in split_line_y:
  1166. # print(y)
  1167. if y - last_y >= 20:
  1168. # print(y, last_y)
  1169. temp_split_line_y.append(y)
  1170. last_y = y
  1171. split_line_y = temp_split_line_y
  1172. # print("split_line_y", split_line_y)
  1173. # 生成分割线
  1174. split_line = []
  1175. last_y = 0
  1176. for y in split_line_y:
  1177. # if y - last_y <= 15:
  1178. # continue
  1179. split_line.append([(0, y), (image_np.shape[1], y)])
  1180. last_y = y
  1181. split_line.append([(0, 0), (image_np.shape[1], 0)])
  1182. split_line.append([(0, image_np.shape[0]), (image_np.shape[1], image_np.shape[0])])
  1183. split_line.sort(key=lambda x: x[0][1])
  1184. # print("split_line", split_line)
  1185. # 画图画线
  1186. # split_line_img = np.copy(image_np)
  1187. # for y in split_line_y:
  1188. # cv2.line(split_line_img, (0, y), (image_np.shape[1], y), (0, 0, 0), 1)
  1189. # cv2.imshow("split_line_img", split_line_img)
  1190. # cv2.waitKey(0)
  1191. return split_line, split_line_y
  1192. def get_points(row_lines, col_lines, image_size):
  1193. # 创建空图
  1194. row_img = np.zeros(image_size, np.uint8)
  1195. col_img = np.zeros(image_size, np.uint8)
  1196. # 画线
  1197. thresh = 3
  1198. for row in row_lines:
  1199. cv2.line(row_img, (int(row[0] - thresh), int(row[1])), (int(row[2] + thresh), int(row[3])), (255, 255, 255), 1)
  1200. for col in col_lines:
  1201. cv2.line(col_img, (int(col[0]), int(col[1] - thresh)), (int(col[2]), int(col[3] + thresh)), (255, 255, 255), 1)
  1202. # 求出交点
  1203. point_img = np.bitwise_and(row_img, col_img)
  1204. # cv2.imwrite("get_points.jpg", row_img+col_img)
  1205. # cv2.imshow("get_points", row_img+col_img)
  1206. # cv2.waitKey(0)
  1207. # 识别黑白图中的白色交叉点,将横纵坐标取出
  1208. ys, xs = np.where(point_img > 0)
  1209. points = []
  1210. for i in range(len(xs)):
  1211. points.append((xs[i], ys[i]))
  1212. points.sort(key=lambda x: (x[0], x[1]))
  1213. return points
  1214. def get_minAreaRect(image):
  1215. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  1216. gray = cv2.bitwise_not(gray)
  1217. thresh = cv2.threshold(gray, 0, 255,
  1218. cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  1219. coords = np.column_stack(np.where(thresh > 0))
  1220. return cv2.minAreaRect(coords)
  1221. def get_contours(image):
  1222. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  1223. ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
  1224. contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  1225. cv2.drawContours(image, contours, -1, (0, 0, 255), 3)
  1226. cv2.imshow("get contours", image)
  1227. cv2.waitKey(0)
  1228. def merge_line(lines, axis, threshold=5):
  1229. """
  1230. 解决模型预测一条直线错开成多条直线,合并成一条直线
  1231. :param lines: 线条列表
  1232. :param axis: 0:横线 1:竖线
  1233. :param threshold: 两条线间像素差阈值
  1234. :return: 合并后的线条列表
  1235. """
  1236. # 任意一条line获取该合并的line,横线往下找,竖线往右找
  1237. lines.sort(key=lambda x: (x[axis], x[1 - axis]))
  1238. merged_lines = []
  1239. used_lines = []
  1240. for line1 in lines:
  1241. if line1 in used_lines:
  1242. continue
  1243. merged_line = [line1]
  1244. used_lines.append(line1)
  1245. for line2 in lines:
  1246. if line2 in used_lines:
  1247. continue
  1248. if line1[1 - axis] - threshold <= line2[1 - axis] <= line1[1 - axis] + threshold:
  1249. # 计算基准长度
  1250. min_axis = 10000
  1251. max_axis = 0
  1252. for line3 in merged_line:
  1253. if line3[axis] < min_axis:
  1254. min_axis = line3[axis]
  1255. if line3[axis + 2] > max_axis:
  1256. max_axis = line3[axis + 2]
  1257. # 判断两条线有无交集
  1258. if min_axis <= line2[axis] <= max_axis \
  1259. or min_axis <= line2[axis + 2] <= max_axis:
  1260. merged_line.append(line2)
  1261. used_lines.append(line2)
  1262. if merged_line:
  1263. merged_lines.append(merged_line)
  1264. # 合并line
  1265. result_lines = []
  1266. for merged_line in merged_lines:
  1267. # 获取line宽的平均值
  1268. axis_average = 0
  1269. for line in merged_line:
  1270. axis_average += line[1 - axis]
  1271. axis_average = int(axis_average / len(merged_line))
  1272. # 获取最长line两端
  1273. merged_line.sort(key=lambda x: (x[axis]))
  1274. axis_start = merged_line[0][axis]
  1275. merged_line.sort(key=lambda x: (x[axis + 2]))
  1276. axis_end = merged_line[-1][axis + 2]
  1277. if axis:
  1278. result_lines.append([axis_average, axis_start, axis_average, axis_end])
  1279. else:
  1280. result_lines.append([axis_start, axis_average, axis_end, axis_average])
  1281. return result_lines
  1282. def fix_inner2(row_points, col_points, row_lines, col_lines, threshold=3):
  1283. for i in range(len(row_points)):
  1284. row = row_points[i]
  1285. row.sort(key=lambda x: (x[1], x[0]))
  1286. for j in range(len(row)):
  1287. # 当前点
  1288. point = row[j]
  1289. # 获取当前点在所在行的下个点
  1290. if j >= len(row) - 1:
  1291. next_row_point = []
  1292. else:
  1293. next_row_point = row[j + 1]
  1294. if next_row_point:
  1295. for k in range(len(row_lines)):
  1296. line = row_lines[k]
  1297. if line[1] - threshold <= point[1] <= line[1] + threshold:
  1298. if not line[0] <= point[0] <= next_row_point[0] <= line[2]:
  1299. if point[0] <= line[2] < next_row_point[0]:
  1300. if line[2] - point[0] >= 1 / 3 * (next_row_point[0] - point[0]):
  1301. row_lines[k][2] = next_row_point[0]
  1302. if point[0] < line[0] <= next_row_point[0]:
  1303. if next_row_point[0] - line[0] >= 1 / 3 * (next_row_point[0] - point[0]):
  1304. row_lines[k][0] = point[0]
  1305. # 获取当前点所在列的下个点
  1306. next_col_point = []
  1307. for col in col_points:
  1308. if point in col:
  1309. col.sort(key=lambda x: (x[0], x[1]))
  1310. if col.index(point) < len(col) - 1:
  1311. next_col_point = col[col.index(point) + 1]
  1312. break
  1313. # 获取当前点的对角线点,通过该列下个点所在行的下个点获得
  1314. next_row_next_col_point = []
  1315. if next_col_point:
  1316. for row2 in row_points:
  1317. if next_col_point in row2:
  1318. row2.sort(key=lambda x: (x[1], x[0]))
  1319. if row2.index(next_col_point) < len(row2) - 1:
  1320. next_row_next_col_point = row2[row2.index(next_col_point) + 1]
  1321. break
  1322. # 有该列下一点但没有该列下一点所在行的下个点
  1323. if not next_row_next_col_point:
  1324. # 如果有该行下个点
  1325. if next_row_point:
  1326. next_row_next_col_point = [next_row_point[0], next_col_point[1]]
  1327. if next_col_point:
  1328. for k in range(len(col_lines)):
  1329. line = col_lines[k]
  1330. if line[0] - threshold <= point[0] <= line[0] + threshold:
  1331. if not line[1] <= point[1] <= next_col_point[1] <= line[3]:
  1332. if point[1] <= line[3] < next_col_point[1]:
  1333. if line[3] - point[1] >= 1 / 3 * (next_col_point[1] - point[1]):
  1334. col_lines[k][3] = next_col_point[1]
  1335. if point[1] < line[1] <= next_col_point[1]:
  1336. if next_col_point[1] - line[1] >= 1 / 3 * (next_col_point[1] - point[1]):
  1337. col_lines[k][1] = point[1]
  1338. if next_row_next_col_point:
  1339. for k in range(len(col_lines)):
  1340. line = col_lines[k]
  1341. if line[0] - threshold <= next_row_next_col_point[0] <= line[0] + threshold:
  1342. if not line[1] <= point[1] <= next_row_next_col_point[1] <= line[3]:
  1343. if point[1] < line[1] <= next_row_next_col_point[1]:
  1344. if next_row_next_col_point[1] - line[1] >= 1 / 3 * (
  1345. next_row_next_col_point[1] - point[1]):
  1346. col_lines[k][1] = point[1]
  1347. return row_lines, col_lines
  1348. def fix_inner1(row_lines, col_lines, points, split_y):
  1349. def fix(fix_lines, assist_lines, split_points, axis):
  1350. new_points = []
  1351. for line1 in fix_lines:
  1352. min_assist_line = [[], []]
  1353. min_distance = [1000, 1000]
  1354. if_find = [0, 0]
  1355. # 获取fix_line中的所有col point,里面可能不包括两个顶点,col point是交点,顶点可能不是交点
  1356. fix_line_points = []
  1357. for point in split_points:
  1358. if abs(point[1 - axis] - line1[1 - axis]) <= 2:
  1359. if line1[axis] <= point[axis] <= line1[axis + 2]:
  1360. fix_line_points.append(point)
  1361. # 找出离两个顶点最近的assist_line, 并且assist_line与fix_line不相交
  1362. line1_point = [line1[:2], line1[2:]]
  1363. for i in range(2):
  1364. point = line1_point[i]
  1365. for line2 in assist_lines:
  1366. if not if_find[i] and abs(point[axis] - line2[axis]) <= 2:
  1367. if line1[1 - axis] <= point[1 - axis] <= line2[1 - axis + 2]:
  1368. # print("line1, match line2", line1, line2)
  1369. if_find[i] = 1
  1370. break
  1371. else:
  1372. if abs(point[axis] - line2[axis]) < min_distance[i] and line2[1 - axis] <= point[1 - axis] <= \
  1373. line2[1 - axis + 2]:
  1374. if line1[axis] <= line2[axis] <= line1[axis + 2]:
  1375. continue
  1376. min_distance[i] = abs(line1[axis] - line2[axis])
  1377. min_assist_line[i] = line2
  1378. # 找出离assist_line最近的交点
  1379. # 顶点到交点的距离(多出来的线)需大于assist_line到交点的距离(bbox的边)的1/3
  1380. min_distance = [1000, 1000]
  1381. min_col_point = [[], []]
  1382. for i in range(2):
  1383. # print("顶点", i, line1_point[i])
  1384. if min_assist_line[i]:
  1385. for point in fix_line_points:
  1386. if abs(point[axis] - min_assist_line[i][axis]) < min_distance[i]:
  1387. min_distance[i] = abs(point[axis] - min_assist_line[i][axis])
  1388. min_col_point[i] = point
  1389. if min_col_point[i]:
  1390. bbox_len = abs(min_col_point[i][axis] - min_assist_line[i][axis])
  1391. line_distance = abs(min_col_point[i][axis] - line1_point[i][axis])
  1392. if bbox_len / 3 <= line_distance <= bbox_len:
  1393. add_point = (line1_point[i][1 - axis], min_assist_line[i][axis])
  1394. print("============================table line==")
  1395. print("fix_inner add point", add_point)
  1396. print(min_col_point[i][axis], line1_point[i][axis], min_col_point[i][axis],
  1397. min_assist_line[i][axis])
  1398. print(abs(min_col_point[i][axis] - line1_point[i][axis]),
  1399. abs(min_col_point[i][axis] - min_assist_line[i][axis]) / 3)
  1400. print("line1, line2", line1, min_assist_line[i])
  1401. new_points.append(add_point)
  1402. return new_points
  1403. new_points = []
  1404. for i in range(1, len(split_y)):
  1405. last_y = split_y[i - 1]
  1406. y = split_y[i]
  1407. # 先对点线进行分区
  1408. split_row_lines = []
  1409. split_col_lines = []
  1410. split_points = []
  1411. for row in row_lines:
  1412. if last_y <= row[1] <= y:
  1413. split_row_lines.append(row)
  1414. for col in col_lines:
  1415. if last_y <= col[1] <= y:
  1416. split_col_lines.append(col)
  1417. for point in points:
  1418. if last_y <= point[1] <= y:
  1419. split_points.append(point)
  1420. new_points += fix(split_col_lines, split_row_lines, split_points, axis=1)
  1421. new_points += fix(split_row_lines, split_col_lines, split_points, axis=0)
  1422. # 找出所有col的顶点不在row上的、row的顶点不在col上的
  1423. # for col in split_col_lines:
  1424. # print("*"*30)
  1425. #
  1426. # # 获取该line中的所有point
  1427. # col_points = []
  1428. # for point in split_points:
  1429. # if abs(point[0] - col[0]) <= 2:
  1430. # if col[1] <= point[1] <= col[3]:
  1431. # col_points.append(point)
  1432. #
  1433. # # 比较顶点
  1434. # min_row_1 = []
  1435. # min_row_2 = []
  1436. # min_distance_1 = 1000
  1437. # min_distance_2 = 1000
  1438. # if_find_1 = 0
  1439. # if_find_2 = 0
  1440. # for row in split_row_lines:
  1441. # # 第一个顶点
  1442. # if not if_find_1 and abs(col[1] - row[1]) <= 2:
  1443. # if row[0] <= col[0] <= row[2]:
  1444. # print("col, match row", col, row)
  1445. # if_find_1 = 1
  1446. # break
  1447. # else:
  1448. # if abs(col[1] - row[1]) < min_distance_1 and row[0] <= col[0] <= row[2]:
  1449. # if col[1] <= row[1] <= col[3]:
  1450. # continue
  1451. # min_distance_1 = abs(col[1] - row[1])
  1452. # min_row_1 = row
  1453. #
  1454. # # 第二个顶点
  1455. # if not if_find_2 and abs(col[3] - row[1]) <= 2:
  1456. # if row[0] <= col[2] <= row[2]:
  1457. # if_find_2 = 1
  1458. # break
  1459. # else:
  1460. # if abs(col[3] - row[1]) < min_distance_2 and row[0] <= col[2] <= row[2]:
  1461. # min_distance_2 = abs(col[3] - row[1])
  1462. # min_row_2 = row
  1463. #
  1464. # if not if_find_1:
  1465. # print("col", col)
  1466. # print("min_row_1", min_row_1)
  1467. # if min_row_1:
  1468. # min_distance_1 = 1000
  1469. # min_col_point = []
  1470. # for point in col_points:
  1471. # if abs(point[1] - min_row_1[1]) < min_distance_1:
  1472. # min_distance_1 = abs(point[1] - min_row_1[1])
  1473. # min_col_point = point
  1474. #
  1475. # if abs(min_col_point[1] - col[1]) >= abs(min_col_point[1] - min_row_1[1])/3:
  1476. #
  1477. # add_point = (col[0], min_row_1[1])
  1478. # print("fix_inner add point", add_point)
  1479. # new_points.append(add_point)
  1480. # else:
  1481. # print("distance too long", min_col_point, min_row_1)
  1482. # print(abs(min_col_point[1] - col[1]), abs(min_col_point[1] - min_row_1[1])/3)
  1483. return points + new_points
  1484. def fix_inner(row_lines, col_lines, points, split_y):
  1485. def fix(fix_lines, assist_lines, split_points, axis):
  1486. new_points = []
  1487. for line1 in fix_lines:
  1488. min_assist_line = [[], []]
  1489. min_distance = [1000, 1000]
  1490. if_find = [0, 0]
  1491. # 获取fix_line中的所有col point,里面可能不包括两个顶点,col point是交点,顶点可能不是交点
  1492. fix_line_points = []
  1493. for point in split_points:
  1494. if abs(point[1 - axis] - line1[1 - axis]) <= 2:
  1495. if line1[axis] <= point[axis] <= line1[axis + 2]:
  1496. fix_line_points.append(point)
  1497. # 找出离两个顶点最近的assist_line, 并且assist_line与fix_line不相交
  1498. line1_point = [line1[:2], line1[2:]]
  1499. for i in range(2):
  1500. point = line1_point[i]
  1501. for line2 in assist_lines:
  1502. if not if_find[i] and abs(point[axis] - line2[axis]) <= 2:
  1503. if line1[1 - axis] <= point[1 - axis] <= line2[1 - axis + 2]:
  1504. # print("line1, match line2", line1, line2)
  1505. if_find[i] = 1
  1506. break
  1507. else:
  1508. if abs(point[axis] - line2[axis]) < min_distance[i] and line2[1 - axis] <= point[1 - axis] <= \
  1509. line2[1 - axis + 2]:
  1510. if line1[axis] <= line2[axis] <= line1[axis + 2]:
  1511. continue
  1512. min_distance[i] = abs(line1[axis] - line2[axis])
  1513. min_assist_line[i] = line2
  1514. # 找出离assist_line最近的交点
  1515. # 顶点到交点的距离(多出来的线)需大于assist_line到交点的距离(bbox的边)的1/3
  1516. min_distance = [1000, 1000]
  1517. min_col_point = [[], []]
  1518. for i in range(2):
  1519. # print("顶点", i, line1_point[i])
  1520. if min_assist_line[i]:
  1521. for point in fix_line_points:
  1522. if abs(point[axis] - min_assist_line[i][axis]) < min_distance[i]:
  1523. min_distance[i] = abs(point[axis] - min_assist_line[i][axis])
  1524. min_col_point[i] = point
  1525. if len(min_col_point[0]) == 0:
  1526. return []
  1527. # print("min_col_point", min_col_point)
  1528. # print("min_assist_line", min_assist_line)
  1529. # print("line1_point", line1_point)
  1530. if min_assist_line[0] and min_assist_line[0] == min_assist_line[1]:
  1531. if min_assist_line[0][axis] < line1_point[0][axis]:
  1532. bbox_len = abs(min_col_point[0][axis] - min_assist_line[0][axis])
  1533. line_distance = abs(min_col_point[0][axis] - line1_point[0][axis])
  1534. if bbox_len / 3 <= line_distance <= bbox_len:
  1535. if axis == 1:
  1536. add_point = (line1_point[0][1 - axis], min_assist_line[0][axis])
  1537. else:
  1538. add_point = (min_assist_line[0][axis], line1_point[0][1 - axis])
  1539. new_points.append([line1, add_point])
  1540. elif min_assist_line[1][axis] > line1_point[1][axis]:
  1541. bbox_len = abs(min_col_point[1][axis] - min_assist_line[1][axis])
  1542. line_distance = abs(min_col_point[1][axis] - line1_point[1][axis])
  1543. if bbox_len / 3 <= line_distance <= bbox_len:
  1544. if axis == 1:
  1545. add_point = (line1_point[1][1 - axis], min_assist_line[1][axis])
  1546. else:
  1547. add_point = (min_assist_line[1][axis], line1_point[1][1 - axis])
  1548. new_points.append([line1, add_point])
  1549. else:
  1550. for i in range(2):
  1551. if min_col_point[i]:
  1552. bbox_len = abs(min_col_point[i][axis] - min_assist_line[i][axis])
  1553. line_distance = abs(min_col_point[i][axis] - line1_point[i][axis])
  1554. # print("bbox_len, line_distance", bbox_len, line_distance)
  1555. if bbox_len / 3 <= line_distance <= bbox_len:
  1556. if axis == 1:
  1557. add_point = (line1_point[i][1 - axis], min_assist_line[i][axis])
  1558. else:
  1559. add_point = (min_assist_line[i][axis], line1_point[i][1 - axis])
  1560. # print("============================table line==")
  1561. # print("fix_inner add point", add_point)
  1562. # print(min_col_point[i][axis], line1_point[i][axis], min_col_point[i][axis], min_assist_line[i][axis])
  1563. # print(abs(min_col_point[i][axis] - line1_point[i][axis]), abs(min_col_point[i][axis] - min_assist_line[i][axis])/3)
  1564. # print("line1, line2", line1, min_assist_line[i])
  1565. # print("line1, add_point", [line1, add_point])
  1566. new_points.append([line1, add_point])
  1567. return new_points
  1568. row_lines_copy = copy.deepcopy(row_lines)
  1569. col_lines_copy = copy.deepcopy(col_lines)
  1570. try:
  1571. new_points = []
  1572. for i in range(1, len(split_y)):
  1573. last_y = split_y[i - 1]
  1574. y = split_y[i]
  1575. # 先对点线进行分区
  1576. split_row_lines = []
  1577. split_col_lines = []
  1578. split_points = []
  1579. for row in row_lines:
  1580. if last_y <= row[1] <= y:
  1581. split_row_lines.append(row)
  1582. for col in col_lines:
  1583. if last_y <= col[1] <= y:
  1584. split_col_lines.append(col)
  1585. for point in points:
  1586. if last_y <= point[1] <= y:
  1587. split_points.append(point)
  1588. new_point_list = fix(split_col_lines, split_row_lines, split_points, axis=1)
  1589. for line, new_point in new_point_list:
  1590. if line in col_lines:
  1591. index = col_lines.index(line)
  1592. point1 = line[:2]
  1593. point2 = line[2:]
  1594. if new_point[1] >= point2[1]:
  1595. col_lines[index] = [point1[0], point1[1], new_point[0], new_point[1]]
  1596. elif new_point[1] <= point1[1]:
  1597. col_lines[index] = [new_point[0], new_point[1], point2[0], point2[1]]
  1598. new_point_list = fix(split_row_lines, split_col_lines, split_points, axis=0)
  1599. for line, new_point in new_point_list:
  1600. if line in row_lines:
  1601. index = row_lines.index(line)
  1602. point1 = line[:2]
  1603. point2 = line[2:]
  1604. if new_point[0] >= point2[0]:
  1605. row_lines[index] = [point1[0], point1[1], new_point[0], new_point[1]]
  1606. elif new_point[0] <= point1[0]:
  1607. row_lines[index] = [new_point[0], new_point[1], point2[0], point2[1]]
  1608. return row_lines, col_lines
  1609. except:
  1610. traceback.print_exc()
  1611. return row_lines_copy, col_lines_copy
  1612. def fix_corner(row_lines, col_lines, split_y, threshold=0):
  1613. new_row_lines = []
  1614. new_col_lines = []
  1615. last_y = split_y[0]
  1616. for y in split_y:
  1617. if y == last_y:
  1618. continue
  1619. split_row_lines = []
  1620. split_col_lines = []
  1621. for row in row_lines:
  1622. if last_y - threshold <= row[1] <= y + threshold or last_y - threshold <= row[3] <= y + threshold:
  1623. split_row_lines.append(row)
  1624. for col in col_lines:
  1625. # fix corner 容易因split line 漏掉线
  1626. if last_y - threshold <= col[1] <= y + threshold or last_y - threshold <= col[3] <= y + threshold:
  1627. split_col_lines.append(col)
  1628. if not split_row_lines or not split_col_lines:
  1629. last_y = y
  1630. continue
  1631. split_row_lines.sort(key=lambda x: (x[1], x[0]))
  1632. split_col_lines.sort(key=lambda x: (x[0], x[1]))
  1633. up_line = split_row_lines[0]
  1634. bottom_line = split_row_lines[-1]
  1635. left_line = split_col_lines[0]
  1636. right_line = split_col_lines[-1]
  1637. # 左上角
  1638. if up_line[0:2] != left_line[0:2]:
  1639. # print("up_line, left_line", up_line, left_line)
  1640. add_corner = [left_line[0], up_line[1]]
  1641. split_row_lines[0][0] = add_corner[0]
  1642. split_col_lines[0][1] = add_corner[1]
  1643. # 右上角
  1644. if up_line[2:] != right_line[:2]:
  1645. # print("up_line, right_line", up_line, right_line)
  1646. add_corner = [right_line[0], up_line[1]]
  1647. split_row_lines[0][2] = add_corner[0]
  1648. split_col_lines[-1][1] = add_corner[1]
  1649. new_row_lines = new_row_lines + split_row_lines
  1650. new_col_lines = new_col_lines + split_col_lines
  1651. last_y = y
  1652. return new_row_lines, new_col_lines
  1653. def delete_outline(row_lines, col_lines, points):
  1654. row_lines.sort(key=lambda x: (x[1], x[0]))
  1655. col_lines.sort(key=lambda x: (x[0], x[1]))
  1656. line = [row_lines[0], row_lines[-1], col_lines[0], col_lines[-1]]
  1657. threshold = 2
  1658. point_cnt = [0, 0, 0, 0]
  1659. for point in points:
  1660. for i in range(4):
  1661. if i < 2:
  1662. if line[i][1] - threshold <= point[1] <= line[i][1] + threshold:
  1663. if line[i][0] <= point[0] <= line[i][2]:
  1664. point_cnt[i] += 1
  1665. else:
  1666. if line[i][0] - threshold <= point[0] <= line[i][0] + threshold:
  1667. if line[i][1] <= point[1] <= line[i][3]:
  1668. point_cnt[i] += 1
  1669. # if line[0][1]-threshold <= point[1] <= line[0][1]+threshold:
  1670. # if line[0][0] <= point[0] <= line[0][2]:
  1671. # point_cnt[0] += 1
  1672. # elif line[1][1]-threshold <= point[1] <= line[1][1]+threshold:
  1673. # if line[1][0] <= point[0] <= line[1][2]:
  1674. # point_cnt[1] += 1
  1675. # elif line[2][0]-threshold <= point[0] <= line[2][0]+threshold:
  1676. # if line[2][1] <= point[1] <= line[2][3]:
  1677. # point_cnt[2] += 1
  1678. # elif line[3][0]-threshold <= point[0] <= line[3][0]+threshold:
  1679. # if line[3][1] <= point[1] <= line[3][3]:
  1680. # point_cnt[3] += 1
  1681. # 轮廓line至少包含3个交点
  1682. for i in range(4):
  1683. if point_cnt[i] < 3:
  1684. if i < 2:
  1685. if line[i] in row_lines:
  1686. row_lines.remove(line[i])
  1687. else:
  1688. if line[i] in col_lines:
  1689. col_lines.remove(line[i])
  1690. return row_lines, col_lines
  1691. def fix_outline2(image, row_lines, col_lines, points, split_y):
  1692. print("split_y", split_y)
  1693. # 分割线纵坐标
  1694. if len(split_y) < 2:
  1695. return [], [], [], []
  1696. # elif len(split_y) == 2:
  1697. # split_y = [2000., 2000., 2000., 2000.]
  1698. split_y.sort(key=lambda x: x)
  1699. new_split_y = []
  1700. for i in range(1, len(split_y), 2):
  1701. new_split_y.append(int((split_y[i] + split_y[i - 1]) / 2))
  1702. # # 查看是否正确输出区域分割线
  1703. # for line in split_y:
  1704. # cv2.line(image, (0, int(line)), (int(image.shape[1]), int(line)), (0, 0, 255), 2)
  1705. # cv2.imshow("split_y", image)
  1706. # cv2.waitKey(0)
  1707. # 预测线根据分割线纵坐标分为多个分割区域
  1708. # row_lines.sort(key=lambda x: (x[3], x[2], x[1], x[0]))
  1709. # col_lines.sort(key=lambda x: (x[3], x[2], x[1], x[0]))
  1710. # points.sort(key=lambda x: (x[1], x[0]))
  1711. # row_count = 0
  1712. # col_count = 0
  1713. # point_count = 0
  1714. split_row_list = []
  1715. split_col_list = []
  1716. split_point_list = []
  1717. # for i in range(1, len(split_y)):
  1718. # y = split_y[i]
  1719. # last_y = split_y[i-1]
  1720. # row_lines = row_lines[row_count:]
  1721. # col_lines = col_lines[col_count:]
  1722. # points = points[point_count:]
  1723. # row_count = 0
  1724. # col_count = 0
  1725. # point_count = 0
  1726. #
  1727. # if not row_lines:
  1728. # split_row_list.append([])
  1729. # for row in row_lines:
  1730. # if last_y <= row[3] <= y:
  1731. # row_count += 1
  1732. # else:
  1733. # split_row_list.append(row_lines[:row_count])
  1734. # break
  1735. # if row_count == len(row_lines):
  1736. # split_row_list.append(row_lines[:row_count])
  1737. # break
  1738. #
  1739. # if not col_lines:
  1740. # split_col_list.append([])
  1741. #
  1742. # for col in col_lines:
  1743. # # if last_y <= col[3] <= y:
  1744. # if col[1] <= last_y <= y <= col[3] or last_y <= col[3] <= y:
  1745. # # if last_y <= col[1] <= y or last_y <= col[3] <= y:
  1746. # col_count += 1
  1747. # else:
  1748. # split_col_list.append(col_lines[:col_count])
  1749. # break
  1750. # if col_count == len(col_lines):
  1751. # split_col_list.append(col_lines[:col_count])
  1752. # break
  1753. #
  1754. # if not points:
  1755. # split_point_list.append([])
  1756. # for point in points:
  1757. # if last_y <= point[1] <= y:
  1758. # point_count += 1
  1759. # else:
  1760. # split_point_list.append(points[:point_count])
  1761. # break
  1762. # if point_count == len(points):
  1763. # split_point_list.append(points[:point_count])
  1764. # break
  1765. #
  1766. # # print("len(split_row_list)", len(split_row_list))
  1767. # # print("len(split_col_list)", len(split_col_list))
  1768. # if row_count < len(row_lines) - 1 and col_count < len(col_lines) - 1:
  1769. # row_lines = row_lines[row_count:]
  1770. # split_row_list.append(row_lines)
  1771. # col_lines = col_lines[col_count:]
  1772. # split_col_list.append(col_lines)
  1773. #
  1774. # if point_count < len(points) - 1:
  1775. # points = points[point_count:len(points)]
  1776. # split_point_list.append(points)
  1777. for i in range(1, len(split_y)):
  1778. y = split_y[i]
  1779. last_y = split_y[i - 1]
  1780. split_row = []
  1781. for row in row_lines:
  1782. if last_y <= row[3] <= y:
  1783. split_row.append(row)
  1784. split_row_list.append(split_row)
  1785. split_col = []
  1786. for col in col_lines:
  1787. if last_y <= col[1] <= y or last_y <= col[3] <= y or col[1] < last_y < y < col[3]:
  1788. split_col.append(col)
  1789. split_col_list.append(split_col)
  1790. split_point = []
  1791. for point in points:
  1792. if last_y <= point[1] <= y:
  1793. split_point.append(point)
  1794. split_point_list.append(split_point)
  1795. # 预测线取上下左右4个边(会有超出表格部分) [(), ()]
  1796. area_row_line = []
  1797. area_col_line = []
  1798. for area in split_row_list:
  1799. if not area:
  1800. area_row_line.append([])
  1801. continue
  1802. area.sort(key=lambda x: (x[1], x[0]))
  1803. up_line = area[0]
  1804. bottom_line = area[-1]
  1805. area_row_line.append([up_line, bottom_line])
  1806. for area in split_col_list:
  1807. if not area:
  1808. area_col_line.append([])
  1809. continue
  1810. area.sort(key=lambda x: x[0])
  1811. left_line = area[0]
  1812. right_line = area[-1]
  1813. area_col_line.append([left_line, right_line])
  1814. # 线交点根据分割线纵坐标分为多个分割区域
  1815. # points.sort(key=lambda x: (x[1], x[0]))
  1816. # point_count = 0
  1817. # split_point_list = []
  1818. # for y in new_split_y:
  1819. # points = points[point_count:len(points)]
  1820. # point_count = 0
  1821. # for point in points:
  1822. # if point[1] <= y:
  1823. # point_count += 1
  1824. # else:
  1825. # split_point_list.append(points[:point_count])
  1826. # break
  1827. # if point_count == len(points):
  1828. # split_point_list.append(points[:point_count])
  1829. # break
  1830. # if point_count < len(points) - 1:
  1831. # points = points[point_count:len(points)]
  1832. # split_point_list.append(points)
  1833. # print("len(split_point_list)", len(split_point_list))
  1834. # 取每个分割区域的4条线(无超出表格部分)
  1835. area_row_line2 = []
  1836. area_col_line2 = []
  1837. for area in split_point_list:
  1838. if not area:
  1839. area_row_line2.append([])
  1840. area_col_line2.append([])
  1841. continue
  1842. area.sort(key=lambda x: (x[0], x[1]))
  1843. left_up = area[0]
  1844. right_bottom = area[-1]
  1845. up_line = [left_up[0], left_up[1], right_bottom[0], left_up[1]]
  1846. bottom_line = [left_up[0], right_bottom[1], right_bottom[0], right_bottom[1]]
  1847. left_line = [left_up[0], left_up[1], left_up[0], right_bottom[1]]
  1848. right_line = [right_bottom[0], left_up[1], right_bottom[0], right_bottom[1]]
  1849. area_row_line2.append([up_line, bottom_line])
  1850. area_col_line2.append([left_line, right_line])
  1851. # 判断超出部分的长度,超出一定长度就补线
  1852. new_row_lines = []
  1853. new_col_lines = []
  1854. longer_row_lines = []
  1855. longer_col_lines = []
  1856. all_longer_row_lines = []
  1857. all_longer_col_lines = []
  1858. # print("split_y", split_y)
  1859. # print("split_row_list", split_row_list, len(split_row_list))
  1860. # print("split_row_list", split_col_list, len(split_col_list))
  1861. # print("area_row_line", area_row_line, len(area_row_line))
  1862. # print("area_col_line", area_col_line, len(area_col_line))
  1863. for i in range(len(area_row_line)):
  1864. if not area_row_line[i] or not area_col_line[i]:
  1865. continue
  1866. up_line = area_row_line[i][0]
  1867. up_line2 = area_row_line2[i][0]
  1868. bottom_line = area_row_line[i][1]
  1869. bottom_line2 = area_row_line2[i][1]
  1870. left_line = area_col_line[i][0]
  1871. left_line2 = area_col_line2[i][0]
  1872. right_line = area_col_line[i][1]
  1873. right_line2 = area_col_line2[i][1]
  1874. # 计算单格高度宽度
  1875. if len(split_row_list[i]) > 1:
  1876. height_dict = {}
  1877. for j in range(len(split_row_list[i])):
  1878. if j + 1 > len(split_row_list[i]) - 1:
  1879. break
  1880. height = abs(int(split_row_list[i][j][3] - split_row_list[i][j + 1][3]))
  1881. if height in height_dict.keys():
  1882. height_dict[height] = height_dict[height] + 1
  1883. else:
  1884. height_dict[height] = 1
  1885. height_list = [[x, height_dict[x]] for x in height_dict.keys()]
  1886. height_list.sort(key=lambda x: (x[1], -x[0]), reverse=True)
  1887. # print("height_list", height_list)
  1888. box_height = height_list[0][0]
  1889. else:
  1890. box_height = 10
  1891. if len(split_col_list[i]) > 1:
  1892. box_width = abs(split_col_list[i][1][2] - split_col_list[i][0][2])
  1893. else:
  1894. box_width = 10
  1895. print("box_height", box_height, "box_width", box_width)
  1896. # cv2.line(image, (int(up_line[0]), int(up_line[1])),
  1897. # (int(up_line[2]), int(up_line[3])),
  1898. # (255, 255, 0), 2)
  1899. # cv2.line(image, (int(right_line[0]), int(right_line[1])),
  1900. # (int(right_line[2]), int(right_line[3])),
  1901. # (0, 255, 255), 2)
  1902. # cv2.imshow("right_line", image)
  1903. # cv2.waitKey(0)
  1904. # 补左右两条竖线超出来的线的row
  1905. if (up_line[1] - left_line[1] >= 10 and up_line[1] - right_line[1] >= 2) or \
  1906. (up_line[1] - left_line[1] >= 2 and up_line[1] - right_line[1] >= 10):
  1907. if up_line[1] - left_line[1] >= up_line[1] - right_line[1]:
  1908. new_row_lines.append([left_line[0], left_line[1], right_line[0], left_line[1]])
  1909. new_col_y = left_line[1]
  1910. # 补了row,要将其他短的col连到row上
  1911. for j in range(len(split_col_list[i])):
  1912. col = split_col_list[i][j]
  1913. # 且距离不能相差大于一格
  1914. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  1915. if abs(new_col_y - col[1]) <= box_height:
  1916. split_col_list[i][j][1] = min([new_col_y, col[1]])
  1917. longer_col_lines.append([col[0], min([new_col_y, col[1]]), col[2], col[3]])
  1918. else:
  1919. new_row_lines.append([left_line[0], right_line[1], right_line[0], right_line[1]])
  1920. new_col_y = right_line[1]
  1921. # 补了row,要将其他短的col连到row上
  1922. for j in range(len(split_col_list[i])):
  1923. # 需判断该线在这个区域中
  1924. # if up_line2[1]-3 <= col[1] <= col[3] <= bottom_line2[1]+3:
  1925. col = split_col_list[i][j]
  1926. # 且距离不能相差太大
  1927. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  1928. if abs(new_col_y - col[1]) <= box_height:
  1929. split_col_list[i][j][1] = min([new_col_y, col[1]])
  1930. if (left_line[3] - bottom_line[3] >= 10 and right_line[3] - bottom_line[3] >= 2) or \
  1931. (left_line[3] - bottom_line[3] >= 2 and right_line[3] - bottom_line[3] >= 10):
  1932. if left_line[3] - bottom_line[3] >= right_line[3] - bottom_line[3]:
  1933. new_row_lines.append([left_line[2], left_line[3], right_line[2], left_line[3]])
  1934. new_col_y = left_line[3]
  1935. # 补了row,要将其他短的col连到row上
  1936. for j in range(len(split_col_list[i])):
  1937. col = split_col_list[i][j]
  1938. # 且距离不能相差太大
  1939. if abs(new_col_y - col[3]) <= box_height:
  1940. split_col_list[i][j][3] = max([new_col_y, col[3]])
  1941. else:
  1942. new_row_lines.append([left_line[2], right_line[3], right_line[2], right_line[3]])
  1943. new_col_y = right_line[3]
  1944. # 补了row,要将其他短的col连到row上
  1945. for j in range(len(split_col_list[i])):
  1946. col = split_col_list[i][j]
  1947. # 且距离不能相差太大
  1948. if abs(new_col_y - col[3]) <= box_height:
  1949. split_col_list[i][j][3] = max([new_col_y, col[3]])
  1950. # 补上下两条横线超出来的线的col
  1951. if (left_line[0] - up_line[0] >= 10 and left_line[0] - bottom_line[0] >= 2) or \
  1952. (left_line[0] - up_line[0] >= 2 and left_line[0] - bottom_line[0] >= 10):
  1953. if left_line[0] - up_line[0] >= left_line[0] - bottom_line[0]:
  1954. new_col_lines.append([up_line[0], up_line[1], up_line[0], bottom_line[1]])
  1955. new_row_x = up_line[0]
  1956. # 补了col,要将其他短的row连到col上
  1957. for j in range(len(split_row_list[i])):
  1958. row = split_row_list[i][j]
  1959. # 且距离不能相差太大
  1960. if abs(new_row_x - row[0]) <= box_width:
  1961. split_row_list[i][j][0] = min([new_row_x, row[0]])
  1962. else:
  1963. new_col_lines.append([bottom_line[0], up_line[1], bottom_line[0], bottom_line[1]])
  1964. new_row_x = bottom_line[0]
  1965. # 补了col,要将其他短的row连到col上
  1966. for j in range(len(split_row_list[i])):
  1967. row = split_row_list[i][j]
  1968. # 且距离不能相差太大
  1969. if abs(new_row_x - row[0]) <= box_width:
  1970. split_row_list[i][j][0] = min([new_row_x, row[0]])
  1971. if (up_line[2] - right_line[2] >= 10 and bottom_line[2] - right_line[2] >= 2) or \
  1972. (up_line[2] - right_line[2] >= 2 and bottom_line[2] - right_line[2] >= 10):
  1973. if up_line[2] - right_line[2] >= bottom_line[2] - right_line[2]:
  1974. new_col_lines.append([up_line[2], up_line[3], up_line[2], bottom_line[3]])
  1975. new_row_x = up_line[2]
  1976. # 补了col,要将其他短的row连到col上
  1977. for j in range(len(split_row_list[i])):
  1978. row = split_row_list[i][j]
  1979. # 且距离不能相差太大
  1980. if abs(new_row_x - row[2]) <= box_width:
  1981. split_row_list[i][j][2] = max([new_row_x, row[2]])
  1982. else:
  1983. new_col_lines.append([bottom_line[2], up_line[3], bottom_line[2], bottom_line[3]])
  1984. new_row_x = bottom_line[2]
  1985. # 补了col,要将其他短的row连到col上
  1986. for j in range(len(split_row_list[i])):
  1987. # 需判断该线在这个区域中
  1988. # if up_line2[1]-3 <= row[1] <= bottom_line2[1]+3:
  1989. row = split_row_list[i][j]
  1990. # 且距离不能相差太大
  1991. if abs(new_row_x - row[2]) <= box_width:
  1992. split_row_list[i][j][2] = max([new_row_x, row[2]])
  1993. all_longer_row_lines += split_row_list[i]
  1994. all_longer_col_lines += split_col_list[i]
  1995. # print("all_longer_row_lines", len(all_longer_row_lines), i)
  1996. # print("all_longer_col_lines", len(all_longer_col_lines), i)
  1997. # print("new_row_lines", len(new_row_lines), i)
  1998. # print("new_col_lines", len(new_col_lines), i)
  1999. # 删除表格内部的补线
  2000. # temp_list = []
  2001. # for row in new_row_lines:
  2002. # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
  2003. # continue
  2004. # temp_list.append(row)
  2005. # print("fix_outline", new_row_lines)
  2006. # new_row_lines = temp_list
  2007. # print("fix_outline", new_row_lines)
  2008. # temp_list = []
  2009. # for col in new_col_lines:
  2010. # if left_line[0]-5 <= col[0] <= right_line[0]+5:
  2011. # continue
  2012. # temp_list.append(col)
  2013. #
  2014. # new_col_lines = temp_list
  2015. # print("fix_outline", new_col_lines)
  2016. # print("fix_outline", new_row_lines)
  2017. # 删除重复包含的补线
  2018. # temp_list = []
  2019. # for row in new_row_lines:
  2020. # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
  2021. # continue
  2022. # temp_list.append(row)
  2023. # new_row_lines = temp_list
  2024. # 展示上下左右边框线
  2025. # for i in range(len(area_row_line)):
  2026. # print("row1", area_row_line[i])
  2027. # print("row2", area_row_line2[i])
  2028. # print("col1", area_col_line[i])
  2029. # print("col2", area_col_line2[i])
  2030. # cv2.line(image, (int(area_row_line[i][0][0]), int(area_row_line[i][0][1])),
  2031. # (int(area_row_line[i][0][2]), int(area_row_line[i][0][3])), (0, 255, 0), 2)
  2032. # cv2.line(image, (int(area_row_line2[i][1][0]), int(area_row_line2[i][1][1])),
  2033. # (int(area_row_line2[i][1][2]), int(area_row_line2[i][1][3])), (0, 0, 255), 2)
  2034. # cv2.imshow("fix_outline", image)
  2035. # cv2.waitKey(0)
  2036. # 展示所有线
  2037. # for line in all_longer_col_lines:
  2038. # cv2.line(image, (int(line[0]), int(line[1])),
  2039. # (int(line[2]), int(line[3])),
  2040. # (0, 255, 0), 2)
  2041. # cv2.imshow("fix_outline", image)
  2042. # cv2.waitKey(0)
  2043. # for line in all_longer_row_lines:
  2044. # cv2.line(image, (int(line[0]), int(line[1])),
  2045. # (int(line[2]), int(line[3])),
  2046. # (0, 0, 255), 2)
  2047. # cv2.imshow("fix_outline", image)
  2048. # cv2.waitKey(0)
  2049. return new_row_lines, new_col_lines, all_longer_row_lines, all_longer_col_lines
  2050. def fix_outline(image, row_lines, col_lines, points, split_y, scale=25):
  2051. log("into fix_outline")
  2052. x_min_len = max(10, int(image.shape[0] / scale))
  2053. y_min_len = max(10, int(image.shape[1] / scale))
  2054. # print("x_min_len", x_min_len, "y_min_len", y_min_len)
  2055. # print("split_y", split_y)
  2056. # 分割线纵坐标
  2057. if len(split_y) < 2:
  2058. return [], [], [], []
  2059. split_y.sort(key=lambda x: x)
  2060. new_split_y = []
  2061. for i in range(1, len(split_y), 2):
  2062. new_split_y.append(int((split_y[i] + split_y[i - 1]) / 2))
  2063. split_row_list = []
  2064. split_col_list = []
  2065. split_point_list = []
  2066. for i in range(1, len(split_y)):
  2067. y = split_y[i]
  2068. last_y = split_y[i - 1]
  2069. split_row = []
  2070. for row in row_lines:
  2071. if last_y <= row[3] <= y:
  2072. split_row.append(row)
  2073. split_row_list.append(split_row)
  2074. split_col = []
  2075. for col in col_lines:
  2076. if last_y <= col[1] <= y or last_y <= col[3] <= y or col[1] < last_y < y < col[3]:
  2077. split_col.append(col)
  2078. split_col_list.append(split_col)
  2079. split_point = []
  2080. for point in points:
  2081. if last_y <= point[1] <= y:
  2082. split_point.append(point)
  2083. split_point_list.append(split_point)
  2084. # 预测线取上下左右4个边(会有超出表格部分) [(), ()]
  2085. area_row_line = []
  2086. area_col_line = []
  2087. for area in split_row_list:
  2088. if not area:
  2089. area_row_line.append([])
  2090. continue
  2091. area.sort(key=lambda x: (x[1], x[0]))
  2092. up_line = area[0]
  2093. bottom_line = area[-1]
  2094. area_row_line.append([up_line, bottom_line])
  2095. for area in split_col_list:
  2096. if not area:
  2097. area_col_line.append([])
  2098. continue
  2099. area.sort(key=lambda x: x[0])
  2100. left_line = area[0]
  2101. right_line = area[-1]
  2102. area_col_line.append([left_line, right_line])
  2103. # 取每个分割区域的4条线(无超出表格部分)
  2104. area_row_line2 = []
  2105. area_col_line2 = []
  2106. for area in split_point_list:
  2107. if not area:
  2108. area_row_line2.append([])
  2109. area_col_line2.append([])
  2110. continue
  2111. area.sort(key=lambda x: (x[0], x[1]))
  2112. left_up = area[0]
  2113. right_bottom = area[-1]
  2114. up_line = [left_up[0], left_up[1], right_bottom[0], left_up[1]]
  2115. bottom_line = [left_up[0], right_bottom[1], right_bottom[0], right_bottom[1]]
  2116. left_line = [left_up[0], left_up[1], left_up[0], right_bottom[1]]
  2117. right_line = [right_bottom[0], left_up[1], right_bottom[0], right_bottom[1]]
  2118. area_row_line2.append([up_line, bottom_line])
  2119. area_col_line2.append([left_line, right_line])
  2120. # 判断超出部分的长度,超出一定长度就补线
  2121. new_row_lines = []
  2122. new_col_lines = []
  2123. longer_row_lines = []
  2124. longer_col_lines = []
  2125. all_longer_row_lines = []
  2126. all_longer_col_lines = []
  2127. for i in range(len(area_row_line)):
  2128. if not area_row_line[i] or not area_col_line[i]:
  2129. continue
  2130. up_line = area_row_line[i][0]
  2131. # up_line2 = area_row_line2[i][0]
  2132. bottom_line = area_row_line[i][1]
  2133. # bottom_line2 = area_row_line2[i][1]
  2134. left_line = area_col_line[i][0]
  2135. # left_line2 = area_col_line2[i][0]
  2136. right_line = area_col_line[i][1]
  2137. # right_line2 = area_col_line2[i][1]
  2138. # 计算单格高度宽度
  2139. if len(split_row_list[i]) > 1:
  2140. height_dict = {}
  2141. for j in range(len(split_row_list[i])):
  2142. if j + 1 > len(split_row_list[i]) - 1:
  2143. break
  2144. # print("height_dict", split_row_list[i][j], split_row_list[i][j+1])
  2145. height = abs(int(split_row_list[i][j][3] - split_row_list[i][j + 1][3]))
  2146. if height >= 10:
  2147. if height in height_dict.keys():
  2148. height_dict[height] = height_dict[height] + 1
  2149. else:
  2150. height_dict[height] = 1
  2151. height_list = [[x, height_dict[x]] for x in height_dict.keys()]
  2152. if height_list:
  2153. height_list.sort(key=lambda x: (x[1], -x[0]), reverse=True)
  2154. # print("box_height", height_list)
  2155. box_height = height_list[0][0]
  2156. else:
  2157. box_height = y_min_len
  2158. else:
  2159. box_height = y_min_len
  2160. if len(split_col_list[i]) > 1:
  2161. box_width = abs(split_col_list[i][1][2] - split_col_list[i][0][2])
  2162. else:
  2163. box_width = x_min_len
  2164. # print("box_height", box_height, "box_width", box_width)
  2165. # 设置轮廓线需超出阈值
  2166. if box_height >= 2 * y_min_len:
  2167. fix_h_len = y_min_len
  2168. else:
  2169. fix_h_len = box_height * 2 / 3
  2170. if box_width >= 2 * x_min_len:
  2171. fix_w_len = x_min_len
  2172. else:
  2173. fix_w_len = box_width * 2 / 3
  2174. # 补左右两条竖线超出来的线的row
  2175. if up_line[1] - left_line[1] >= fix_h_len and up_line[1] - right_line[1] >= fix_h_len:
  2176. if up_line[1] - left_line[1] >= up_line[1] - right_line[1]:
  2177. new_row_lines.append([left_line[0], left_line[1], right_line[0], left_line[1]])
  2178. new_col_y = left_line[1]
  2179. # 补了row,要将其他短的col连到row上
  2180. for j in range(len(split_col_list[i])):
  2181. col = split_col_list[i][j]
  2182. # 且距离不能相差大于一格
  2183. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  2184. if abs(new_col_y - col[1]) <= box_height:
  2185. split_col_list[i][j][1] = min([new_col_y, col[1]])
  2186. longer_col_lines.append([col[0], min([new_col_y, col[1]]), col[2], col[3]])
  2187. else:
  2188. new_row_lines.append([left_line[0], right_line[1], right_line[0], right_line[1]])
  2189. new_col_y = right_line[1]
  2190. # 补了row,要将其他短的col连到row上
  2191. for j in range(len(split_col_list[i])):
  2192. # 需判断该线在这个区域中
  2193. # if up_line2[1]-3 <= col[1] <= col[3] <= bottom_line2[1]+3:
  2194. col = split_col_list[i][j]
  2195. # 且距离不能相差太大
  2196. # print("abs(new_col_y - col[1])", abs(new_col_y - col[1]))
  2197. if abs(new_col_y - col[1]) <= box_height:
  2198. split_col_list[i][j][1] = min([new_col_y, col[1]])
  2199. if left_line[3] - bottom_line[3] >= fix_h_len and right_line[3] - bottom_line[3] >= fix_h_len:
  2200. if left_line[3] - bottom_line[3] >= right_line[3] - bottom_line[3]:
  2201. new_row_lines.append([left_line[2], left_line[3], right_line[2], left_line[3]])
  2202. new_col_y = left_line[3]
  2203. # 补了row,要将其他短的col连到row上
  2204. for j in range(len(split_col_list[i])):
  2205. col = split_col_list[i][j]
  2206. # 且距离不能相差太大
  2207. if abs(new_col_y - col[3]) <= box_height:
  2208. split_col_list[i][j][3] = max([new_col_y, col[3]])
  2209. else:
  2210. new_row_lines.append([left_line[2], right_line[3], right_line[2], right_line[3]])
  2211. new_col_y = right_line[3]
  2212. # 补了row,要将其他短的col连到row上
  2213. for j in range(len(split_col_list[i])):
  2214. col = split_col_list[i][j]
  2215. # 且距离不能相差太大
  2216. if abs(new_col_y - col[3]) <= box_height:
  2217. split_col_list[i][j][3] = max([new_col_y, col[3]])
  2218. # 补上下两条横线超出来的线的col
  2219. if left_line[0] - up_line[0] >= fix_w_len and left_line[0] - bottom_line[0] >= fix_w_len:
  2220. if left_line[0] - up_line[0] >= left_line[0] - bottom_line[0]:
  2221. new_col_lines.append([up_line[0], up_line[1], up_line[0], bottom_line[1]])
  2222. new_row_x = up_line[0]
  2223. # 补了col,要将其他短的row连到col上
  2224. for j in range(len(split_row_list[i])):
  2225. row = split_row_list[i][j]
  2226. # 且距离不能相差太大
  2227. if abs(new_row_x - row[0]) <= box_width:
  2228. split_row_list[i][j][0] = min([new_row_x, row[0]])
  2229. else:
  2230. new_col_lines.append([bottom_line[0], up_line[1], bottom_line[0], bottom_line[1]])
  2231. new_row_x = bottom_line[0]
  2232. # 补了col,要将其他短的row连到col上
  2233. for j in range(len(split_row_list[i])):
  2234. row = split_row_list[i][j]
  2235. # 且距离不能相差太大
  2236. if abs(new_row_x - row[0]) <= box_width:
  2237. split_row_list[i][j][0] = min([new_row_x, row[0]])
  2238. if up_line[2] - right_line[2] >= fix_w_len and bottom_line[2] - right_line[2] >= fix_w_len:
  2239. if up_line[2] - right_line[2] >= bottom_line[2] - right_line[2]:
  2240. new_col_lines.append([up_line[2], up_line[3], up_line[2], bottom_line[3]])
  2241. new_row_x = up_line[2]
  2242. # 补了col,要将其他短的row连到col上
  2243. for j in range(len(split_row_list[i])):
  2244. row = split_row_list[i][j]
  2245. # 且距离不能相差太大
  2246. if abs(new_row_x - row[2]) <= box_width:
  2247. split_row_list[i][j][2] = max([new_row_x, row[2]])
  2248. else:
  2249. new_col_lines.append([bottom_line[2], up_line[3], bottom_line[2], bottom_line[3]])
  2250. new_row_x = bottom_line[2]
  2251. # 补了col,要将其他短的row连到col上
  2252. for j in range(len(split_row_list[i])):
  2253. # 需判断该线在这个区域中
  2254. # if up_line2[1]-3 <= row[1] <= bottom_line2[1]+3:
  2255. row = split_row_list[i][j]
  2256. # 且距离不能相差太大
  2257. if abs(new_row_x - row[2]) <= box_width:
  2258. split_row_list[i][j][2] = max([new_row_x, row[2]])
  2259. all_longer_row_lines += split_row_list[i]
  2260. all_longer_col_lines += split_col_list[i]
  2261. return new_row_lines, new_col_lines, all_longer_row_lines, all_longer_col_lines
  2262. def fix_table(row_point_list, col_point_list, split_y, row_lines, col_lines):
  2263. # 分割线纵坐标
  2264. if len(split_y) < 2:
  2265. return []
  2266. # 获取bbox
  2267. bbox = []
  2268. # 每个点获取与其x最相近和y最相近的点
  2269. for i in range(1, len(split_y)):
  2270. # 循环每行
  2271. for row in row_point_list:
  2272. row.sort(key=lambda x: (x[0], x[1]))
  2273. # 行不在该区域跳过
  2274. if row[0][1] <= split_y[i - 1] or row[0][1] >= split_y[i]:
  2275. continue
  2276. # print("len(row)", len(row))
  2277. # print("row", row)
  2278. # 循环行中的点
  2279. for j in range(len(row)):
  2280. if j == len(row) - 1:
  2281. break
  2282. current_point = row[j]
  2283. next_point_in_row_list = row[j + 1:]
  2284. # 循环这一行的下一个点
  2285. for next_point_in_row in next_point_in_row_list:
  2286. # 是否在这一行点找到,找不到就这一行的下个点
  2287. not_found = 1
  2288. # 查询下个点所在列
  2289. next_col = []
  2290. for col in col_point_list:
  2291. col.sort(key=lambda x: (x[1], x[0]))
  2292. # 列不在该区域跳过
  2293. if col[0][1] <= split_y[i - 1] or col[-1][1] >= split_y[i]:
  2294. continue
  2295. if col[0][0] - 3 <= next_point_in_row[0] <= col[0][0] + 3:
  2296. next_col = col
  2297. break
  2298. # 循环匹配当前点和下一列点
  2299. next_col.sort(key=lambda x: (x[1], x[0]))
  2300. for point1 in next_col:
  2301. # 同一行的就跳过
  2302. if current_point[1] - 3 <= point1[1] <= current_point[1] + 3:
  2303. continue
  2304. if point1[1] <= current_point[1] - 3:
  2305. continue
  2306. # 候选bbox
  2307. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  2308. # print("candidate_bbox", candidate_bbox)
  2309. # 判断该bbox是否存在,判断bbox的上下两条边是否有包含在row中
  2310. contain_flag1 = 0
  2311. contain_flag2 = 0
  2312. for row1 in row_lines:
  2313. # 行不在该区域跳过
  2314. if row1[1] <= split_y[i - 1] or row1[1] >= split_y[i]:
  2315. continue
  2316. # bbox上边框 y一样
  2317. if not contain_flag1:
  2318. if row1[1] - 3 <= candidate_bbox[1] <= row1[1] + 3:
  2319. # 格子里的断开线段
  2320. row1_break = (max([row1[0], candidate_bbox[0]]),
  2321. row1[1],
  2322. min([row1[2], candidate_bbox[2]]),
  2323. row1[3])
  2324. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0]) / 3:
  2325. contain_flag1 = 1
  2326. # bbox下边框 y一样
  2327. if not contain_flag2:
  2328. if row1[1] - 3 <= candidate_bbox[3] <= row1[1] + 3:
  2329. # 格子里的断开线段
  2330. row1_break = (max([row1[0], candidate_bbox[0]]),
  2331. row1[1],
  2332. min([row1[2], candidate_bbox[2]]),
  2333. row1[3])
  2334. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0]) / 3:
  2335. contain_flag2 = 1
  2336. # 判断该bbox是否存在,判断bbox的左右两条边是否有包含在col中
  2337. contain_flag3 = 0
  2338. contain_flag4 = 0
  2339. for col1 in col_lines:
  2340. # 列不在该区域跳过
  2341. if col1[1] <= split_y[i - 1] or col1[3] >= split_y[i]:
  2342. continue
  2343. # bbox左边线 x一样
  2344. if not contain_flag3:
  2345. if col1[0] - 3 <= candidate_bbox[0] <= col1[0] + 3:
  2346. # 格子里的断开线段
  2347. col1_break = (col1[0],
  2348. max([col1[1], candidate_bbox[1]]),
  2349. col1[2],
  2350. min([col1[3], candidate_bbox[3]]))
  2351. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1]) / 3:
  2352. contain_flag3 = 1
  2353. # bbox右边框 x一样
  2354. if not contain_flag4:
  2355. if col1[0] - 3 <= candidate_bbox[2] <= col1[0] + 3:
  2356. # 格子里的断开线段
  2357. col1_break = (col1[0],
  2358. max([col1[1], candidate_bbox[1]]),
  2359. col1[2],
  2360. min([col1[3], candidate_bbox[3]]))
  2361. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1]) / 3:
  2362. contain_flag4 = 1
  2363. # 找到了该bbox,并且是存在的
  2364. if contain_flag1 and contain_flag2 and contain_flag3 and contain_flag4:
  2365. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  2366. (candidate_bbox[2], candidate_bbox[3])])
  2367. not_found = 0
  2368. break
  2369. if not not_found:
  2370. break
  2371. return bbox
  2372. def delete_close_points(point_list, row_point_list, col_point_list, threshold=5):
  2373. new_point_list = []
  2374. delete_point_list = []
  2375. point_list.sort(key=lambda x: (x[1], x[0]))
  2376. for i in range(len(point_list)):
  2377. point1 = point_list[i]
  2378. if point1 in delete_point_list:
  2379. continue
  2380. if i == len(point_list) - 1:
  2381. new_point_list.append(point1)
  2382. break
  2383. point2 = point_list[i + 1]
  2384. # 判断坐标
  2385. if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
  2386. new_point_list.append(point1)
  2387. else:
  2388. # 看两个点上的相同坐标点哪个多,就保留哪个
  2389. count1 = 0
  2390. count2 = 0
  2391. for col in col_point_list:
  2392. if point1[0] == col[0][0]:
  2393. count1 += len(col)
  2394. elif point2[0] == col[0][0]:
  2395. count2 += len(col)
  2396. if count1 >= count2:
  2397. new_point_list.append(point1)
  2398. delete_point_list.append(point2)
  2399. else:
  2400. new_point_list.append(point2)
  2401. delete_point_list.append(point1)
  2402. point_list = new_point_list
  2403. new_point_list = []
  2404. delete_point_list = []
  2405. point_list.sort(key=lambda x: (x[0], x[1]))
  2406. for i in range(len(point_list)):
  2407. point1 = point_list[i]
  2408. if point1 in delete_point_list:
  2409. continue
  2410. if i == len(point_list) - 1:
  2411. new_point_list.append(point1)
  2412. break
  2413. point2 = point_list[i + 1]
  2414. # 判断坐标
  2415. if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
  2416. new_point_list.append(point1)
  2417. else:
  2418. count1 = 0
  2419. count2 = 0
  2420. for row in row_point_list:
  2421. if point1[0] == row[0][0]:
  2422. count1 += len(row)
  2423. elif point2[0] == row[0][0]:
  2424. count2 += len(row)
  2425. if count1 >= count2:
  2426. new_point_list.append(point1)
  2427. delete_point_list.append(point2)
  2428. else:
  2429. new_point_list.append(point2)
  2430. delete_point_list.append(point1)
  2431. return new_point_list
  2432. def get_bbox2(image_np, points):
  2433. # # 坐标点按行分
  2434. # row_point_list = []
  2435. # row_point = []
  2436. # points.sort(key=lambda x: (x[0], x[1]))
  2437. # for p in points:
  2438. # if len(row_point) == 0:
  2439. # x = p[0]
  2440. # if x-5 <= p[0] <= x+5:
  2441. # row_point.append(p)
  2442. # else:
  2443. # row_point_list.append(row_point)
  2444. # row_point = []
  2445. # # 坐标点按列分
  2446. # col_point_list = []
  2447. # col_point = []
  2448. # points.sort(key=lambda x: (x[1], x[0]))
  2449. # for p in points:
  2450. # if len(col_point) == 0:
  2451. # y = p[1]
  2452. # if y-5 <= p[1] <= y+5:
  2453. # col_point.append(p)
  2454. # else:
  2455. # col_point_list.append(col_point)
  2456. # col_point = []
  2457. row_point_list = get_points_row(points)
  2458. col_point_list = get_points_col(points)
  2459. print("len(points)", len(points))
  2460. for point in points:
  2461. cv2.circle(image_np, point, 1, (0, 255, 0), 1)
  2462. cv2.imshow("points_deleted", image_np)
  2463. points = delete_close_points(points, row_point_list, col_point_list)
  2464. print("len(points)", len(points))
  2465. for point in points:
  2466. cv2.circle(image_np, point, 1, (255, 0, 0), 3)
  2467. cv2.imshow("points_deleted", image_np)
  2468. cv2.waitKey(0)
  2469. row_point_list = get_points_row(points, 5)
  2470. col_point_list = get_points_col(points, 5)
  2471. print("len(row_point_list)", len(row_point_list))
  2472. for row in row_point_list:
  2473. print("row", len(row))
  2474. print("col_point_list", len(col_point_list))
  2475. for col in col_point_list:
  2476. print("col", len(col))
  2477. bbox = []
  2478. for i in range(len(row_point_list)):
  2479. if i == len(row_point_list) - 1:
  2480. break
  2481. # 遍历每个row的point,找到其所在列的下一个点和所在行的下一个点
  2482. current_row = row_point_list[i]
  2483. for j in range(len(current_row)):
  2484. current_point = current_row[j]
  2485. if j == len(current_row) - 1:
  2486. break
  2487. next_row_point = current_row[j + 1]
  2488. # 找出当前点所在的col,得到该列下一个point
  2489. current_col = col_point_list[j]
  2490. for k in range(len(current_col)):
  2491. if current_col[k][1] > current_point[1] + 10:
  2492. next_col_point = current_col[k]
  2493. break
  2494. next_row = row_point_list[k]
  2495. for k in range(len(next_row)):
  2496. if next_row[k][0] >= next_row_point[0] + 5:
  2497. next_point = next_row[k]
  2498. break
  2499. # 得到bbox
  2500. bbox.append([(current_point[0], current_point[1]), (next_point[0], next_point[1])])
  2501. # bbox = []
  2502. # for p in points:
  2503. # # print("p", p)
  2504. # p_row = []
  2505. # p_col = []
  2506. # for row in row_point_list:
  2507. # if p[0] == row[0][0]:
  2508. # for p1 in row:
  2509. # if abs(p[1]-p1[1]) <= 5:
  2510. # continue
  2511. # p_row.append([p1, abs(p[1]-p1[1])])
  2512. # p_row.sort(key=lambda x: x[1])
  2513. # for col in col_point_list:
  2514. # if p[1] == col[0][1]:
  2515. # for p2 in col:
  2516. # if abs(p[0]-p2[0]) <= 5:
  2517. # continue
  2518. # p_col.append([p2, abs(p[0]-p2[0])])
  2519. # p_col.sort(key=lambda x: x[1])
  2520. # if len(p_row) == 0 or len(p_col) == 0:
  2521. # continue
  2522. # break_flag = 0
  2523. # for i in range(len(p_row)):
  2524. # for j in range(len(p_col)):
  2525. # # print(p_row[i][0])
  2526. # # print(p_col[j][0])
  2527. # another_point = (p_col[j][0][0], p_row[i][0][1])
  2528. # # print("another_point", another_point)
  2529. # if abs(p[0]-another_point[0]) <= 5 or abs(p[1]-another_point[1]) <= 5:
  2530. # continue
  2531. # if p[0] >= another_point[0] or p[1] >= another_point[1]:
  2532. # continue
  2533. # if another_point in points:
  2534. # box = [p, another_point]
  2535. # box.sort(key=lambda x: x[0])
  2536. # if box not in bbox:
  2537. # bbox.append(box)
  2538. # break_flag = 1
  2539. # break
  2540. # if break_flag:
  2541. # break
  2542. #
  2543. # # delete duplicate
  2544. # delete_bbox = []
  2545. # for i in range(len(bbox)):
  2546. # for j in range(i+1, len(bbox)):
  2547. # if bbox[i][0] == bbox[j][0]:
  2548. # if bbox[i][1][0] - bbox[j][1][0] <= 3 \
  2549. # and bbox[i][1][1] - bbox[j][1][1] <= 3:
  2550. # delete_bbox.append(bbox[j])
  2551. # if bbox[i][1] == bbox[j][1]:
  2552. # if bbox[i][0][0] - bbox[j][0][0] <= 3 \
  2553. # and bbox[i][0][1] - bbox[j][0][1] <= 3:
  2554. # delete_bbox.append(bbox[j])
  2555. # # delete too small area
  2556. # # for box in bbox:
  2557. # # if box[1][0] - box[0][0] <=
  2558. # for d_box in delete_bbox:
  2559. # if d_box in bbox:
  2560. # bbox.remove(d_box)
  2561. # print bbox
  2562. bbox.sort(key=lambda x: (x[0][0], x[0][1], x[1][0], x[1][1]))
  2563. # origin bbox
  2564. # origin_bbox = []
  2565. # for box in bbox:
  2566. # origin_bbox.append([(box[0][0], box[0][1] - 40), (box[1][0], box[1][1] - 40)])
  2567. # for box in origin_bbox:
  2568. # cv2.rectangle(origin_image, box[0], box[1], (0, 0, 255), 2, 8)
  2569. # cv2.imshow('AlanWang', origin_image)
  2570. # cv2.waitKey(0)
  2571. for box in bbox:
  2572. cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
  2573. cv2.imshow('bboxes', image_np)
  2574. cv2.waitKey(0)
  2575. # for point in points:
  2576. # print(point)
  2577. # cv2.circle(image_np, point, 1, (0, 0, 255), 3)
  2578. # cv2.imshow('points', image_np)
  2579. # cv2.waitKey(0)
  2580. return bbox
  2581. def get_bbox1(image_np, points, split_y):
  2582. # 分割线纵坐标
  2583. # print("split_y", split_y)
  2584. if len(split_y) < 2:
  2585. return []
  2586. # 计算行列,剔除相近交点
  2587. row_point_list = get_points_row(points)
  2588. col_point_list = get_points_col(points)
  2589. print("len(row_point_list)", row_point_list)
  2590. print("len(col_point_list)", len(col_point_list))
  2591. # for point in points:
  2592. # cv2.circle(image_np, point, 1, (0, 255, 0), 1)
  2593. # cv2.imshow("points", image_np)
  2594. points = delete_close_points(points, row_point_list, col_point_list)
  2595. # print("len(points)", len(points))
  2596. # for point in points:
  2597. # cv2.circle(image_np, point, 1, (255, 0, 0), 3)
  2598. # cv2.imshow("points_deleted", image_np)
  2599. # cv2.waitKey(0)
  2600. # 获取bbox
  2601. bbox = []
  2602. # 每个点获取与其x最相近和y最相近的点
  2603. for i in range(1, len(split_y)):
  2604. for point1 in points:
  2605. if point1[1] <= split_y[i - 1] or point1[1] >= split_y[i]:
  2606. continue
  2607. distance_x = 10000
  2608. distance_y = 10000
  2609. x = 0
  2610. y = 0
  2611. threshold = 10
  2612. for point2 in points:
  2613. if point2[1] <= split_y[i - 1] or point2[1] >= split_y[i]:
  2614. continue
  2615. # 最近 x y
  2616. if 2 < point2[0] - point1[0] < distance_x and point2[1] - point1[1] <= threshold:
  2617. distance_x = point2[0] - point1[0]
  2618. x = point2[0]
  2619. if 2 < point2[1] - point1[1] < distance_y and point2[0] - point1[0] <= threshold:
  2620. distance_y = point2[1] - point1[1]
  2621. y = point2[1]
  2622. if not x or not y:
  2623. continue
  2624. bbox.append([(point1[0], point1[1]), (x, y)])
  2625. # 删除包含关系bbox
  2626. temp_list = []
  2627. for i in range(len(bbox)):
  2628. box1 = bbox[i]
  2629. for j in range(len(bbox)):
  2630. if i == j:
  2631. continue
  2632. box2 = bbox[j]
  2633. contain_flag = 0
  2634. if box2[0][0] <= box1[0][0] <= box1[1][0] <= box2[1][0] and \
  2635. box2[0][1] <= box1[0][1] <= box1[1][1] <= box2[1][1]:
  2636. contain_flag = 1
  2637. break
  2638. temp_list.append(box1)
  2639. bbox = temp_list
  2640. # 展示
  2641. for box in bbox:
  2642. # print(box[0], box[1])
  2643. # if abs(box[0][1] - box[1][1]) > abs(box[0][0] - box[1][0]):
  2644. # continue
  2645. cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
  2646. cv2.imshow('bboxes', image_np)
  2647. cv2.waitKey(0)
  2648. return bbox
  2649. def get_bbox0(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  2650. # 分割线纵坐标
  2651. if len(split_y) < 2:
  2652. return []
  2653. # 计算行列,剔除相近交点
  2654. # row_point_list = get_points_row(points)
  2655. # col_point_list = get_points_col(points)
  2656. # points = delete_close_points(points, row_point_list, col_point_list)
  2657. # row_point_list = get_points_row(points)
  2658. # col_point_list = get_points_col(points)
  2659. # 获取bbox
  2660. bbox = []
  2661. # print("get_bbox split_y", split_y)
  2662. # 每个点获取与其x最相近和y最相近的点
  2663. for i in range(1, len(split_y)):
  2664. # 循环每行
  2665. for row in row_point_list:
  2666. row.sort(key=lambda x: (x[0], x[1]))
  2667. # 行不在该区域跳过
  2668. if row[0][1] <= split_y[i - 1] or row[0][1] >= split_y[i]:
  2669. continue
  2670. # 循环行中的点
  2671. for j in range(len(row)):
  2672. if j == len(row) - 1:
  2673. break
  2674. current_point = row[j]
  2675. next_point_in_row = row[j + 1]
  2676. # 查询下个点所在列
  2677. next_col = []
  2678. for col in col_point_list:
  2679. col.sort(key=lambda x: (x[1], x[0]))
  2680. # 列不在该区域跳过
  2681. if col[0][1] <= split_y[i - 1] or col[-1][1] >= split_y[i]:
  2682. continue
  2683. if col[0][0] - 3 <= next_point_in_row[0] <= col[0][0] + 3:
  2684. next_col = col
  2685. break
  2686. # 循环匹配当前点和下一列点
  2687. for point1 in next_col:
  2688. # 同一行的就跳过
  2689. if current_point[1] - 3 <= point1[1] <= current_point[1] + 3:
  2690. continue
  2691. if point1[1] <= current_point[1] - 3:
  2692. continue
  2693. # 候选bbox
  2694. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  2695. # 判断该bbox是否存在,线条包含关系
  2696. contain_flag1 = 0
  2697. contain_flag2 = 0
  2698. for row1 in row_lines:
  2699. # 行不在该区域跳过
  2700. if row1[1] <= split_y[i - 1] or row1[1] >= split_y[i]:
  2701. continue
  2702. # bbox上边框 y一样
  2703. if not contain_flag1:
  2704. if row1[1] - 3 <= candidate_bbox[1] <= row1[1] + 3:
  2705. # candidate的x1,x2需被包含在row线中
  2706. if row1[0] - 3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2] + 3:
  2707. contain_flag1 = 1
  2708. # bbox下边框 y一样
  2709. if not contain_flag2:
  2710. if row1[1] - 3 <= candidate_bbox[3] <= row1[1] + 3:
  2711. # candidate的x1,x2需被包含在row线中
  2712. if row1[0] - 3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2] + 3:
  2713. contain_flag2 = 1
  2714. # 找到了该bbox,并且是存在的
  2715. if contain_flag1 and contain_flag2:
  2716. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  2717. (candidate_bbox[2], candidate_bbox[3])])
  2718. break
  2719. return bbox
  2720. def get_bbox3(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  2721. # 分割线纵坐标
  2722. if len(split_y) < 2:
  2723. return []
  2724. # 获取bbox
  2725. bbox = []
  2726. # 每个点获取与其x最相近和y最相近的点
  2727. for i in range(1, len(split_y)):
  2728. # 循环每行
  2729. for row in row_point_list:
  2730. row.sort(key=lambda x: (x[0], x[1]))
  2731. # 行不在该区域跳过
  2732. if row[0][1] <= split_y[i - 1] or row[0][1] >= split_y[i]:
  2733. continue
  2734. # print("len(row)", len(row))
  2735. # print("row", row)
  2736. # 循环行中的点
  2737. for j in range(len(row)):
  2738. if j == len(row) - 1:
  2739. break
  2740. current_point = row[j]
  2741. # print("current_point", current_point)
  2742. next_point_in_row_list = row[j + 1:]
  2743. # 循环这一行的下一个点
  2744. for next_point_in_row in next_point_in_row_list:
  2745. # 是否在这一行点找到,找不到就这一行的下个点
  2746. not_found = 1
  2747. # 查询下个点所在列
  2748. next_col = []
  2749. for col in col_point_list:
  2750. col.sort(key=lambda x: (x[1], x[0]))
  2751. # 列不在该区域跳过
  2752. if col[0][1] <= split_y[i - 1] or col[-1][1] >= split_y[i]:
  2753. continue
  2754. if col[0][0] - 3 <= next_point_in_row[0] <= col[0][0] + 3:
  2755. next_col = col
  2756. break
  2757. # 循环匹配当前点和下一列点
  2758. next_col.sort(key=lambda x: (x[1], x[0]))
  2759. for point1 in next_col:
  2760. # 同一行的就跳过
  2761. if current_point[1] - 3 <= point1[1] <= current_point[1] + 3:
  2762. continue
  2763. if point1[1] <= current_point[1] - 3:
  2764. continue
  2765. # 候选bbox
  2766. candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
  2767. # print("candidate_bbox", candidate_bbox)
  2768. # 判断该bbox是否存在,判断bbox的上下两条边是否有包含在row中
  2769. contain_flag1 = 0
  2770. contain_flag2 = 0
  2771. for row1 in row_lines:
  2772. # 行不在该区域跳过
  2773. if row1[1] <= split_y[i - 1] or row1[1] >= split_y[i]:
  2774. continue
  2775. # bbox上边框 y一样
  2776. if not contain_flag1:
  2777. if row1[1] - 3 <= candidate_bbox[1] <= row1[1] + 3:
  2778. # 格子里的断开线段
  2779. row1_break = (max([row1[0], candidate_bbox[0]]),
  2780. row1[1],
  2781. min([row1[2], candidate_bbox[2]]),
  2782. row1[3])
  2783. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0]) / 3:
  2784. contain_flag1 = 1
  2785. # # candidate的x1,x2需被包含在row线中
  2786. # if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  2787. # contain_flag1 = 1
  2788. #
  2789. # # 判断线条有无端点在格子中
  2790. # elif candidate_bbox[0] < row1[0] < candidate_bbox[2] \
  2791. # or candidate_bbox[0] < row1[2] < candidate_bbox[2]:
  2792. # # 线条会有缺一点情况,判断长度超过格子一半
  2793. # if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  2794. # contain_flag1 = 1
  2795. # bbox下边框 y一样
  2796. if not contain_flag2:
  2797. if row1[1] - 3 <= candidate_bbox[3] <= row1[1] + 3:
  2798. # 格子里的断开线段
  2799. row1_break = (max([row1[0], candidate_bbox[0]]),
  2800. row1[1],
  2801. min([row1[2], candidate_bbox[2]]),
  2802. row1[3])
  2803. if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0]) / 3:
  2804. contain_flag2 = 1
  2805. # # candidate的x1,x2需被包含在row线中
  2806. # if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
  2807. # contain_flag2 = 1
  2808. #
  2809. # # 判断线条有无端点在格子中
  2810. # elif candidate_bbox[0] < row1[0] < candidate_bbox[2] \
  2811. # or candidate_bbox[0] < row1[2] < candidate_bbox[2]:
  2812. # # 线条会有缺一点情况,判断长度超过格子一半
  2813. # if row1_break[2] - row1_break[0] >= (candidate_bbox[2] - candidate_bbox[0])/3:
  2814. # contain_flag2 = 1
  2815. # 判断该bbox是否存在,判断bbox的左右两条边是否有包含在col中
  2816. contain_flag3 = 0
  2817. contain_flag4 = 0
  2818. for col1 in col_lines:
  2819. # 列不在该区域跳过
  2820. if col1[1] <= split_y[i - 1] or col1[3] >= split_y[i]:
  2821. continue
  2822. # bbox左边线 x一样
  2823. if not contain_flag3:
  2824. if col1[0] - 3 <= candidate_bbox[0] <= col1[0] + 3:
  2825. # 格子里的断开线段
  2826. col1_break = (col1[0],
  2827. max([col1[1], candidate_bbox[1]]),
  2828. col1[2],
  2829. min([col1[3], candidate_bbox[3]]))
  2830. if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1]) / 3:
  2831. contain_flag3 = 1
  2832. # # candidate的y1,y2需被包含在col线中
  2833. # if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
  2834. # contain_flag3 = 1
  2835. #
  2836. # # 判断线条有无端点在格子中
  2837. # elif candidate_bbox[1] < col1[1] < candidate_bbox[3] \
  2838. # or candidate_bbox[1] < col1[3] < candidate_bbox[3]:
  2839. # # 线条会有缺一点情况,判断长度超过格子一半
  2840. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  2841. # contain_flag3 = 1
  2842. # bbox右边框 x一样
  2843. if not contain_flag4:
  2844. if col1[0] - 3 <= candidate_bbox[2] <= col1[0] + 3:
  2845. # 格子里的断开线段
  2846. # col1_break = (col1[0],
  2847. # max([col1[1], candidate_bbox[1]]),
  2848. # col1[2],
  2849. # min([col1[3], candidate_bbox[3]]))
  2850. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  2851. # contain_flag4 = 1
  2852. # 如果候选bbox的边的上1/3或下1/3包含在col中
  2853. candidate_bbox_line1 = [candidate_bbox[1],
  2854. candidate_bbox[1] + (
  2855. candidate_bbox[3] - candidate_bbox[1]) / 3]
  2856. candidate_bbox_line2 = [
  2857. candidate_bbox[3] - (candidate_bbox[3] - candidate_bbox[1]) / 3,
  2858. candidate_bbox[3]]
  2859. if col1[1] <= candidate_bbox_line1[0] <= candidate_bbox_line1[1] <= col1[3] \
  2860. or col1[1] <= candidate_bbox_line2[0] <= candidate_bbox_line2[1] <= col1[3]:
  2861. # print("candidate_bbox", candidate_bbox)
  2862. # print("col1", col1)
  2863. contain_flag4 = 1
  2864. # # candidate的y1,y2需被包含在col线中
  2865. # if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
  2866. # contain_flag4 = 1
  2867. #
  2868. # # 判断线条有无端点在格子中
  2869. # elif candidate_bbox[1] < col1[1] < candidate_bbox[3] \
  2870. # or candidate_bbox[1] < col1[3] < candidate_bbox[3]:
  2871. # # 线条会有缺一点情况,判断长度超过格子一半
  2872. # if col1_break[3] - col1_break[1] >= (candidate_bbox[3] - candidate_bbox[1])/3:
  2873. # contain_flag4 = 1
  2874. # 找到了该bbox,并且是存在的
  2875. if contain_flag1 and contain_flag2 and contain_flag3 and contain_flag4:
  2876. bbox.append([(candidate_bbox[0], candidate_bbox[1]),
  2877. (candidate_bbox[2], candidate_bbox[3])])
  2878. not_found = 0
  2879. # print("exist candidate_bbox", candidate_bbox)
  2880. # print(contain_flag1, contain_flag2, contain_flag3, contain_flag4)
  2881. break
  2882. # else:
  2883. # print("candidate_bbox", candidate_bbox)
  2884. # print(contain_flag1, contain_flag2, contain_flag3, contain_flag4)
  2885. if not not_found:
  2886. break
  2887. return bbox
  2888. def get_bbox(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
  2889. # 分割线纵坐标
  2890. if len(split_y) < 2:
  2891. return []
  2892. # 获取bbox
  2893. bbox_list = []
  2894. for i in range(1, len(split_y)):
  2895. last_y = split_y[i - 1]
  2896. y = split_y[i]
  2897. # 先对点线进行分区
  2898. split_row_point_list = []
  2899. split_col_point_list = []
  2900. split_row_lines = []
  2901. split_col_lines = []
  2902. for row in row_point_list:
  2903. if last_y <= row[0][1] <= y:
  2904. row.sort(key=lambda x: (x[1], x[0]))
  2905. split_row_point_list.append(row)
  2906. for col in col_point_list:
  2907. if last_y <= col[0][1] <= y:
  2908. split_col_point_list.append(col)
  2909. for row in row_lines:
  2910. if last_y <= row[1] <= y:
  2911. split_row_lines.append(row)
  2912. for col in col_lines:
  2913. if last_y <= col[1] <= y:
  2914. split_col_lines.append(col)
  2915. # 每个点获取其对角线点,以便形成bbox,按行循环
  2916. for i in range(len(split_row_point_list) - 1):
  2917. row = split_row_point_list[i]
  2918. # 循环该行的点
  2919. for k in range(len(row) - 1):
  2920. point1 = row[k]
  2921. next_point1 = row[k + 1]
  2922. # print("*"*30)
  2923. # print("point1", point1)
  2924. # 有三种对角线点
  2925. # 1. 该点下一行的下一列的点
  2926. # 2. 该点下一列的下一行的点
  2927. # 3. 上述两个点是同一个点
  2928. # 下一行没找到就循环后面的行
  2929. if_find = 0
  2930. for j in range(i + 1, len(split_row_point_list)):
  2931. if if_find:
  2932. break
  2933. next_row = split_row_point_list[j]
  2934. # print("next_row", next_row)
  2935. # 循环下一行的点
  2936. for point2 in next_row:
  2937. if abs(point1[0] - point2[0]) <= 2:
  2938. continue
  2939. if point2[0] < point1[0]:
  2940. continue
  2941. bbox = [point1[0], point1[1], point2[0], point2[1]]
  2942. if abs(bbox[0] - bbox[2]) <= 10:
  2943. continue
  2944. if abs(bbox[1] - bbox[3]) <= 10:
  2945. continue
  2946. # bbox的四条边都需要验证是否在line上
  2947. if check_bbox(bbox, split_row_lines, split_col_lines):
  2948. bbox_list.append([(bbox[0], bbox[1]), (bbox[2], bbox[3])])
  2949. if_find = 1
  2950. # print("check bbox", bbox)
  2951. break
  2952. return bbox_list
  2953. def check_bbox(bbox, rows, cols, threshold=5):
  2954. def check(check_line, lines, limit_axis, axis):
  2955. # 需检查的线的1/2段,1/3段,2/3段,1/4段,3/4段
  2956. line_1_2 = [check_line[0], (check_line[0] + check_line[1]) / 2]
  2957. line_2_2 = [(check_line[0] + check_line[1]) / 2, check_line[1]]
  2958. line_1_3 = [check_line[0], check_line[0] + (check_line[1] - check_line[0]) / 3]
  2959. line_2_3 = [check_line[1] - (check_line[1] - check_line[0]) / 3, check_line[1]]
  2960. line_1_4 = [check_line[0], check_line[0] + (check_line[1] - check_line[0]) / 4]
  2961. line_3_4 = [check_line[1] - (check_line[1] - check_line[0]) / 4, check_line[1]]
  2962. # 限制row相同y,col相同x
  2963. if_line = 0
  2964. for line1 in lines:
  2965. if not if_line and abs(line1[1 - axis] - limit_axis) <= threshold:
  2966. # check_line完全包含在line中
  2967. if line1[axis] <= check_line[0] <= check_line[1] <= line1[axis + 2]:
  2968. if_line = 1
  2969. # check_line的1/2包含在line
  2970. elif line1[axis] <= line_1_2[0] <= line_1_2[1] <= line1[axis + 2] \
  2971. or line1[axis] <= line_2_2[0] <= line_2_2[1] <= line1[axis + 2]:
  2972. if_line = 1
  2973. # check_line两个1/3段被包含在不同line中
  2974. elif line1[axis] <= line_1_3[0] <= line_1_3[1] <= line1[axis + 2]:
  2975. # check_line另一边的1/4被包含
  2976. for line2 in lines:
  2977. if abs(line1[1 - axis] - limit_axis) <= threshold:
  2978. if line2[axis] <= line_3_4[0] <= line_3_4[1] <= line2[axis + 2]:
  2979. if_line = 1
  2980. break
  2981. elif line1[axis] <= line_2_3[0] <= line_2_3[1] <= line1[axis + 2]:
  2982. # check_line另一边的1/4被包含
  2983. for line2 in lines:
  2984. if abs(line1[1 - axis] - limit_axis) <= threshold:
  2985. if line2[axis] <= line_1_4[0] <= line_1_4[1] <= line2[axis + 2]:
  2986. if_line = 1
  2987. break
  2988. return if_line
  2989. up_down_line = [bbox[0], bbox[2]]
  2990. up_y, down_y = bbox[1], bbox[3]
  2991. left_right_line = [bbox[1], bbox[3]]
  2992. left_x, right_x = bbox[0], bbox[2]
  2993. # 检查bbox四条边是否存在
  2994. if_up = check(up_down_line, rows, up_y, 0)
  2995. if_down = check(up_down_line, rows, down_y, 0)
  2996. if_left = check(left_right_line, cols, left_x, 1)
  2997. if_right = check(left_right_line, cols, right_x, 1)
  2998. # 检查bbox内部除了四条边,是否有其它line在bbox内部
  2999. if_col = 0
  3000. if_row = 0
  3001. if if_up and if_down and if_left and if_right:
  3002. for col in cols:
  3003. if not if_col and left_x + threshold <= col[0] <= right_x - threshold:
  3004. if col[1] <= left_right_line[0] <= left_right_line[1] <= col[3]:
  3005. if_col = 1
  3006. elif left_right_line[0] <= col[1] <= left_right_line[1]:
  3007. if left_right_line[1] - col[1] >= (left_right_line[1] + left_right_line[0]) / 2:
  3008. if_col = 1
  3009. elif left_right_line[0] <= col[3] <= left_right_line[1]:
  3010. if col[3] - left_right_line[0] >= (left_right_line[1] + left_right_line[0]) / 2:
  3011. if_col = 1
  3012. for row in rows:
  3013. if not if_row and up_y + threshold <= row[1] <= down_y - threshold:
  3014. if row[0] <= up_down_line[0] <= up_down_line[1] <= row[2]:
  3015. if_row = 1
  3016. elif up_down_line[0] <= row[0] <= up_down_line[1]:
  3017. if up_down_line[1] - row[0] >= (up_down_line[1] + up_down_line[0]) / 2:
  3018. if_row = 1
  3019. elif up_down_line[0] <= row[2] <= up_down_line[1]:
  3020. if row[2] - up_down_line[0] >= (up_down_line[1] + up_down_line[0]) / 2:
  3021. if_row = 1
  3022. if if_up and if_down and if_left and if_right and not if_col and not if_row:
  3023. return True
  3024. else:
  3025. return False
  3026. # def add_continue_bbox(bboxes):
  3027. # add_bbox_list = []
  3028. # bboxes.sort(key=lambda x: (x[0][0], x[0][1]))
  3029. # last_bbox = bboxes[0]
  3030. # # 先对bbox分区
  3031. # for i in range(1, len(split_y)):
  3032. # y = split_y[i]
  3033. # last_y = split_y[i-1]
  3034. #
  3035. # split_bbox = []
  3036. # for bbox in bboxes:
  3037. # if last_y <= bbox[1][1] <= y:
  3038. # split_bbox.append(bbox)
  3039. # split_bbox.sort
  3040. #
  3041. # for i in range(1, len(bboxes)):
  3042. # bbox = bboxes[i]
  3043. # if last_y <= bbox[1][1] <= y and last_y <= last_bbox[1][1] <= y:
  3044. # if abs(last_bbox[1][1] - bbox[0][1]) <= 2:
  3045. # last_bbox = bbox
  3046. # else:
  3047. # if last_bbox[1][1] > bbox[0][1]:
  3048. # last_bbox = bbox
  3049. # else:
  3050. # add_bbox = [(last_bbox[0][0], last_bbox[1][1]),
  3051. # (last_bbox[1][0], bbox[0][1])]
  3052. # add_bbox_list.append(add_bbox)
  3053. # last_y = y
  3054. #
  3055. # print("add_bbox_list", add_bbox_list)
  3056. # if add_bbox_list:
  3057. # bboxes = [str(x) for x in bboxes + add_bbox_list]
  3058. # bboxes = list(set(bboxes))
  3059. # bboxes = [eval(x) for x in bboxes]
  3060. # bboxes.sort(key=lambda x: (x[0][1], x[0][0]))
  3061. #
  3062. # return bboxes
  3063. def points_to_line(points_lines, axis):
  3064. new_line_list = []
  3065. for line in points_lines:
  3066. average = 0
  3067. _min = _min = line[0][axis]
  3068. _max = line[-1][axis]
  3069. for point in line:
  3070. average += point[1 - axis]
  3071. if point[axis] < _min:
  3072. _min = point[axis]
  3073. if point[axis] > _max:
  3074. _max = point[axis]
  3075. average = int(average / len(line))
  3076. if axis:
  3077. new_line = [average, _min, average, _max]
  3078. else:
  3079. new_line = [_min, average, _max, average]
  3080. new_line_list.append(new_line)
  3081. return new_line_list
  3082. def get_bbox_by_contours(image_np):
  3083. img_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  3084. ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
  3085. # 3.连通域分析
  3086. img_bin, contours, hierarchy = cv2.findContours(img_bin,
  3087. cv2.RETR_LIST,
  3088. cv2.CHAIN_APPROX_SIMPLE)
  3089. # 4.获取最小外接圆 圆心 半径
  3090. center, radius = cv2.minEnclosingTriangle(contours[0])
  3091. center = np.int0(center)
  3092. # 5.绘制最小外接圆
  3093. img_result = image_np.copy()
  3094. cv2.circle(img_result, tuple(center), int(radius), (255, 255, 255), 2)
  3095. # # 读入图片
  3096. # img = image_np
  3097. # cv2.imshow("get_bbox_by_contours ", image_np)
  3098. # # 中值滤波,去噪
  3099. # img = cv2.medianBlur(img, 3)
  3100. # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  3101. # cv2.namedWindow('original', cv2.WINDOW_AUTOSIZE)
  3102. # cv2.imshow('original', gray)
  3103. #
  3104. # # 阈值分割得到二值化图片
  3105. # ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  3106. #
  3107. # # 膨胀操作
  3108. # kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  3109. # bin_clo = cv2.dilate(binary, kernel2, iterations=2)
  3110. #
  3111. # # 连通域分析
  3112. # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(bin_clo, connectivity=8)
  3113. #
  3114. # # 查看各个返回值
  3115. # # 连通域数量
  3116. # print('num_labels = ',num_labels)
  3117. # # 连通域的信息:对应各个轮廓的x、y、width、height和面积
  3118. # print('stats = ',stats)
  3119. # # 连通域的中心点
  3120. # print('centroids = ',centroids)
  3121. # # 每一个像素的标签1、2、3.。。,同一个连通域的标签是一致的
  3122. # print('labels = ',labels)
  3123. #
  3124. # # 不同的连通域赋予不同的颜色
  3125. # output = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)
  3126. # for i in range(1, num_labels):
  3127. #
  3128. # mask = labels == i
  3129. # output[:, :, 0][mask] = np.random.randint(0, 255)
  3130. # output[:, :, 1][mask] = np.random.randint(0, 255)
  3131. # output[:, :, 2][mask] = np.random.randint(0, 255)
  3132. # cv2.imshow('oginal', output)
  3133. # cv2.waitKey()
  3134. # cv2.destroyAllWindows()
  3135. def get_points_col(points, split_y, threshold=5):
  3136. # 坐标点按行分
  3137. row_point_list = []
  3138. row_point = []
  3139. points.sort(key=lambda x: (x[0], x[1]))
  3140. # print("get_points_col points sort", points)
  3141. x = points[0][0]
  3142. for i in range(1, len(split_y)):
  3143. for p in points:
  3144. if p[1] <= split_y[i - 1] or p[1] >= split_y[i]:
  3145. continue
  3146. if x - threshold <= p[0] <= x + threshold:
  3147. row_point.append(p)
  3148. else:
  3149. # print("row_point", row_point)
  3150. row_point.sort(key=lambda x: (x[1], x[0]))
  3151. if row_point:
  3152. row_point_list.append(row_point)
  3153. row_point = []
  3154. x = p[0]
  3155. row_point.append(p)
  3156. if row_point:
  3157. row_point_list.append(row_point)
  3158. return row_point_list
  3159. def get_points_row(points, split_y, threshold=5):
  3160. # 坐标点按列分
  3161. col_point_list = []
  3162. col_point = []
  3163. points.sort(key=lambda x: (x[1], x[0]))
  3164. y = points[0][1]
  3165. for i in range(len(split_y)):
  3166. for p in points:
  3167. if p[1] <= split_y[i - 1] or p[1] >= split_y[i]:
  3168. continue
  3169. if y - threshold <= p[1] <= y + threshold:
  3170. col_point.append(p)
  3171. else:
  3172. col_point.sort(key=lambda x: (x[0], x[1]))
  3173. if col_point:
  3174. col_point_list.append(col_point)
  3175. col_point = []
  3176. y = p[1]
  3177. col_point.append(p)
  3178. if col_point:
  3179. col_point_list.append(col_point)
  3180. return col_point_list
  3181. def get_outline_point(points, split_y):
  3182. # 分割线纵坐标
  3183. # print("get_outline_point split_y", split_y)
  3184. if len(split_y) < 2:
  3185. return []
  3186. outline_2point = []
  3187. points.sort(key=lambda x: (x[1], x[0]))
  3188. for i in range(1, len(split_y)):
  3189. area_points = []
  3190. for point in points:
  3191. if point[1] <= split_y[i - 1] or point[1] >= split_y[i]:
  3192. continue
  3193. area_points.append(point)
  3194. if area_points:
  3195. area_points.sort(key=lambda x: (x[1], x[0]))
  3196. outline_2point.append([area_points[0], area_points[-1]])
  3197. return outline_2point
  3198. # def merge_row(row_lines):
  3199. # for row in row_lines:
  3200. # for row1 in row_lines:
  3201. def get_best_predict_size(image_np):
  3202. sizes = [1280, 1152, 1024, 896, 768, 640, 512, 384, 256, 128]
  3203. min_len = 10000
  3204. best_height = sizes[0]
  3205. for height in sizes:
  3206. if abs(image_np.shape[0] - height) < min_len:
  3207. min_len = abs(image_np.shape[0] - height)
  3208. best_height = height
  3209. min_len = 10000
  3210. best_width = sizes[0]
  3211. for width in sizes:
  3212. if abs(image_np.shape[1] - width) < min_len:
  3213. min_len = abs(image_np.shape[1] - width)
  3214. best_width = width
  3215. return best_height, best_width
  3216. def choose_longer_row(lines):
  3217. new_row = []
  3218. jump_row = []
  3219. for i in range(len(lines)):
  3220. row1 = lines[i]
  3221. jump_flag = 0
  3222. if row1 in jump_row:
  3223. continue
  3224. for j in range(i + 1, len(lines)):
  3225. row2 = lines[j]
  3226. if row2 in jump_row:
  3227. continue
  3228. if row2[1] - 5 <= row1[1] <= row2[1] + 5:
  3229. if row1[0] <= row2[0] and row1[2] >= row2[2]:
  3230. new_row.append(row1)
  3231. jump_row.append(row1)
  3232. jump_row.append(row2)
  3233. jump_flag = 1
  3234. break
  3235. elif row2[0] <= row1[0] and row2[2] >= row1[2]:
  3236. new_row.append(row2)
  3237. jump_row.append(row1)
  3238. jump_row.append(row2)
  3239. jump_flag = 1
  3240. break
  3241. if not jump_flag:
  3242. new_row.append(row1)
  3243. jump_row.append(row1)
  3244. return new_row
  3245. def choose_longer_col(lines):
  3246. new_col = []
  3247. jump_col = []
  3248. for i in range(len(lines)):
  3249. col1 = lines[i]
  3250. jump_flag = 0
  3251. if col1 in jump_col:
  3252. continue
  3253. for j in range(i + 1, len(lines)):
  3254. col2 = lines[j]
  3255. if col2 in jump_col:
  3256. continue
  3257. if col2[0] - 5 <= col1[0] <= col2[0] + 5:
  3258. if col1[1] <= col2[1] and col1[3] >= col2[3]:
  3259. new_col.append(col1)
  3260. jump_col.append(col1)
  3261. jump_col.append(col2)
  3262. jump_flag = 1
  3263. break
  3264. elif col2[1] <= col1[1] and col2[3] >= col1[3]:
  3265. new_col.append(col2)
  3266. jump_col.append(col1)
  3267. jump_col.append(col2)
  3268. jump_flag = 1
  3269. break
  3270. if not jump_flag:
  3271. new_col.append(col1)
  3272. jump_col.append(col1)
  3273. return new_col
  3274. def delete_contain_bbox(bboxes):
  3275. # bbox互相包含,取小的bbox
  3276. delete_bbox = []
  3277. for i in range(len(bboxes)):
  3278. for j in range(i + 1, len(bboxes)):
  3279. bbox1 = bboxes[i]
  3280. bbox2 = bboxes[j]
  3281. # 横坐标相等情况
  3282. if bbox1[0][0] == bbox2[0][0] and bbox1[1][0] == bbox2[1][0]:
  3283. if bbox1[0][1] <= bbox2[0][1] <= bbox2[1][1] <= bbox1[1][1]:
  3284. # print("1", bbox1, bbox2)
  3285. delete_bbox.append(bbox1)
  3286. elif bbox2[0][1] <= bbox1[0][1] <= bbox1[1][1] <= bbox2[1][1]:
  3287. # print("2", bbox1, bbox2)
  3288. delete_bbox.append(bbox2)
  3289. # 纵坐标相等情况
  3290. elif bbox1[0][1] == bbox2[0][1] and bbox1[1][1] == bbox2[1][1]:
  3291. if bbox1[0][0] <= bbox2[0][0] <= bbox2[1][0] <= bbox1[1][0]:
  3292. print("3", bbox1, bbox2)
  3293. delete_bbox.append(bbox1)
  3294. elif bbox2[0][0] <= bbox1[0][0] <= bbox1[1][0] <= bbox2[1][0]:
  3295. print("4", bbox1, bbox2)
  3296. delete_bbox.append(bbox2)
  3297. print("delete_contain_bbox len(bboxes)", len(bboxes))
  3298. print("delete_contain_bbox len(delete_bbox)", len(delete_bbox))
  3299. for bbox in delete_bbox:
  3300. if bbox in bboxes:
  3301. bboxes.remove(bbox)
  3302. print("delete_contain_bbox len(bboxes)", len(bboxes))
  3303. return bboxes
  3304. def fix_4_points(cross_points):
  3305. cross_points.sort(key=lambda x: (x[0], x[1]))
  3306. left_up_p = cross_points[0]
  3307. right_down_p = cross_points[-1]
  3308. cross_points.sort(key=lambda x: (-x[0], x[1]))
  3309. right_up_p = cross_points[0]
  3310. left_down_p = cross_points[-1]
  3311. print('left_up_p', left_up_p, 'left_down_p', left_down_p)
  3312. print('right_up_p', right_up_p, 'right_down_p', right_down_p)
  3313. min_x = min(left_up_p[0], left_down_p[0], right_down_p[0], right_up_p[0])
  3314. max_x = max(left_up_p[0], left_down_p[0], right_down_p[0], right_up_p[0])
  3315. min_y = min(left_up_p[1], left_down_p[1], right_down_p[1], right_up_p[1])
  3316. max_y = max(left_up_p[1], left_down_p[1], right_down_p[1], right_up_p[1])
  3317. if left_up_p[0] != min_x or left_up_p[1] != min_y:
  3318. log('轮廓左上角交点有问题')
  3319. if left_down_p[0] != min_x or left_down_p[1] != max_y:
  3320. log('轮廓左下角交点有问题')
  3321. cross_points.append([min_x, max_y])
  3322. if right_up_p[0] != max_x or right_up_p[1] != min_y:
  3323. log('轮廓右上角交点有问题')
  3324. if right_down_p[0] != max_x or right_down_p[1] != max_y:
  3325. log('轮廓右下角交点有问题')
  3326. return cross_points
  3327. if __name__ == '__main__':
  3328. print()
  3329. path = "C:\\Users\\Administrator\\Downloads\\pred.pk"
  3330. with open(path, "rb") as f:
  3331. pred = pickle.load(f)
  3332. draw_pixel(pred, 0.2, True)
  3333. points2lines(pred, False, 0.5)