从图像中删除字符之间的小垂直线

时间:2019-09-25 12:15:46

标签: python opencv image-processing computer-vision

我要删除所有水平和垂直线。我可以删除水平线,但是在删除小的垂直线时,原始文本也会受到影响。这是我正在使用的代码:

image = cv2.imread('opt/doc/uploads/img1.png')
result = image.copy()
blur = image.copy()
gray = cv2.cvtColor(blur,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0,255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

rows,cols = thresh.shape
horizontalsize = int(cols // 30)
verticalsize = int(rows // 30)

# Remove horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontalsize,1))
remove_horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel)
cnts = cv2.findContours(remove_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(result, [c], -1, (255,255,255), 3)                        


# Remove vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,20))        
remove_vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel)
cnts = cv2.findContours(remove_vertical, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(result, [c], -1, (255,255,255),3)

cv2.imwrite('result.png', result)

PFB 2输入图像:

Input Image Input Image

PFB分别输出以上2张图像的图像:

Output output

1 个答案:

答案 0 :(得分:0)

另一种方法不是尝试检测水平/垂直线条,而是使用轮廓区域进行过滤以“忽略”线条并仅采用所需的文本字符。一个限制是它将无法检测到连接到水平/垂直线的文本

enter image description here

import cv2
import numpy as np

image = cv2.imread('1.png')
mask = np.ones(image.shape, dtype=np.uint8) * 255
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area < 1000:
        x,y,w,h = cv2.boundingRect(c)
        mask[y:y+h, x:x+w] = image[y:y+h, x:x+w]

cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.waitKey()