table_line.py 144 KB

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