table_line.py 144 KB

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