table_line.py 126 KB

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