table_line.py 133 KB

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