table_line.py 125 KB

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