使用python以及工具包進行簡單的驗證碼識別

識別數字驗證碼

首先咱們準備素材,4張驗證碼圖片以下:html

   

 

第一步:python

  打開圖像。app

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

第二步: ide

  把彩色圖像轉化爲灰度圖像。彩色圖像轉化爲灰度圖像的方法不少,這裏採用RBG轉化到HSI彩色空間,採用I份量。函數

imgry = im.convert('L')
 

灰度看起來是這樣的       優化

 

第三步:google

  須要把圖像中的噪聲去除掉。這裏的圖像比較簡單,直接閾值化就好了。咱們把大於閾值threshold的像素置爲1,其餘的置爲0。對此,先生成一張查找表,映射過程讓庫函數幫咱們作。spa

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

 

閾值爲何是140呢?試出來的,或者參考直方圖。

 

映射過程爲code

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

此時圖像看起來是這樣的htm

 

第四步:

  將圖片中的字符轉化爲文本。採用pytesser 中的image_to_string函數

text = image_to_string(out)

第五步:
  優化。根據觀察,驗證碼中只有數字,而且上面的文字識別程序常常把8識別爲S。所以,對於識別結果,在進行一些替換操做。
#因爲都是數字
#對於識別成字母的 採用該表進行修正
rep={'O':'0',
    'I':'1','L':'1',
    'Z':'2',
    'S':'8'
   for r in rep:
        text = text.replace(r,rep[r])

 

好了,text中爲最終結果。
7025
0195
7039
6716

注:程序須要 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])
 
    #out.save(text+'.jpg')
    print text
    return text
getverify1('v1.jpg')
getverify1('v2.jpg')
getverify1('v3.jpg')
getverify1('v4.jpg')
完整代碼
相關文章
相關標籤/搜索