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

标签 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张图片的Image:

Output output

最佳答案

不是尝试检测水平/垂直线,另一种方法是使用轮廓区域进行过滤以“忽略”这些线,只获取所需的文本字符。一个限制是它不会检测连接到水平/垂直线的文本

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()

关于python - 从图像中删除字符之间的小垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098161/

相关文章:

Python MySQL ON DUPLICATE KEY UPDATE - 只想更新某些列

python - 值错误: "hostingstart.app" could not be imported

python - 为什么cv2.resize()对整数数组不起作用?

image-processing - 只需 2 张图像即可自动进行人脸验证

python - 发送帖子请求python

Python读取大型xml文件并保存到csv文件

opencv - 适用于Pandaboard Ubuntu的CMake与OpenCV交叉编译

c++ - Boost/OpenCV 错误:不匹配调用 '(boost::_mfi::dm<void(cv::Mat*, cv::VideoCapture*), Recorder>)

python - 在Python中从图像中识别棋子

opencv - 如何从细节丰富的图像中指定计算机感兴趣的区域?