Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用Python與工具庫做簡單的驗證碼識別

本文用Python搭配工具庫做一個簡單的驗證碼識別,直接開始。

原始圖像

Step 1 先把圖片打開。

im = Image.open('temp1.jpg')

Step 2 把彩色圖像轉為灰階圖像。彩色轉灰階的方法很多,這裡採用RGB轉到HSI彩色空間、取I分量的方式。

imgry = im.convert('L')

灰階看起來是這樣的

Step 3 需要把圖片中的雜訊去掉。這張圖比較簡單,直接做閾值化即可:把大於閾值threshold的像素設為1,其餘設為0。為此先建立一張查找表,映射過程交給庫函數完成。

threshold = 140
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)

閾值為什麼是140?試出來的,或參考直方圖。

映射過程為

 out = imgry.point(table, '1')

此時圖片看起來是這樣的

Step 4 把圖片中的字元轉為文字,採用pytesser中的image_to_string函數。

text = image_to_string(out)

Step 5 優化。依觀察,驗證碼中只有數字,而上面的識別程式常把8誤判為S,因此對識別結果再做一層替換修正。

#由於都是數字
#對於被識別成字母的,採用該表進行修正
rep = {'O':'0',
    'I':'1', 'L':'1',
    'Z':'2',
    'S':'8'
    };

程式需要PIL庫與pytesser庫支援。最後,整個程式看起來是這樣:

import Image
import ImageEnhance
import ImageFilter
import sys
from pytesser import * # 二值化
threshold = 140
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
#由於都是數字
#對於被識別成字母的,採用該表進行修正
rep = {'O':'0',
    'I':'1', 'L':'1',
    'Z':'2',
    'S':'8'
    };
def getverify1(name):
   
    #打開圖片
    im = Image.open(name)
    #轉化到亮度
    imgry = im.convert('L')
    imgry.save('g' + name)
    #二值化
    out = imgry.point(table, '1')
    out.save('b' + name)
    #識別
    text = image_to_string(out)
    #識別對嗎
    text = text.strip()
    text = text.upper();
    for r in rep:
        text = text.replace(r, rep[r])
    print text
    return text
getverify1('v1.jpg')
getverify1('v2.jpg')
getverify1('v3.jpg')
getverify1('v4.jpg')

程式與測試資料可至Linux公社的1號FTP伺服器下載:

FTP位址:ftp://www.linuxidc.com
用戶名:www.linuxidc.com
密碼:www.muu.cc
目錄:2013年LinuxIDC.com\1月\使用Python以及工具包進行簡單的驗證碼識別

下載方法見 https://www.linuxidc.net/thread-1187-1-1.html

Copyright © Linux教程網 All Rights Reserved