table_line.py 101 KB

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