使用PYTHON PIL从Captcha Image中删除背景噪声线

时间:2013-03-10 06:17:21

标签: python algorithm image-processing python-imaging-library captcha

我有一个处理过的验证码图像(放大)看起来像:
captcha

如您所见,“TEXT”的字体大小比噪音线的宽度略大。
所以我需要一个算法或代码来从这个图像中删除嘈杂的线条。

借助Python PIL Library和下面提到的斩波算法,我得不到OCR可以轻松读取的输出图像。

这是我尝试过的Python代码:

import PIL.Image
import sys

# python chop.py [chop-factor] [in-file] [out-file]

chop = int(sys.argv[1])
image = PIL.Image.open(sys.argv[2]).convert('1')
width, height = image.size
data = image.load()

# Iterate through the rows.
for y in range(height):
    for x in range(width):

        # Make sure we're on a dark pixel.
        if data[x, y] > 128:
            continue

        # Keep a total of non-white contiguous pixels.
        total = 0

        # Check a sequence ranging from x to image.width.
        for c in range(x, width):

            # If the pixel is dark, add it to the total.
            if data[c, y] < 128:
                total += 1

            # If the pixel is light, stop the sequence.
            else:
                break

        # If the total is less than the chop, replace everything with white.
        if total <= chop:
            for c in range(total):
                data[x + c, y] = 255

        # Skip this sequence we just altered.
        x += total


# Iterate through the columns.
for x in range(width):
    for y in range(height):

        # Make sure we're on a dark pixel.
        if data[x, y] > 128:
            continue

        # Keep a total of non-white contiguous pixels.
        total = 0

        # Check a sequence ranging from y to image.height.
        for c in range(y, height):
            # If the pixel is dark, add it to the total.
            if data[x, c] < 128:
                total += 1

            # If the pixel is light, stop the sequence.
            else:
                break

        # If the total is less than the chop, replace everything with white.
        if total <= chop:
            for c in range(total):
                data[x, y + c] = 255

        # Skip this sequence we just altered.
        y += total

image.save(sys.argv[3])

所以,基本上我想知道一个更好的算法/代码来摆脱噪音,从而能够使图像可以被OCR(Tesseract或pytesser)读取。

3 个答案:

答案 0 :(得分:1)

要快速摆脱大多数线条,您可以将两个或更少相邻黑色像素的所有黑色像素变为白色。这应该可以修复杂散线。然后,当你有很多“块”时,你可以删除较小的块。

这是假设样本图像已放大,并且线条只有一个像素宽。

答案 1 :(得分:0)

您可以使用自己的扩张和侵蚀功能,这将删除最小的线条。可以找到一个很好的实现here

答案 2 :(得分:0)

我个人使用如上所述的扩张和侵蚀,但将其与宽度和高度的一些基本统计结合起来,尝试找出异常值并根据需要消除这些线。之后,在使用临时图像作为原始图像之前,采用内核的最小值并转换临时图像中的颜色的中心像素(迭代旧图像)的过滤器应该起作用。在pillow / PIL中,基于最小的任务是通过img.filter(ImageFilter.MINFILTER)完成的。

如果这还不够,它应该产生一个可识别的集合,OpenCV的轮廓和最小边界旋转框可用于旋转字母进行比较(我推荐Tesseract或商业OCR,因为他们有一吨字体和其他功能,如群集和清理)。