table_line.py 125 KB

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