从图像中移除噪声线

2024-04-29 14:05:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些像下面这样的随机线的图像:
enter image description here
我想对它们进行一些预处理,以消除不必要的噪音(扭曲书写的线条),以便我可以将它们与OCR(Tesseract)一起使用。
我想到的想法是用膨胀法去除噪音,然后用腐蚀法在第二步修复缺失的部分。
为此,我使用了以下代码:

import cv2
import numpy as np

img = cv2.imread('linee.png', cv2.IMREAD_GRAYSCALE)
kernel = np.ones((5, 5), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)
cv2.imwrite('delatedtest.png', img)

不幸的是,扩容效果不好,噪音线仍然存在。在

enter image description here
我试着改变内核的形状,但情况变得更糟:文字部分或全部被删除。
我还发现一个answer表示可以通过

turning all black pixels with two or less adjacent black pixels to white.

这对我来说有点复杂,因为我是计算机视觉和opencv的初学者。
任何帮助都将不胜感激,谢谢。在


Tags: 图像importimgpngnpcv2kernel线条
2条回答

探测像这样的线是path opening发明的目的。PyDIP有一个实现(披露:我在那里实现了它;还请注意,您必须从源代码安装PyDIP,因为我们还没有创建一个二进制发行版)。作为一种选择,你可以尝试使用我上面链接的论文的the implementation by the authors。该实现没有我下面使用的the "constrained" mode。在

下面是一个如何使用它的快速演示:

import PyDIP as dip
import matplotlib.pyplot as pp

img = 1 - pp.imread('/home/cris/tmp/DWRTF.png')
lines = dip.PathOpening(img, length=300, mode={'constrained'})

在这里,我们首先将图像反转,因为这样可以使以后的其他事情变得更简单。如果不反转,请使用闭合路径。lines图像:

lines

接下来我们减去这些线。一个小区域开口将删除由路径开口过滤掉的行中的几个孤立像素:

^{pr2}$

text

然而,我们现在在文本中做了一些空白。把这些填满可不是小事。下面是一个快速而肮脏的尝试,您可以将其作为起点:

lines = lines > 0.5
text = text > 0.5
lines -= dip.BinaryPropagation(text, lines, connectivity=-1, iterations=3)
img[lines] = 0

final result

您可以使用createLineSegmentDetector(),这是一个来自opencv的函数

import cv2

#Read gray image
img = cv2.imread("lines.png",0)

#Create default parametrization LSD
lsd = cv2.createLineSegmentDetector(0)

#Detect lines in the image
lines = lsd.detect(img)[0] #Position 0 of the returned tuple are the detected lines

#Draw the detected lines
drawn_img = lsd.drawSegments(img,lines)

#Save the image with the detected lines
cv2.imwrite('lsdsaved.png', drawn_img)

enter image description here
代码的下一部分将只删除长度超过50像素的行:

^{pr2}$

enter image description here

嗯,它不能很好地处理当前的图像,但它可能会在不同的图像上产生更好的效果。您可以调整要删除的线条的长度和白色线条的粗细以绘制已删除线条的背面。
我希望有帮助。在

相关问题 更多 >