table_line.py 151 KB

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