如何从图像中删除所有线条? (水平、垂直、对角线)

How to remove all lines from an image? (horizontal, vertical, diagonal)

我需要删除图像中的线条,最终是 table。我找到了删除水平线和垂直线的方法:

convert 1.jpg -type Grayscale -negate -define morphology:compose=darken -morphology Thinning 'Rectangle:1x80+0+0<' -negate out.jpg

下图:

已转换为以下内容:

可以看到对角线还在。我尝试将图像旋转 45 度,然后尝试将其删除,但也没有成功。怎么做到的?任何建议表示赞赏。我选择了 imagemagick,但欢迎任何其他选项

您可以尝试使用cv2.HoughLinesP()检测对角线,然后使用遮罩填充轮廓

import cv2
import numpy as np

image = cv2.imread('1.jpg')
mask = np.zeros(image.shape, np.uint8)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray,100,200)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
close = cv2.morphologyEx(canny, cv2.MORPH_CLOSE, kernel)
minLineLength = 10
maxLineGap = 350
lines = cv2.HoughLinesP(close,1,np.pi/180,100,minLineLength,maxLineGap)
for line in lines:
    for x1,y1,x2,y2 in line:
        cv2.line(mask,(x1,y1),(x2,y2),(255,255,255),3)

mask = cv2.cvtColor(mask,cv2.COLOR_BGR2GRAY)
cnts = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

for c in cnts:
    cv2.drawContours(image, [c], -1, (255,255,255), -1)

cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.imwrite('image.png', image)
cv2.waitKey()

这是另一种方法。我使用 Imagemagick,因为我不精通 OpenCV。基本上,我将图像二值化。然后做连通分量处理,隔离出最大的连续黑色区域,也就是你要排除的黑线。然后用它作为蒙版在线条上填充白色。这是 Imagemagick 的 Unix 语法。

请注意,如果碰到黑线,一些文本字符将会丢失。

输入:

获取最大黑色区域的id号:

id=`convert Arkey.jpg -threshold 50% -type bilevel \
-define connected-components:verbose=true \
-define connected-components:mean-color=true \
-connected-components 4 null: |\
grep "gray(0)" | head -n 1 | sed -n 's/^ *\(.*\):.*$//p'`


隔离黑线并放大它们

convert Arkey.jpg -threshold 50% -type bilevel \
-define connected-components:mean-color=true \
-define connected-components:keep=$id \
-connected-components 4 \
-alpha extract \
-morphology dilate octagon:2 \
mask.png


使用蒙版控制在图像中的线条上填充白色:

convert Arkey.jpg \( -clone 0 -fill white -colorize 100 \) mask.png -compose over -composite result.png


请参阅 https://imagemagick.org/script/connected-components.php 中的 -connected-components 了解其工作原理的详细信息。