如何在图像opencv中的表格中添加水平线

问题描述 投票:0回答:1

我想在下图中添加水平线input image

结果输出应该是这样的: output

任何关于如何解决这个问题的方法,即使存在没有水平线的差异图像。

我尝试过使用下面的方法,但我没有得到任何水平线

import cv2
import numpy as np

# read image
img = cv2.imread("table.png")

# convert to grayscale 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# invert
gray_inv = 255 - gray

# threshold
gray_inv[gray_inv!=255] = 0

# get bounding box
x,y,w,h = cv2.boundingRect(gray_inv)

# crop gray image
crop = gray[y:y+h, x:x+w]
hh, ww = crop.shape[:2]

# remove horizontal lines
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (ww,1))
morph = cv2.morphologyEx(crop, cv2.MORPH_CLOSE, kernel)
crop[morph<255] = 255

# average crop image to one column
column = cv2.resize(crop, (1,hh), interpolation = cv2.INTER_AREA)

# threshold on white
thresh = cv2.threshold(column, 245, 255, cv2.THRESH_BINARY)[1]

# get contours
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]

# loop over contours and get bounding boxes and ycenter and draw horizontal line at ycenter
result = crop.copy()
for cntr in contours:
    x,y,w,h = cv2.boundingRect(cntr)
    ycenter = y+h//2
    cv2.line(result, (0,ycenter), (ww-1,ycenter), (0, 0, 0), 2)

# write results
cv2.imwrite("table_lines2.png", result)

# display results
cv2.imshow("CROP", crop)
cv2.imshow("MORPH", morph)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
python opencv image-processing computer-vision ocr
1个回答
0
投票

制作tr(表格行)并将每个数据作为td(表格数据)我的朋友@Exhuzaifa使用了这个方法

© www.soinside.com 2019 - 2024. All rights reserved.