• 验证码识别 图像降噪 Python (一)


    原始图片:

    降噪后的图片

    实现代码:

    # coding:utf-8
    import sys, os
    from PIL import Image, ImageDraw
    
    # 二值数组
    t2val = {}
    
    
    def twoValue(image, G):
        for y in xrange(0, image.size[1]):
            for x in xrange(0, image.size[0]):
                g = image.getpixel((x, y))
                if g > G:
                    t2val[(x, y)] = 1
                else:
                    t2val[(x, y)] = 0
    
    
    # 根据一个点A的RGB值,与周围的8个点的RBG值比较,设定一个值N(0 <N <8),当A的RGB值与周围8个点的RGB相等数小于N时,此点为噪点
    # G: Integer 图像二值化阀值
    # N: Integer 降噪率 0 <N <8
    # Z: Integer 降噪次数
    # 输出
    #  0:降噪成功
    #  1:降噪失败
    def clearNoise(image, N, Z):
        for i in xrange(0, Z):
            t2val[(0, 0)] = 1
            t2val[(image.size[0] - 1, image.size[1] - 1)] = 1
    
            for x in xrange(1, image.size[0] - 1):
                for y in xrange(1, image.size[1] - 1):
                    nearDots = 0
                    L = t2val[(x, y)]
                    if L == t2val[(x - 1, y - 1)]:
                        nearDots += 1
                    if L == t2val[(x - 1, y)]:
                        nearDots += 1
                    if L == t2val[(x - 1, y + 1)]:
                        nearDots += 1
                    if L == t2val[(x, y - 1)]:
                        nearDots += 1
                    if L == t2val[(x, y + 1)]:
                        nearDots += 1
                    if L == t2val[(x + 1, y - 1)]:
                        nearDots += 1
                    if L == t2val[(x + 1, y)]:
                        nearDots += 1
                    if L == t2val[(x + 1, y + 1)]:
                        nearDots += 1
    
                    if nearDots < N:
                        t2val[(x, y)] = 1
    
    
    def saveImage(filename, size):
        image = Image.new("1", size)
        draw = ImageDraw.Draw(image)
    
        for x in xrange(0, size[0]):
            for y in xrange(0, size[1]):
                draw.point((x, y), t2val[(x, y)])
    
        image.save(filename)
    for i in range(1,21):
        path = "/" + str(i) + ".jpg"
        image = Image.open(path).convert("L")
        twoValue(image, 100)
        clearNoise(image, 2, 1)
        path1 = "/" + str(i) + ".png"
        saveImage(path1, image.size)
  • 相关阅读:
    使用css的类名交集复合选择器 《转》
    在Web.config或App.config中的添加自定义配置 <转>
    [转]给ListView加上ComboBox或是TextBox控件
    WinForm Timer控件,三级联动[省,市,区]
    WinForm用户窗体
    WinForm 进程 ,线程
    WinForm MDI窗体容器
    WinForm 控件TabelControl对TabelPage页的添加,删除操作
    [转]C#重绘TabControl的Tabpage标签,添加图片及关闭按钮
    WinForm sender初级应用
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/9234455.html
Copyright © 2020-2023  润新知