python 驗證碼 (二) 連通域分割

來源:互聯網
上載者:User

標籤:blog   imp   最小   cut   位置   一個   max   pil   pre   

切割前:     切割後:            

 

代碼:

#-*-coding:utf-8-*-from PIL import Imageimport queuedef 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 cutsdef 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軸上的切割位置。這種分割的方法還是只能適用於沒有粘連的驗證碼,比垂直分割的好處是,可以處理位置比較奇怪的驗證碼。


轉載:80557242

 

python 驗證碼 (二) 連通域分割

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.