首页 > 解决方案 > 如何从表格中提取行并创建只有表格行的黑白表格

问题描述

我有一个包含表格的图像: 在此处输入图像描述 我使用下面的代码删除水平和垂直线并创建一个只有表格线的图像

import cv2 as cv
import numpy as np

img = cv.imread('1.jpg')
cv.imshow('Original', img)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
gray = cv.bitwise_not(gray)
bw = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 15, -2)

# Create the images that will use to extract the vertical lines
vertical = np.copy(bw)
horizontal = np.copy(bw)

# Specify size on horizontal axis
cols = horizontal.shape[1]
horizontal_size = cols / 10
horizontal_size=int(horizontal_size)

# Create structure element for extracting horizontal lines through morphology operations
horizontalStructure = cv.getStructuringElement(cv.MORPH_RECT, (horizontal_size, 1))

horizontal = cv.erode(horizontal, horizontalStructure)
horizontal = cv.dilate(horizontal, horizontalStructure) 
# horizontal = cv.dilate(horizontal, (3, 3), iterations=1)

# Specify size on vertical axis
rows = vertical.shape[0]
verticalsize = rows / 10
verticalsize = int(verticalsize)

# Create structure element for extracting vertical lines through morphology operations
verticalStructure = cv.getStructuringElement(cv.MORPH_RECT, (1, verticalsize))

# Apply morphology operations
vertical = cv.erode(vertical, verticalStructure)
vertical = cv.dilate(vertical, verticalStructure)
# vertical = cv.dilate(vertical, (3, 3), iterations=1)

ret, thresh_v = cv.threshold(vertical, 127, 255, cv.THRESH_BINARY)
# cv.imshow('thresh vertical', thresh_v)

ret, thresh_h = cv.threshold(horizontal, 127, 255, cv.THRESH_BINARY)
# cv.imshow('thresh horizontal', thresh_h)

table_lines = cv.bitwise_or(thresh_h, thresh_v)
cv.imshow('table lines', table_lines)

cv.waitKey(0)

这是输出: 在此处输入图像描述 这张图片很乱。有没有办法处理它以制作一个完整的表格,其中只有原始图像中可见的线条?

标签: pythonopencv

解决方案


您应该能够使用霍夫线变换改进您的结果:https ://docs.opencv.org/4.5.3/d9/db0/tutorial_hough_lines.html 。我怀疑您能否恢复整个表格,因为右侧的对比度非常低。


推荐阅读