从包含带边框的表格的图像中提取表格结构

2024-05-16

我正在尝试提取下表中的单元格位置。

应用自适应阈值处理后,我能够获得细胞位置周围的轮廓,并且 HoughLines 获得垂直和水平结构元素。 这是我的代码:

img = cv2.imread(os.path.join(img_path, file))
img1 = img.copy()


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 17, 1)
bw = cv2.bitwise_not(bw)


#detect horizontal lines
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))

horizontal = cv2.erode(bw, horizontalStructure)
horizontal = cv2.dilate(horizontal, horizontalStructure)

horizontal = cv2.dilate(horizontal, (1,1), iterations=5)
horizontal = cv2.erode(horizontal, (1,1), iterations=5)


hlines = cv2.HoughLinesP(horizontal, 1, np.pi/180, 20, np.array([]), 20, 2)


for line in hlines :
    for x1,y1,x2,y2 in line:
        if abs(x1 - x2) > img.shape[1]/4:    
            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)





#detect vertical lines
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 15))

vertical = cv2.erode(bw, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)

vertical = cv2.dilate(vertical, (1,1), iterations=5)
#vertical = cv2.erode(vertical, (1,1), iterations=5)


vlines = cv2.HoughLinesP(vertical, 1, np.pi/180, 20, np.array([]), 20, 2)


for line in vlines :
    for x1,y1,x2,y2 in line:
        #if abs(y1 - y2) > img.shape[0]/2:
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)





# red color boundaries [B, G, R]
lower = [0, 240, 0]
upper = [20, 255, 20]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img1, img, mask=mask)



ret,thresh = cv2.threshold(mask, 40, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img_area  = img.shape[0] * img.shape[1]

for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    if w * h > 0.005 * img_area:
        cv2.rectangle(img1, (x, y), (x+w, y+h), (0, 0, 255), 2)

我该如何改进这个解决方案?为了更好、更稳健地提取表格单元格信息,我还可以实施哪些其他方法?


对于检测到的每个框,采用更宽的区域来处理任意错误阈值(以n像素宽度,例如5像素),您应该能够检测到每个文本内容

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从包含带边框的表格的图像中提取表格结构 的相关文章

随机推荐