123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- Created on Thu Sep 9 23:11:51 2020
- table line detect
- @author: chineseocr
- """
- import copy
- import tensorflow as tf
- import keras.backend as K
- from tensorflow.keras.models import Model
- from tensorflow.keras.layers import Input, concatenate, Conv2D, MaxPooling2D, BatchNormalization, UpSampling2D
- from tensorflow.keras.layers import LeakyReLU
- from config import tableModeLinePath
- from utils import letterbox_image, get_table_line, adjust_lines, line_to_line, draw_boxes
- import numpy as np
- import cv2
- import time
- from utils import draw_lines
- def dice_coef(y_true, y_pred, smooth=1e-5):
- y_true_f = K.flatten(y_true)
- y_pred_f = K.flatten(y_pred)
- intersection = K.sum(y_true_f * y_pred_f)
- return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
- def dice_coef_loss():
- def dice_coef_loss_fixed(y_true, y_pred):
- return -dice_coef(y_true, y_pred)
- return dice_coef_loss_fixed
- def focal_loss(gamma=3., alpha=.85):
- def focal_loss_fixed(y_true, y_pred):
- pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
- pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
- 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()))
- return focal_loss_fixed
- def table_net(input_shape=(1152, 896, 3), num_classes=1):
- inputs = Input(shape=input_shape)
- # 512
- use_bias = False
- down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(inputs)
- down0a = BatchNormalization()(down0a)
- down0a = LeakyReLU(alpha=0.1)(down0a)
- down0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(down0a)
- down0a = BatchNormalization()(down0a)
- down0a = LeakyReLU(alpha=0.1)(down0a)
- down0a_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0a)
- # 256
- down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0a_pool)
- down0 = BatchNormalization()(down0)
-
- down0 = LeakyReLU(alpha=0.1)(down0)
- down0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(down0)
- down0 = BatchNormalization()(down0)
- down0 = LeakyReLU(alpha=0.1)(down0)
- down0_pool = MaxPooling2D((2, 2), strides=(2, 2))(down0)
- # 128
- down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down0_pool)
- down1 = BatchNormalization()(down1)
- down1 = LeakyReLU(alpha=0.1)(down1)
- down1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(down1)
- down1 = BatchNormalization()(down1)
- down1 = LeakyReLU(alpha=0.1)(down1)
- down1_pool = MaxPooling2D((2, 2), strides=(2, 2))(down1)
- # 64
- down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down1_pool)
- down2 = BatchNormalization()(down2)
- down2 = LeakyReLU(alpha=0.1)(down2)
- down2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(down2)
- down2 = BatchNormalization()(down2)
- down2 = LeakyReLU(alpha=0.1)(down2)
- down2_pool = MaxPooling2D((2, 2), strides=(2, 2))(down2)
- # 32
- down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down2_pool)
- down3 = BatchNormalization()(down3)
- down3 = LeakyReLU(alpha=0.1)(down3)
- down3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(down3)
- down3 = BatchNormalization()(down3)
- down3 = LeakyReLU(alpha=0.1)(down3)
- down3_pool = MaxPooling2D((2, 2), strides=(2, 2))(down3)
- # 16
- down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down3_pool)
- down4 = BatchNormalization()(down4)
- down4 = LeakyReLU(alpha=0.1)(down4)
- down4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(down4)
- down4 = BatchNormalization()(down4)
- down4 = LeakyReLU(alpha=0.1)(down4)
- down4_pool = MaxPooling2D((2, 2), strides=(2, 2))(down4)
- # 8
- center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(down4_pool)
- center = BatchNormalization()(center)
- center = LeakyReLU(alpha=0.1)(center)
- center = Conv2D(1024, (3, 3), padding='same', use_bias=use_bias)(center)
- center = BatchNormalization()(center)
- center = LeakyReLU(alpha=0.1)(center)
- # center
- up4 = UpSampling2D((2, 2))(center)
- up4 = concatenate([down4, up4], axis=3)
- up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
- up4 = BatchNormalization()(up4)
- up4 = LeakyReLU(alpha=0.1)(up4)
- up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
- up4 = BatchNormalization()(up4)
- up4 = LeakyReLU(alpha=0.1)(up4)
- up4 = Conv2D(512, (3, 3), padding='same', use_bias=use_bias)(up4)
- up4 = BatchNormalization()(up4)
- up4 = LeakyReLU(alpha=0.1)(up4)
- # 16
- up3 = UpSampling2D((2, 2))(up4)
- up3 = concatenate([down3, up3], axis=3)
- up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
- up3 = BatchNormalization()(up3)
- up3 = LeakyReLU(alpha=0.1)(up3)
- up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
- up3 = BatchNormalization()(up3)
- up3 = LeakyReLU(alpha=0.1)(up3)
- up3 = Conv2D(256, (3, 3), padding='same', use_bias=use_bias)(up3)
- up3 = BatchNormalization()(up3)
- up3 = LeakyReLU(alpha=0.1)(up3)
- # 32
- up2 = UpSampling2D((2, 2))(up3)
- up2 = concatenate([down2, up2], axis=3)
- up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
- up2 = BatchNormalization()(up2)
- up2 = LeakyReLU(alpha=0.1)(up2)
- up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
- up2 = BatchNormalization()(up2)
- up2 = LeakyReLU(alpha=0.1)(up2)
- up2 = Conv2D(128, (3, 3), padding='same', use_bias=use_bias)(up2)
- up2 = BatchNormalization()(up2)
- up2 = LeakyReLU(alpha=0.1)(up2)
- # 64
- up1 = UpSampling2D((2, 2))(up2)
- up1 = concatenate([down1, up1], axis=3)
- up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
- up1 = BatchNormalization()(up1)
- up1 = LeakyReLU(alpha=0.1)(up1)
- up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
- up1 = BatchNormalization()(up1)
- up1 = LeakyReLU(alpha=0.1)(up1)
- up1 = Conv2D(64, (3, 3), padding='same', use_bias=use_bias)(up1)
- up1 = BatchNormalization()(up1)
- up1 = LeakyReLU(alpha=0.1)(up1)
- # 128
- up0 = UpSampling2D((2, 2))(up1)
- up0 = concatenate([down0, up0], axis=3)
- up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
- up0 = BatchNormalization()(up0)
- up0 = LeakyReLU(alpha=0.1)(up0)
- up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
- up0 = BatchNormalization()(up0)
- up0 = LeakyReLU(alpha=0.1)(up0)
- up0 = Conv2D(32, (3, 3), padding='same', use_bias=use_bias)(up0)
- up0 = BatchNormalization()(up0)
- up0 = LeakyReLU(alpha=0.1)(up0)
- # 256
- up0a = UpSampling2D((2, 2))(up0)
- up0a = concatenate([down0a, up0a], axis=3)
- up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
- up0a = BatchNormalization()(up0a)
- up0a = LeakyReLU(alpha=0.1)(up0a)
- up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
- up0a = BatchNormalization()(up0a)
- up0a = LeakyReLU(alpha=0.1)(up0a)
- up0a = Conv2D(16, (3, 3), padding='same', use_bias=use_bias)(up0a)
- up0a = BatchNormalization()(up0a)
- up0a = LeakyReLU(alpha=0.1)(up0a)
- # 512
- classify = Conv2D(num_classes, (1, 1), activation='sigmoid')(up0a)
- model = Model(inputs=inputs, outputs=classify)
- return model
- model = table_net((None, None, 3), 2)
- def table_line(img, model, size=(512, 1024), hprob=0.5, vprob=0.5, row=50, col=30, alph=15):
- sizew, sizeh = size
- # [..., ::-1] 最后一维内部反向输出
- # inputBlob, fx, fy = letterbox_image(img[..., ::-1], (sizew, sizeh))
- # pred = model.predict(np.array([np.array(inputBlob)]))
- # pred = model.predict(np.array([np.array(inputBlob)/255.0]))
- img_new = cv2.resize(img, (sizew, sizeh), interpolation=cv2.INTER_AREA)
- pred = model.predict(np.array([img_new]))
- pred = pred[0]
- vpred = pred[..., 1] > vprob # 横线
- hpred = pred[..., 0] > hprob # 竖线
- vpred = vpred.astype(int)
- hpred = hpred.astype(int)
- # print("vpred shape", vpred)
- # print("hpred shape", hpred)
- colboxes = get_table_line(vpred, axis=1, lineW=col)
- rowboxes = get_table_line(hpred, axis=0, lineW=row)
- # if len(rowboxes) > 0:
- # rowboxes = np.array(rowboxes)
- # rowboxes[:, [0, 2]] = rowboxes[:, [0, 2]]/fx
- # rowboxes[:, [1, 3]] = rowboxes[:, [1, 3]]/fy
- # rowboxes = rowboxes.tolist()
- # if len(colboxes) > 0:
- # colboxes = np.array(colboxes)
- # colboxes[:, [0, 2]] = colboxes[:, [0, 2]]/fx
- # colboxes[:, [1, 3]] = colboxes[:, [1, 3]]/fy
- # colboxes = colboxes.tolist()
- nrow = len(rowboxes)
- ncol = len(colboxes)
- for i in range(nrow):
- for j in range(ncol):
- rowboxes[i] = line_to_line(rowboxes[i], colboxes[j], 10)
- colboxes[j] = line_to_line(colboxes[j], rowboxes[i], 10)
- # 删掉贴着边框的line
- temp_list = []
- threshold = 5
- for line in rowboxes:
- if line[1]-0 <= threshold or size[1]-line[1] <= threshold:
- continue
- temp_list.append(line)
- rowboxes = temp_list
- temp_list = []
- for line in colboxes:
- if line[0]-0 <= threshold or size[0]-line[0] <= threshold:
- continue
- temp_list.append(line)
- colboxes = temp_list
- return rowboxes, colboxes, img_new
- def get_outline(points, image_np):
- # 取出x, y的最大值最小值
- x_min = points[0][0]
- x_max = points[-1][0]
- points.sort(key=lambda x: (x[1], x[0]))
- y_min = points[0][1]
- y_max = points[-1][1]
- # 创建空图
- # outline_img = np.zeros(image_size, np.uint8)
- outline_img = np.copy(image_np)
- cv2.rectangle(outline_img, (x_min-5, y_min-5), (x_max+5, y_max+5), (0, 0, 0), 2)
- # cv2.imshow("outline_img", outline_img)
- # cv2.waitKey(0)
- return outline_img
- def get_split_line(points, col_lines, image_np):
- # print("get_split_line", image_np.shape)
- points.sort(key=lambda x: (x[1], x[0]))
- # 遍历y坐标,并判断y坐标与上一个y坐标是否存在连接线
- i = 0
- split_line_y = []
- for point in points:
- # 从已分开的线下面开始判断
- if split_line_y:
- if point[1] <= split_line_y[-1] + 5:
- last_y = point[1]
- continue
- if last_y <= split_line_y[-1] + 5:
- last_y = point[1]
- continue
- if i == 0:
- last_y = point[1]
- i += 1
- continue
- current_line = (last_y, point[1])
- split_flag = 1
- for col in col_lines:
- # 只要找到一条col包含就不是分割线
- if current_line[0] >= col[1]-3 and current_line[1] <= col[3]+3:
- split_flag = 0
- # print("img", img.shape)
- # print("col", col)
- # print("current_line", current_line)
- break
- if split_flag:
- split_line_y.append(current_line[0]+5)
- split_line_y.append(current_line[1]-5)
- last_y = point[1]
- # 加上收尾分割线
- points.sort(key=lambda x: (x[1], x[0]))
- y_min = points[0][1]
- y_max = points[-1][1]
- # print("加上收尾分割线", y_min, y_max)
- if y_min-5 < 0:
- split_line_y.append(0)
- else:
- split_line_y.append(y_min-5)
- if y_max+5 > image_np.shape[0]:
- split_line_y.append(image_np.shape[0])
- else:
- split_line_y.append(y_max+5)
- split_line_y = list(set(split_line_y))
- # 剔除两条相隔太近分割线
- temp_split_line_y = []
- split_line_y.sort(key=lambda x: x)
- last_y = -20
- for y in split_line_y:
- # print(y)
- if y - last_y >= 20:
- # print(y, last_y)
- temp_split_line_y.append(y)
- last_y = y
- split_line_y = temp_split_line_y
- # print("split_line_y", split_line_y)
- # 生成分割线
- split_line = []
- last_y = 0
- for y in split_line_y:
- # if y - last_y <= 15:
- # continue
- split_line.append([(0, y), (image_np.shape[1], y)])
- last_y = y
- split_line.append([(0, 0), (image_np.shape[1], 0)])
- split_line.append([(0, image_np.shape[0]), (image_np.shape[1], image_np.shape[0])])
- split_line.sort(key=lambda x: x[0][1])
- # print("split_line", split_line)
- # 画图画线
- # split_line_img = np.copy(image_np)
- # for y in split_line_y:
- # cv2.line(split_line_img, (0, y), (image_np.shape[1], y), (0, 0, 0), 1)
- # cv2.imshow("split_line_img", split_line_img)
- # cv2.waitKey(0)
- return split_line, split_line_y
- def get_points(row_lines, col_lines, image_size):
- # 创建空图
- row_img = np.zeros(image_size, np.uint8)
- col_img = np.zeros(image_size, np.uint8)
- # 画线
- for row in row_lines:
- cv2.line(row_img, (int(row[0]), int(row[1])), (int(row[2]), int(row[3])), (255, 255, 255), 1)
- for col in col_lines:
- cv2.line(col_img, (int(col[0]), int(col[1])), (int(col[2]), int(col[3])), (255, 255, 255), 1)
- # 求出交点
- point_img = np.bitwise_and(row_img, col_img)
- # cv2.imshow("point_img", np.bitwise_not(point_img))
- # cv2.waitKey(0)
- # 识别黑白图中的白色交叉点,将横纵坐标取出
- ys, xs = np.where(point_img > 0)
- points = []
- for i in range(len(xs)):
- points.append((xs[i], ys[i]))
- points.sort(key=lambda x: (x[0], x[1]))
- return points
- def get_minAreaRect(image):
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- gray = cv2.bitwise_not(gray)
- thresh = cv2.threshold(gray, 0, 255,
- cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
- coords = np.column_stack(np.where(thresh > 0))
- return cv2.minAreaRect(coords)
- def get_contours(image):
- gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
- ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
- contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- cv2.drawContours(image, contours, -1, (0, 0, 255), 3)
- cv2.imshow("get contours", image)
- cv2.waitKey(0)
- def fix_outline(image, row_lines, col_lines, points, split_y):
- # 分割线纵坐标
- # print("len(split_y)", split_y)
- if len(split_y) < 2:
- # split_y = [2000., 2000., 2000., 2000.]
- return [], [], []
- elif len(split_y) == 2:
- split_y = [2000., 2000., 2000., 2000.]
- split_y.sort(key=lambda x: x)
- split_y = split_y[1:-1]
- new_split_y = []
- for i in range(1, len(split_y), 2):
- new_split_y.append(int((split_y[i]+split_y[i-1])/2))
- # print("len(new_split_y)", len(new_split_y))
- # 预测线根据分割线纵坐标分为多个分割区域
- row_lines.sort(key=lambda x: (x[3], x[2]))
- col_lines.sort(key=lambda x: (x[3], x[2]))
- row_count = 0
- col_count = 0
- split_row_list = []
- split_col_list = []
- for y in new_split_y:
- row_lines = row_lines[row_count:]
- col_lines = col_lines[col_count:]
- row_count = 0
- col_count = 0
- for row in row_lines:
- if row[3] <= y:
- row_count += 1
- else:
- split_row_list.append(row_lines[:row_count])
- break
- if row_count == len(row_lines):
- split_row_list.append(row_lines[:row_count])
- break
- for col in col_lines:
- if col[3] <= y:
- col_count += 1
- else:
- split_col_list.append(col_lines[:col_count])
- break
- if col_count == len(col_lines):
- split_col_list.append(col_lines[:col_count])
- break
- if row_count < len(row_lines) - 1:
- row_lines = row_lines[row_count:]
- split_row_list.append(row_lines)
- if col_count < len(col_lines) - 1:
- col_lines = col_lines[col_count:]
- split_col_list.append(col_lines)
- # print("len(split_row_list)", len(split_row_list))
- # print("len(split_col_list)", len(split_col_list))
- # 预测线取上下左右4个边(会有超出表格部分) [(), ()]
- area_row_line = []
- area_col_line = []
- for area in split_row_list:
- if not area:
- continue
- area.sort(key=lambda x: (x[1], x[0]))
- # print(area)
- up_line = area[0]
- bottom_line = area[-1]
- area_row_line.append([up_line, bottom_line])
- for area in split_col_list:
- if not area:
- continue
- area.sort(key=lambda x: x[0])
- left_line = area[0]
- right_line = area[-1]
- area_col_line.append([left_line, right_line])
- # 线交点根据分割线纵坐标分为多个分割区域
- points.sort(key=lambda x: (x[1], x[0]))
- point_count = 0
- split_point_list = []
- for y in new_split_y:
- points = points[point_count:len(points)]
- point_count = 0
- for point in points:
- if point[1] <= y:
- point_count += 1
- else:
- split_point_list.append(points[:point_count])
- break
- if point_count == len(points):
- split_point_list.append(points[:point_count])
- break
- if point_count < len(points) - 1:
- points = points[point_count:len(points)]
- split_point_list.append(points)
- # print("len(split_point_list)", len(split_point_list))
- # 取每个分割区域的4条线(无超出表格部分)
- area_row_line2 = []
- area_col_line2 = []
- for area in split_point_list:
- if not area:
- continue
- area.sort(key=lambda x: (x[0], x[1]))
- left_up = area[0]
- right_bottom = area[-1]
- up_line = [left_up[0], left_up[1], right_bottom[0], left_up[1]]
- bottom_line = [left_up[0], right_bottom[1], right_bottom[0], right_bottom[1]]
- left_line = [left_up[0], left_up[1], left_up[0], right_bottom[1]]
- right_line = [right_bottom[0], left_up[1], right_bottom[0], right_bottom[1]]
- area_row_line2.append([up_line, bottom_line])
- area_col_line2.append([left_line, right_line])
- # 判断超出部分的长度,超出一定长度就补线
- new_row_lines = []
- new_col_lines = []
- longer_row_lines = []
- longer_col_lines = []
- # print(len(area_col_line))
- # print(len(area_col_line2))
- for i in range(len(area_row_line)):
- up_line = area_row_line[i][0]
- up_line2 = area_row_line2[i][0]
- bottom_line = area_row_line[i][1]
- bottom_line2 = area_row_line2[i][1]
- left_line = area_col_line[i][0]
- left_line2 = area_col_line2[i][0]
- right_line = area_col_line[i][1]
- right_line2 = area_col_line2[i][1]
- # 补左右两条竖线超出来的线的row
- # print("left_line2[1] - left_line[1]", left_line2[1] - left_line[1])
- if left_line2[1] - left_line[1] >= 10 and right_line2[1] - right_line[1] >= 10:
- if left_line2[1] - left_line[1] >= right_line2[1] - right_line[1]:
- new_row_lines.append([left_line[0], left_line[1], right_line[0], left_line[1]])
- new_col_y = left_line[1]
- # 补了row,要将其他短的col连到row上
- for col in split_col_list[i]:
- longer_col_lines.append([col[0], new_col_y, col[2], col[3]])
- else:
- new_row_lines.append([left_line[0], right_line[1], right_line[0], right_line[1]])
- new_col_y = right_line[1]
- # 补了row,要将其他短的col连到row上
- for col in split_col_list[i]:
- longer_col_lines.append([col[0], new_col_y, col[2], col[3]])
- # print("left_line[3] - left_line2[3]", left_line[3] - left_line2[3])
- if left_line[3] - left_line2[3] >= 10 and right_line[3] - right_line2[3] >= 10:
- if left_line[3] - left_line2[3] >= right_line[3] - right_line2[3]:
- new_row_lines.append([left_line[2], left_line[3], right_line[2], left_line[3]])
- new_col_y = left_line[3]
- # 补了row,要将其他短的col连到row上
- for col in split_col_list[i]:
- longer_col_lines.append([col[0], col[1], col[2], new_col_y])
- else:
- new_row_lines.append([left_line[2], right_line[3], right_line[2], right_line[3]])
- new_col_y = right_line[3]
- # 补了row,要将其他短的col连到row上
- for col in split_col_list[i]:
- longer_col_lines.append([col[0], col[1], col[2], new_col_y])
- # 补上下两条横线超出来的线的col
- if up_line2[0] - up_line[0] >= 10 and bottom_line2[0] - bottom_line[0] >= 10:
- if up_line2[0] - up_line[0] >= bottom_line2[0] - bottom_line[0]:
- new_col_lines.append([up_line[0], up_line[1], up_line[0], bottom_line[1]])
- new_row_x = up_line[0]
- # 补了col,要将其他短的row连到col上
- for row in split_row_list[i]:
- longer_row_lines.append([new_row_x, row[1], row[2], row[3]])
- # new_row_lines.append([bottom_line[0], up_line[1], bottom_line[2], bottom_line[3]])
- else:
- new_col_lines.append([bottom_line[0], up_line[1], bottom_line[0], bottom_line[1]])
- new_row_x = bottom_line[0]
- # 补了col,要将其他短的row连到col上
- for row in split_row_list[i]:
- longer_row_lines.append([new_row_x, row[1], row[2], row[3]])
- # new_row_lines.append([bottom_line[0], up_line[1], up_line[2], up_line[3]])
- if up_line[2] - up_line2[2] >= 10 and bottom_line[2] - bottom_line2[2] >= 10:
- if up_line[2] - up_line2[2] >= bottom_line[2] - bottom_line2[2]:
- new_col_lines.append([up_line[2], up_line[3], up_line[2], bottom_line[3]])
- new_row_x = up_line[2]
- # 补了col,要将其他短的row连到col上
- for row in split_row_list[i]:
- longer_row_lines.append([row[0], row[1], new_row_x, row[3]])
- else:
- new_col_lines.append([bottom_line[2], up_line[3], bottom_line[2], bottom_line[3]])
- new_row_x = bottom_line[2]
- # 补了col,要将其他短的row连到col上
- for row in split_row_list[i]:
- longer_row_lines.append([row[0], row[1], new_row_x, row[3]])
- # 删除表格内部的补线
- # temp_list = []
- # for row in new_row_lines:
- # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
- # continue
- # temp_list.append(row)
- # print("fix_outline", new_row_lines)
- # new_row_lines = temp_list
- # print("fix_outline", new_row_lines)
- # temp_list = []
- # for col in new_col_lines:
- # if left_line[0]-5 <= col[0] <= right_line[0]+5:
- # continue
- # temp_list.append(col)
- #
- # new_col_lines = temp_list
- # print("fix_outline", new_col_lines)
- # print("fix_outline", new_row_lines)
- # 删除重复包含的补线
- # temp_list = []
- # for row in new_row_lines:
- # if up_line[1]-5 <= row[1] <= bottom_line[1]+5:
- # continue
- # temp_list.append(row)
- # new_row_lines = temp_list
- # 展示上下左右边框线
- # for i in range(len(area_row_line)):
- # print("row1", area_row_line[i])
- # print("row2", area_row_line2[i])
- # print("col1", area_col_line[i])
- # print("col2", area_col_line2[i])
- # cv2.line(image, (int(area_row_line[i][0][0]), int(area_row_line[i][0][1])),
- # (int(area_row_line[i][0][2]), int(area_row_line[i][0][3])), (0, 255, 0), 2)
- # cv2.line(image, (int(area_row_line2[i][1][0]), int(area_row_line2[i][1][1])),
- # (int(area_row_line2[i][1][2]), int(area_row_line2[i][1][3])), (0, 0, 255), 2)
- # cv2.imshow("fix_outline", image)
- # cv2.waitKey(0)
- return new_row_lines, new_col_lines, longer_row_lines, longer_col_lines
- def delete_close_points(point_list, row_point_list, col_point_list, threshold=10):
- new_point_list = []
- delete_point_list = []
- point_list.sort(key=lambda x: (x[1], x[0]))
- for i in range(len(point_list)):
- point1 = point_list[i]
- if point1 in delete_point_list:
- continue
- if i == len(point_list) - 1:
- new_point_list.append(point1)
- break
- point2 = point_list[i+1]
- # 判断坐标
- if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
- new_point_list.append(point1)
- else:
- # 看两个点上的相同坐标点哪个多,就保留哪个
- count1 = 0
- count2 = 0
- for col in col_point_list:
- if point1[0] == col[0][0]:
- count1 += len(col)
- elif point2[0] == col[0][0]:
- count2 += len(col)
- if count1 >= count2:
- new_point_list.append(point1)
- delete_point_list.append(point2)
- else:
- new_point_list.append(point2)
- delete_point_list.append(point1)
- point_list = new_point_list
- new_point_list = []
- delete_point_list = []
- point_list.sort(key=lambda x: (x[0], x[1]))
- for i in range(len(point_list)):
- point1 = point_list[i]
- if point1 in delete_point_list:
- continue
- if i == len(point_list) - 1:
- new_point_list.append(point1)
- break
- point2 = point_list[i+1]
- # 判断坐标
- if abs(point1[0] - point2[0]) > threshold or abs(point1[1] - point2[1]) > threshold:
- new_point_list.append(point1)
- else:
- count1 = 0
- count2 = 0
- for row in row_point_list:
- if point1[0] == row[0][0]:
- count1 += len(row)
- elif point2[0] == row[0][0]:
- count2 += len(row)
- if count1 >= count2:
- new_point_list.append(point1)
- delete_point_list.append(point2)
- else:
- new_point_list.append(point2)
- delete_point_list.append(point1)
- return new_point_list
- def get_bbox2(image_np, points):
- # # 坐标点按行分
- # row_point_list = []
- # row_point = []
- # points.sort(key=lambda x: (x[0], x[1]))
- # for p in points:
- # if len(row_point) == 0:
- # x = p[0]
- # if x-5 <= p[0] <= x+5:
- # row_point.append(p)
- # else:
- # row_point_list.append(row_point)
- # row_point = []
- # # 坐标点按列分
- # col_point_list = []
- # col_point = []
- # points.sort(key=lambda x: (x[1], x[0]))
- # for p in points:
- # if len(col_point) == 0:
- # y = p[1]
- # if y-5 <= p[1] <= y+5:
- # col_point.append(p)
- # else:
- # col_point_list.append(col_point)
- # col_point = []
- row_point_list = get_points_row(points)
- col_point_list = get_points_col(points)
- print("len(points)", len(points))
- for point in points:
- cv2.circle(image_np, point, 1, (0, 255, 0), 1)
- cv2.imshow("points_deleted", image_np)
- points = delete_close_points(points, row_point_list, col_point_list)
- print("len(points)", len(points))
- for point in points:
- cv2.circle(image_np, point, 1, (255, 0, 0), 3)
- cv2.imshow("points_deleted", image_np)
- cv2.waitKey(0)
- row_point_list = get_points_row(points, 5)
- col_point_list = get_points_col(points, 5)
- print("len(row_point_list)", len(row_point_list))
- for row in row_point_list:
- print("row", len(row))
- print("col_point_list", len(col_point_list))
- for col in col_point_list:
- print("col", len(col))
- bbox = []
- for i in range(len(row_point_list)):
- if i == len(row_point_list) - 1:
- break
- # 遍历每个row的point,找到其所在列的下一个点和所在行的下一个点
- current_row = row_point_list[i]
- for j in range(len(current_row)):
- current_point = current_row[j]
- if j == len(current_row) - 1:
- break
- next_row_point = current_row[j+1]
- # 找出当前点所在的col,得到该列下一个point
- current_col = col_point_list[j]
- for k in range(len(current_col)):
- if current_col[k][1] > current_point[1] + 10:
- next_col_point = current_col[k]
- break
- next_row = row_point_list[k]
- for k in range(len(next_row)):
- if next_row[k][0] >= next_row_point[0] + 5:
- next_point = next_row[k]
- break
- # 得到bbox
- bbox.append([(current_point[0], current_point[1]), (next_point[0], next_point[1])])
- # bbox = []
- # for p in points:
- # # print("p", p)
- # p_row = []
- # p_col = []
- # for row in row_point_list:
- # if p[0] == row[0][0]:
- # for p1 in row:
- # if abs(p[1]-p1[1]) <= 5:
- # continue
- # p_row.append([p1, abs(p[1]-p1[1])])
- # p_row.sort(key=lambda x: x[1])
- # for col in col_point_list:
- # if p[1] == col[0][1]:
- # for p2 in col:
- # if abs(p[0]-p2[0]) <= 5:
- # continue
- # p_col.append([p2, abs(p[0]-p2[0])])
- # p_col.sort(key=lambda x: x[1])
- # if len(p_row) == 0 or len(p_col) == 0:
- # continue
- # break_flag = 0
- # for i in range(len(p_row)):
- # for j in range(len(p_col)):
- # # print(p_row[i][0])
- # # print(p_col[j][0])
- # another_point = (p_col[j][0][0], p_row[i][0][1])
- # # print("another_point", another_point)
- # if abs(p[0]-another_point[0]) <= 5 or abs(p[1]-another_point[1]) <= 5:
- # continue
- # if p[0] >= another_point[0] or p[1] >= another_point[1]:
- # continue
- # if another_point in points:
- # box = [p, another_point]
- # box.sort(key=lambda x: x[0])
- # if box not in bbox:
- # bbox.append(box)
- # break_flag = 1
- # break
- # if break_flag:
- # break
- #
- # # delete duplicate
- # delete_bbox = []
- # for i in range(len(bbox)):
- # for j in range(i+1, len(bbox)):
- # if bbox[i][0] == bbox[j][0]:
- # if bbox[i][1][0] - bbox[j][1][0] <= 3 \
- # and bbox[i][1][1] - bbox[j][1][1] <= 3:
- # delete_bbox.append(bbox[j])
- # if bbox[i][1] == bbox[j][1]:
- # if bbox[i][0][0] - bbox[j][0][0] <= 3 \
- # and bbox[i][0][1] - bbox[j][0][1] <= 3:
- # delete_bbox.append(bbox[j])
- # # delete too small area
- # # for box in bbox:
- # # if box[1][0] - box[0][0] <=
- # for d_box in delete_bbox:
- # if d_box in bbox:
- # bbox.remove(d_box)
- # print bbox
- bbox.sort(key=lambda x: (x[0][0], x[0][1], x[1][0], x[1][1]))
- # origin bbox
- # origin_bbox = []
- # for box in bbox:
- # origin_bbox.append([(box[0][0], box[0][1] - 40), (box[1][0], box[1][1] - 40)])
- # for box in origin_bbox:
- # cv2.rectangle(origin_image, box[0], box[1], (0, 0, 255), 2, 8)
- # cv2.imshow('AlanWang', origin_image)
- # cv2.waitKey(0)
- for box in bbox:
- cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
- cv2.imshow('bboxes', image_np)
- cv2.waitKey(0)
- # for point in points:
- # print(point)
- # cv2.circle(image_np, point, 1, (0, 0, 255), 3)
- # cv2.imshow('points', image_np)
- # cv2.waitKey(0)
- return bbox
- def get_bbox1(image_np, points, split_y):
- # 分割线纵坐标
- # print("split_y", split_y)
- if len(split_y) < 2:
- return []
- # 计算行列,剔除相近交点
- row_point_list = get_points_row(points)
- col_point_list = get_points_col(points)
- print("len(row_point_list)", row_point_list)
- print("len(col_point_list)", len(col_point_list))
- # for point in points:
- # cv2.circle(image_np, point, 1, (0, 255, 0), 1)
- # cv2.imshow("points", image_np)
- points = delete_close_points(points, row_point_list, col_point_list)
- # print("len(points)", len(points))
- # for point in points:
- # cv2.circle(image_np, point, 1, (255, 0, 0), 3)
- # cv2.imshow("points_deleted", image_np)
- # cv2.waitKey(0)
- # 获取bbox
- bbox = []
- # 每个点获取与其x最相近和y最相近的点
- for i in range(1, len(split_y)):
- for point1 in points:
- if point1[1] <= split_y[i-1] or point1[1] >= split_y[i]:
- continue
- distance_x = 10000
- distance_y = 10000
- x = 0
- y = 0
- threshold = 10
- for point2 in points:
- if point2[1] <= split_y[i-1] or point2[1] >= split_y[i]:
- continue
- # 最近 x y
- if 2 < point2[0] - point1[0] < distance_x and point2[1] - point1[1] <= threshold:
- distance_x = point2[0] - point1[0]
- x = point2[0]
- if 2 < point2[1] - point1[1] < distance_y and point2[0] - point1[0] <= threshold:
- distance_y = point2[1] - point1[1]
- y = point2[1]
- if not x or not y:
- continue
- bbox.append([(point1[0], point1[1]), (x, y)])
- # 删除包含关系bbox
- temp_list = []
- for i in range(len(bbox)):
- box1 = bbox[i]
- for j in range(len(bbox)):
- if i == j:
- continue
- box2 = bbox[j]
- contain_flag = 0
- if box2[0][0] <= box1[0][0] <= box1[1][0] <= box2[1][0] and \
- box2[0][1] <= box1[0][1] <= box1[1][1] <= box2[1][1]:
- contain_flag = 1
- break
- temp_list.append(box1)
- bbox = temp_list
- # 展示
- for box in bbox:
- # print(box[0], box[1])
- # if abs(box[0][1] - box[1][1]) > abs(box[0][0] - box[1][0]):
- # continue
- cv2.rectangle(image_np, box[0], box[1], (0, 0, 255), 2, 8)
- cv2.imshow('bboxes', image_np)
- cv2.waitKey(0)
- return bbox
- def get_bbox0(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
- # 分割线纵坐标
- if len(split_y) < 2:
- return []
- # 计算行列,剔除相近交点
- # row_point_list = get_points_row(points)
- # col_point_list = get_points_col(points)
- # points = delete_close_points(points, row_point_list, col_point_list)
- # row_point_list = get_points_row(points)
- # col_point_list = get_points_col(points)
- # 获取bbox
- bbox = []
- # print("get_bbox split_y", split_y)
- # 每个点获取与其x最相近和y最相近的点
- for i in range(1, len(split_y)):
- # 循环每行
- for row in row_point_list:
- row.sort(key=lambda x: (x[0], x[1]))
- # 行不在该区域跳过
- if row[0][1] <= split_y[i-1] or row[0][1] >= split_y[i]:
- continue
- # 循环行中的点
- for j in range(len(row)):
- if j == len(row) - 1:
- break
- current_point = row[j]
- next_point_in_row = row[j+1]
- # 查询下个点所在列
- next_col = []
- for col in col_point_list:
- col.sort(key=lambda x: (x[1], x[0]))
- # 列不在该区域跳过
- if col[0][1] <= split_y[i-1] or col[-1][1] >= split_y[i]:
- continue
- if col[0][0]-3 <= next_point_in_row[0] <= col[0][0]+3:
- next_col = col
- break
- # 循环匹配当前点和下一列点
- for point1 in next_col:
- # 同一行的就跳过
- if current_point[1]-3 <= point1[1] <= current_point[1]+3:
- continue
- if point1[1] <= current_point[1]-3:
- continue
- # 候选bbox
- candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
- # 判断该bbox是否存在,线条包含关系
- contain_flag1 = 0
- contain_flag2 = 0
- for row1 in row_lines:
- # 行不在该区域跳过
- if row1[1] <= split_y[i-1] or row1[1] >= split_y[i]:
- continue
- # bbox上边框 y一样
- if not contain_flag1:
- if row1[1]-3 <= candidate_bbox[1] <= row1[1]+3:
- # candidate的x1,x2需被包含在row线中
- if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
- contain_flag1 = 1
- # bbox下边框 y一样
- if not contain_flag2:
- if row1[1]-3 <= candidate_bbox[3] <= row1[1]+3:
- # candidate的x1,x2需被包含在row线中
- if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
- contain_flag2 = 1
- # 找到了该bbox,并且是存在的
- if contain_flag1 and contain_flag2:
- bbox.append([(candidate_bbox[0], candidate_bbox[1]),
- (candidate_bbox[2], candidate_bbox[3])])
- break
- return bbox
- def get_bbox(image_np, row_point_list, col_point_list, split_y, row_lines, col_lines):
- # 分割线纵坐标
- if len(split_y) < 2:
- return []
- # 获取bbox
- bbox = []
- # 每个点获取与其x最相近和y最相近的点
- for i in range(1, len(split_y)):
- # 循环每行
- for row in row_point_list:
- row.sort(key=lambda x: (x[0], x[1]))
- # 行不在该区域跳过
- if row[0][1] <= split_y[i-1] or row[0][1] >= split_y[i]:
- continue
- # 循环行中的点
- for j in range(len(row)):
- if j == len(row) - 1:
- break
- current_point = row[j]
- next_point_in_row_list = row[j+1:]
- # 循环这一行的下一个点
- for next_point_in_row in next_point_in_row_list:
- # 是否在这一行点找到,找不到就这一行的下个点
- not_found = 1
- # 查询下个点所在列
- next_col = []
- for col in col_point_list:
- col.sort(key=lambda x: (x[1], x[0]))
- # 列不在该区域跳过
- if col[0][1] <= split_y[i-1] or col[-1][1] >= split_y[i]:
- continue
- if col[0][0]-3 <= next_point_in_row[0] <= col[0][0]+3:
- next_col = col
- break
- # 循环匹配当前点和下一列点
- for point1 in next_col:
- # 同一行的就跳过
- if current_point[1]-3 <= point1[1] <= current_point[1]+3:
- continue
- if point1[1] <= current_point[1]-3:
- continue
- # 候选bbox
- candidate_bbox = [current_point[0], current_point[1], point1[0], point1[1]]
- # 判断该bbox是否存在,判断bbox的上下两条边是否有包含在row中
- contain_flag1 = 0
- contain_flag2 = 0
- for row1 in row_lines:
- # 行不在该区域跳过
- if row1[1] <= split_y[i-1] or row1[1] >= split_y[i]:
- continue
- # bbox上边框 y一样
- if not contain_flag1:
- if row1[1]-3 <= candidate_bbox[1] <= row1[1]+3:
- # candidate的x1,x2需被包含在row线中
- if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
- contain_flag1 = 1
- # bbox下边框 y一样
- if not contain_flag2:
- if row1[1]-3 <= candidate_bbox[3] <= row1[1]+3:
- # candidate的x1,x2需被包含在row线中
- if row1[0]-3 <= candidate_bbox[0] <= candidate_bbox[2] <= row1[2]+3:
- contain_flag2 = 1
- # 判断该bbox是否存在,判断bbox的左右两条边是否有包含在col中
- contain_flag3 = 0
- contain_flag4 = 0
- for col1 in col_lines:
- # 列不在该区域跳过
- if col1[1] <= split_y[i-1] or col1[3] >= split_y[i]:
- continue
- # bbox左边线 x一样
- if not contain_flag3:
- if col1[0]-3 <= candidate_bbox[0] <= col1[0]+3:
- # candidate的y1,y2需被包含在col线中
- if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
- contain_flag3 = 1
- # bbox右边框 x一样
- if not contain_flag4:
- if col1[0]-3 <= candidate_bbox[2] <= col1[0]+3:
- # candidate的y1,y2需被包含在col线中
- if col1[1]-3 <= candidate_bbox[1] <= candidate_bbox[3] <= col1[3]+3:
- contain_flag4 = 1
- # 找到了该bbox,并且是存在的
- if contain_flag1 and contain_flag2 and contain_flag3 and contain_flag4:
- bbox.append([(candidate_bbox[0], candidate_bbox[1]),
- (candidate_bbox[2], candidate_bbox[3])])
- not_found = 0
- break
- if not not_found:
- break
- return bbox
- def get_bbox_by_contours(image_np):
- img_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
- ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
- # 3.连通域分析
- img_bin, contours, hierarchy = cv2.findContours(img_bin,
- cv2.RETR_LIST,
- cv2.CHAIN_APPROX_SIMPLE)
- # 4.获取最小外接圆 圆心 半径
- center, radius = cv2.minEnclosingTriangle(contours[0])
- center = np.int0(center)
- # 5.绘制最小外接圆
- img_result = image_np.copy()
- cv2.circle(img_result, tuple(center), int(radius), (255, 255, 255), 2)
- # # 读入图片
- # img = image_np
- # cv2.imshow("get_bbox_by_contours ", image_np)
- # # 中值滤波,去噪
- # img = cv2.medianBlur(img, 3)
- # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
- # cv2.namedWindow('original', cv2.WINDOW_AUTOSIZE)
- # cv2.imshow('original', gray)
- #
- # # 阈值分割得到二值化图片
- # ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
- #
- # # 膨胀操作
- # kernel2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
- # bin_clo = cv2.dilate(binary, kernel2, iterations=2)
- #
- # # 连通域分析
- # num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(bin_clo, connectivity=8)
- #
- # # 查看各个返回值
- # # 连通域数量
- # print('num_labels = ',num_labels)
- # # 连通域的信息:对应各个轮廓的x、y、width、height和面积
- # print('stats = ',stats)
- # # 连通域的中心点
- # print('centroids = ',centroids)
- # # 每一个像素的标签1、2、3.。。,同一个连通域的标签是一致的
- # print('labels = ',labels)
- #
- # # 不同的连通域赋予不同的颜色
- # output = np.zeros((img.shape[0], img.shape[1], 3), np.uint8)
- # for i in range(1, num_labels):
- #
- # mask = labels == i
- # output[:, :, 0][mask] = np.random.randint(0, 255)
- # output[:, :, 1][mask] = np.random.randint(0, 255)
- # output[:, :, 2][mask] = np.random.randint(0, 255)
- # cv2.imshow('oginal', output)
- # cv2.waitKey()
- # cv2.destroyAllWindows()
- def get_points_col(points, split_y, threshold=5):
- # 坐标点按行分
- row_point_list = []
- row_point = []
- points.sort(key=lambda x: (x[0], x[1]))
- x = points[0][0]
- for i in range(1, len(split_y)):
- for p in points:
- if p[1] <= split_y[i-1] or p[1] >= split_y[i]:
- continue
- if x-threshold <= p[0] <= x+threshold:
- row_point.append(p)
- else:
- row_point.sort(key=lambda x: (x[1], x[0]))
- if row_point:
- row_point_list.append(row_point)
- row_point = []
- x = p[0]
- row_point.append(p)
- if row_point:
- row_point_list.append(row_point)
- return row_point_list
- def get_points_row(points, split_y, threshold=5):
- # 坐标点按列分
- col_point_list = []
- col_point = []
- points.sort(key=lambda x: (x[1], x[0]))
- y = points[0][1]
- for i in range(len(split_y)):
- for p in points:
- if p[1] <= split_y[i-1] or p[1] >= split_y[i]:
- continue
- if y-threshold <= p[1] <= y+threshold:
- col_point.append(p)
- else:
- col_point.sort(key=lambda x: (x[0], x[1]))
- if col_point:
- col_point_list.append(col_point)
- col_point = []
- y = p[1]
- col_point.append(p)
- if col_point:
- col_point_list.append(col_point)
- return col_point_list
- def get_outline_point(points, split_y):
- # 分割线纵坐标
- # print("get_outline_point split_y", split_y)
- if len(split_y) < 2:
- return []
- outline_2point = []
- points.sort(key=lambda x: (x[1], x[0]))
- for i in range(1, len(split_y)):
- area_points = []
- for point in points:
- if point[1] <= split_y[i-1] or point[1] >= split_y[i]:
- continue
- area_points.append(point)
- if area_points:
- area_points.sort(key=lambda x: (x[1], x[0]))
- outline_2point.append([area_points[0], area_points[-1]])
- return outline_2point
- # def merge_row(row_lines):
- # for row in row_lines:
- # for row1 in row_lines:
- def get_best_predict_size(image_np):
- sizes = [1280, 1152, 1024, 896, 768, 640, 512, 384, 256, 128]
- min_len = 10000
- best_height = sizes[0]
- for height in sizes:
- if abs(image_np.shape[0] - height) < min_len:
- min_len = abs(image_np.shape[0] - height)
- best_height = height
- min_len = 10000
- best_width = sizes[0]
- for width in sizes:
- if abs(image_np.shape[1] - width) < min_len:
- min_len = abs(image_np.shape[1] - width)
- best_width = width
- return best_height, best_width
- def choose_longer_row(lines):
- new_row = []
- jump_row = []
- for i in range(len(lines)):
- row1 = lines[i]
- jump_flag = 0
- if row1 in jump_row:
- continue
- for j in range(i+1, len(lines)):
- row2 = lines[j]
- if row2 in jump_row:
- continue
- if row2[1]-5 <= row1[1] <= row2[1]+5:
- if row1[0] <= row2[0] and row1[2] >= row2[2]:
- new_row.append(row1)
- jump_row.append(row1)
- jump_row.append(row2)
- jump_flag = 1
- break
- elif row2[0] <= row1[0] and row2[2] >= row1[2]:
- new_row.append(row2)
- jump_row.append(row1)
- jump_row.append(row2)
- jump_flag = 1
- break
- if not jump_flag:
- new_row.append(row1)
- jump_row.append(row1)
- return new_row
- def choose_longer_col(lines):
- new_col = []
- jump_col = []
- for i in range(len(lines)):
- col1 = lines[i]
- jump_flag = 0
- if col1 in jump_col:
- continue
- for j in range(i+1, len(lines)):
- col2 = lines[j]
- if col2 in jump_col:
- continue
- if col2[0]-5 <= col1[0] <= col2[0]+5:
- if col1[1] <= col2[1] and col1[3] >= col2[3]:
- new_col.append(col1)
- jump_col.append(col1)
- jump_col.append(col2)
- jump_flag = 1
- break
- elif col2[1] <= col1[1] and col2[3] >= col1[3]:
- new_col.append(col2)
- jump_col.append(col1)
- jump_col.append(col2)
- jump_flag = 1
- break
- if not jump_flag:
- new_col.append(col1)
- jump_col.append(col1)
- return new_col
- if __name__ == '__main__':
- # p = "开标记录表3_page_0.png"
- # p = "train_data/label_1.jpg"
- # p = "train_463.jpg"
- p = "8.png"
- # p = "无边框3.jpg"
- # p = "part1.png"
- # p = "D:\\Project\\format_conversion\\appendix_test\\temp\\00e959a0bc9011ebaf5a00163e0ae709" + \
- # "\\00e95f7cbc9011ebaf5a00163e0ae709_pdf_page0.png"
- # p = "D:\\Project\\format_conversion\\appendix_test\\temp\\00fb3e52bc7e11eb836000163e0ae709" + \
- # "\\00fb43acbc7e11eb836000163e0ae709.png"
- # p = "table.jpg"
- # p = "data_process/create_data/0.jpg"
- img = cv2.imread(p)
- t = time.time()
- model.load_weights(tableModeLinePath)
- best_h, best_w = get_best_predict_size(img)
- print(img.shape)
- print((best_h, best_w))
- # row_boxes, col_boxes = table_line(img[..., ::-1], model, size=(512, 1024), hprob=0.5, vprob=0.5)
- # row_boxes, col_boxes, img = table_line(img[..., ::-1], model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
- row_boxes, col_boxes, img = table_line(img, model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
- # 创建空图
- test_img = np.zeros((img.shape), np.uint8)
- test_img.fill(255)
- for box in row_boxes+col_boxes:
- cv2.line(test_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 0), 1)
- cv2.imshow("test_image", test_img)
- cv2.waitKey(0)
- cv2.imwrite("temp.jpg", test_img)
- # 计算交点、分割线
- crossover_points = get_points(row_boxes, col_boxes, (img.shape[0], img.shape[1]))
- print("len(col_boxes)", len(col_boxes))
- split_lines, split_y = get_split_line(crossover_points, col_boxes, img)
- print("split_y", split_y)
- # for point in crossover_points:
- # cv2.circle(test_img, point, 1, (0, 255, 0), 3)
- # cv2.imshow("point image1", test_img)
- # cv2.waitKey(0)
- # 计算行列,剔除相近交点
- row_point_list = get_points_row(crossover_points, split_y, 0)
- col_point_list = get_points_col(crossover_points, split_y, 0)
- print("1", len(crossover_points), len(row_point_list), len(col_point_list))
- crossover_points = delete_close_points(crossover_points, row_point_list, col_point_list)
- row_point_list = get_points_row(crossover_points, split_y)
- col_point_list = get_points_col(crossover_points, split_y)
- print("2", len(crossover_points), len(row_point_list), len(col_point_list))
- for point in crossover_points:
- cv2.circle(test_img, point, 1, (0, 0, 255), 3)
- cv2.imshow("point image1", test_img)
- cv2.waitKey(0)
- print("len(row_boxes)", len(row_boxes))
- print("len(col_boxes)", len(col_boxes))
- # 修复边框
- new_row_boxes, new_col_boxes, long_row_boxes, long_col_boxes = \
- fix_outline(img, row_boxes, col_boxes, crossover_points, split_y)
- if new_row_boxes or new_col_boxes:
- if long_row_boxes:
- print("long_row_boxes", long_row_boxes)
- row_boxes = long_row_boxes
- if long_col_boxes:
- print("long_col_boxes", long_col_boxes)
- col_boxes = long_col_boxes
- if new_row_boxes:
- row_boxes += new_row_boxes
- if new_col_boxes:
- col_boxes += new_col_boxes
- # row_boxes += new_row_boxes
- # col_boxes += new_col_boxes
- # row_boxes = choose_longer_row(row_boxes)
- # col_boxes = choose_longer_col(col_boxes)
- # 创建空图
- test_img = np.zeros((img.shape), np.uint8)
- test_img.fill(255)
- for box in row_boxes+col_boxes:
- cv2.line(test_img, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 0), 1)
- cv2.imshow("test_image2", test_img)
- cv2.waitKey(0)
- # 展示补线
- for row in new_row_boxes:
- cv2.line(test_img, (int(row[0]), int(row[1])),
- (int(row[2]), int(row[3])), (0, 0, 255), 1)
- for col in new_col_boxes:
- cv2.line(test_img, (int(col[0]), int(col[1])),
- (int(col[2]), int(col[3])), (0, 0, 255), 1)
- cv2.imshow("fix_outline", test_img)
- cv2.waitKey(0)
- cv2.imwrite("temp.jpg", test_img)
- # 修复边框后重新计算交点、分割线
- print("crossover_points", len(crossover_points))
- crossover_points = get_points(row_boxes, col_boxes, (img.shape[0], img.shape[1]))
- print("crossover_points new", len(crossover_points))
- split_lines, split_y = get_split_line(crossover_points, col_boxes, img)
- # 计算行列,剔除相近交点
- row_point_list = get_points_row(crossover_points, split_y, 0)
- col_point_list = get_points_col(crossover_points, split_y, 0)
- print(len(crossover_points), len(row_point_list), len(col_point_list))
- crossover_points = delete_close_points(crossover_points, row_point_list, col_point_list)
- print(len(crossover_points), len(row_point_list), len(col_point_list))
- row_point_list = get_points_row(crossover_points, split_y)
- col_point_list = get_points_col(crossover_points, split_y)
- for point in crossover_points:
- cv2.circle(test_img, point, 1, (0, 255, 0), 3)
- cv2.imshow("point image2", test_img)
- cv2.waitKey(0)
- # 获取每个表格的左上右下两个点
- outline_point = get_outline_point(crossover_points, split_y)
- # print(outline_point)
- for outline in outline_point:
- cv2.circle(test_img, outline[0], 1, (255, 0, 0), 5)
- cv2.circle(test_img, outline[1], 1, (255, 0, 0), 5)
- cv2.imshow("outline point", test_img)
- cv2.waitKey(0)
- # 获取bbox
- # get_bbox(img, crossover_points, split_y)
- # for point in crossover_points:
- # cv2.circle(test_img, point, 1, (0, 255, 0), 3)
- # cv2.imshow("point image3", test_img)
- # cv2.waitKey(0)
- # split_y = []
- # for outline in outline_point:
- # split_y.extend([outline[0][1]-5, outline[1][1]+5])
- print("len(row_boxes)", len(row_boxes))
- print("len(col_boxes)", len(col_boxes))
- bboxes = get_bbox(img, row_point_list, col_point_list, split_y, row_boxes, col_boxes)
- # 展示
- for box in bboxes:
- # print(box[0], box[1])
- # if abs(box[0][1] - box[1][1]) > abs(box[0][0] - box[1][0]):
- # continue
- cv2.rectangle(test_img, box[0], box[1], (0, 0, 255), 2, 8)
- cv2.imshow('bboxes', test_img)
- cv2.waitKey(0)
- # img = draw_lines(img, row_boxes+col_boxes, color=(255, 0, 0), lineW=2)
- # img = draw_boxes(img, rowboxes+colboxes, color=(0, 0, 255))
- print(time.time()-t, len(row_boxes), len(col_boxes))
- # cv2.imwrite('temp.jpg', test_img)
- # cv2.imshow('main', img)
- # cv2.waitKey(0)
|