table_line.py 145 KB

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