You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python OpenCV为无边框表格加线条遇问题求助

无边框表格添加网格线的OpenCV处理问题

我正在开展无边框表格图像处理项目,目标是用Python的OpenCV库为这类表格添加网格线。在Stack Overflow找到一个看似可行的方案,但运行代码后处理效果未达预期。

我使用的代码如下:

import cv2
import numpy as np

# read the input
img = cv2.imread('/content/sample_data/Untitled.png')
hh, ww = img.shape[:2]

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

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

# average gray image to one row
row = cv2.resize(thresh, (ww, 1), interpolation = cv2.INTER_AREA)

# threshold on white
thresh1 = cv2.threshold(row, 254, 255, cv2.THRESH_BINARY)[1]

# apply small amount of morphology to merge period with column of text
kernel = cv2.getStructuringElement(cv2.MORPH_RECT , (5,1))
thresh1 = cv2.morphologyEx(thresh1, cv2.MORPH_OPEN, kernel)

# get contours
contours = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
result = img.copy()
result1 = img.copy()
for cntr in contours:
    x, y, w, h = cv2.boundingRect(cntr)
    xcenter = x + w // 2
    cv2.line(result1, (xcenter,0), (xcenter, hh-1), (0, 0, 0), 1)
    cv2.line(result, (xcenter,0), (xcenter, hh-1), (0, 0, 0), 1)

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

# threshold on white
thresh2 = cv2.threshold(column, 254, 255, cv2.THRESH_BINARY)[1]
# get contours

contours = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
result2 = img.copy()
for cntr in contours:
    x, y, w, h = cv2.boundingRect(cntr)
    ycenter = y + h // 2
    cv2.line(result2, (0, ycenter), (ww-1, ycenter), (0, 0, 0), 1)
    cv2.line(result, (0, ycenter), (ww-1, ycenter), (0, 0, 0), 1)

# save results
cv2.imwrite('table4_threshold.png', thresh)
cv2.imwrite('table4_column_lines.png', result1)
cv2.imwrite('table4_row_lines.png', result2)
cv2.imwrite('table4_column_and_row_lines.png', result)

图像对比

  • 输入图像:
    输入图像

  • 预期输出:
    预期输出

  • 实际输出:
    实际输出

有没有人使用OpenCV处理无边框表格时遇到过类似问题?


内容的提问来源于stack exchange,提问作者Israt jahan Fateha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:07:49