zoukankan      html  css  js  c++  java
  • 验证码识别之图像切割算法(三) 连通域分割

    切割前:     切割后:            

    代码:

    #-*-coding:utf-8-*-
    from PIL import Image
    import queue
    
    
    def cfs(img):
        """传入二值化后的图片进行连通域分割"""
        pixdata = img.load()
        w, h = img.size
        visited = set()
        q = queue.Queue()
        offset = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
        cuts = []
        for x in range(w):
            for y in range(h):
                x_axis = []
                # y_axis = []
                if pixdata[x, y] == 0 and (x, y) not in visited:
                    q.put((x, y))
                    visited.add((x, y))
                while not q.empty():
                    x_p, y_p = q.get()
                    for x_offset, y_offset in offset:
                        x_c, y_c = x_p + x_offset, y_p + y_offset
                        if (x_c, y_c) in visited:
                            continue
                        visited.add((x_c, y_c))
                        try:
                            if pixdata[x_c, y_c] == 0:
                                q.put((x_c, y_c))
                                x_axis.append(x_c)
                                # y_axis.append(y_c)
                        except:
                            pass
                if x_axis:
                    min_x, max_x = min(x_axis), max(x_axis)
                    if max_x - min_x > 3:
                        # 宽度小于3的认为是噪点,根据需要修改
                        cuts.append((min_x, max_x + 1))
        return cuts
    
    
    def saveSmall(img, outDir, cuts):
        w, h = img.size
        pixdata = img.load()
        for i, item in enumerate(cuts):
            box = (item[0], 0, item[1], h)
            img.crop(box).save(outDir + str(i) + ".bmp")
    
    
    img = Image.open('cfs/2.png')
    
    saveSmall(img, 'cfs/', cfs(img))

    思路是用深度遍历,对图片进行二值化处理,先找到一个黑色像素,然后对这个像素的周围8个像素进行判断,如果没有访问过,就保存起来,然后最后这个数组的最小x和最大x就是x轴上的切割位置。这种分割的方法还是只能适用于没有粘连的验证码,比垂直分割的好处是,可以处理位置比较奇怪的验证码。


    转载:https://blog.csdn.net/fox64194167/article/details/80557242
  • 相关阅读:
    python+selenium webdriver.firefox()方式配置浏览器设置
    spring框架学习之依赖注入(二)
    spring框架体系结构介绍
    mongoDB数据更新与操作符
    mongoDB学习笔记<一>
    关于IOS AFNetWorking内存泄漏的问题
    IOS 11 下适配UITableView
    调试Xamarin.Android时出现缺少"Mono.Posix 2.0.0"的错误
    EF6 MySQL错误之“Specified key was too long; max key length is 767 bytes”
    Webstrom安装+激活
  • 原文地址:https://www.cnblogs.com/xuchunlin/p/9290878.html
Copyright © 2011-2022 走看看