歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Python以及工具包進行簡單的驗證碼識別

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

日期:2017/3/1 10:03:55   编辑:Linux編程

使用Python以及工具包進行簡單的驗證碼識別,直接開始。

原始圖像

Step 1 打開圖像吧。

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

Step 2 把彩色圖像轉化為灰度圖像。彩色圖像轉化為灰度圖像的方法很多,這裡采用RBG轉化到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'
}; 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') 程序以及測試數據在這裡

**************************************************************

下載在Linux公社的1號FTP服務器裡,下載地址:

FTP地址:ftp://www.linuxidc.com

用戶名:www.linuxidc.com

密碼:www.muu.cc

在 2013年LinuxIDC.com\1月\使用Python以及工具包進行簡單的驗證碼識別

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

**************************************************************

Copyright © Linux教程網 All Rights Reserved