1. 程式人生 > >10年經驗的老前輩,教你如何用Python 快速的破解驗證碼

10年經驗的老前輩,教你如何用Python 快速的破解驗證碼

我相信有很多的小夥伴跟小編一樣為驗證碼而煩惱。
小編為自學的同學,準備了全套的學習資料。自學需要一個學習好氛圍,小編建立一個群,時不時的小編會在群裡發一些學習資料。歡迎小夥伴的加入。QQ群883444106

專案簡介:本實驗通過一個簡單的例子來實現破解驗證碼,非常適合Python新手練手。從中我們可以學習到 Python 基本知識,PIL 模組的使用,破解驗證碼的原理。

本專案完整教程及線上練習地址:Python 破解驗證碼 (Python學習路徑中的基礎練手專案)

標題一、實驗說明

本實驗將通過一個簡單的例子來講解破解驗證碼的原理,將學習和實踐以下知識點:

Python基本知識
PIL模組的使用

標題二、實驗內容

安裝 pillow(PIL)庫:

$ sudo apt-get update

$ sudo apt-get install python-dev

$ sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev
libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

$ sudo pip install pillow
下載實驗用的檔案:

$ wget http://labfile.oss.aliyuncs.com/courses/364/python_captcha.zip


$ unzip python_captcha.zip
$ cd python_captcha
這是我們實驗使用的驗證碼 captcha.gif

提取文字圖片

在工作目錄下新建 crack.py 檔案,進行編輯。

#-- coding:utf8 --
from PIL import Image

im = Image.open(“captcha.gif”)
#(將圖片轉換為8位畫素模式)
im = im.convert(“P”)

#列印顏色直方圖
print im.histogram()
輸出:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0 , 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 1, 2, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 3, 1, 3, 3, 0, 0, 0, 0, 0, 0, 1, 0, 3, 2, 132, 1, 1, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 15, 0 , 1, 0, 1, 0, 0, 8, 1, 0, 0, 0, 0, 1, 6, 0, 2, 0, 0, 0, 0, 18, 1, 1, 1, 1, 1, 2, 365, 115, 0, 1, 0, 0, 0, 135, 186, 0, 0, 1, 0, 0, 0, 116, 3, 0, 0, 0, 0, 0, 21, 1, 1, 0, 0, 0, 2, 10, 2, 0, 0, 0, 0, 2, 10, 0, 0, 0, 0, 1, 0, 625]
顏色直方圖的每一位數字都代表了在圖片中含有對應位的顏色的畫素的數量。

每個畫素點可表現256種顏色,你會發現白點是最多(白色序號255的位置,也就是最後一位,可以看到,有625個白色畫素)。紅畫素在序號200左右,我們可以通過排序,得到有用的顏色。

his = im.histogram()
values = {}

for i in range(256):
values[i] = his[i]

for j,k in sorted(values.items(),key=lambda x:x[1],reverse = True)[:10]:
print j,k
輸出:

255 625
212 365
220 186
219 135
169 132
227 116
213 115
234 21
205 18
184 15
我們得到了圖片中最多的10種顏色,其中 220 與 227 才是我們需要的紅色和灰色,可以通過這一訊息構造一種黑白二值圖片。

#-- coding:utf8 --
from PIL import Image

im = Image.open(“captcha.gif”)
im = im.convert(“P”)
im2 = Image.new(“P”,im.size,255)

for x in range(im.size[1]):
for y in range(im.size[0]):
pix = im.getpixel((y,x))
if pix == 220 or pix == 227: # these are the numbers to get
im2.putpixel((y,x),0)

im2.show()
得到的結果:

提取單個字元圖片

接下來的工作是要得到單個字元的畫素集合,由於例子比較簡單,我們對其進行縱向切割:

inletter = False
foundletter=False
start = 0
end = 0

letters = []

for y in range(im2.size[0]):
for x in range(im2.size[1]):
pix = im2.getpixel((y,x))
if pix != 255:
inletter = True
if foundletter == False and inletter == True:
foundletter = True
start = y

if foundletter == True and inletter == False:
    foundletter = False
    end = y
    letters.append((start,end))

inletter=False

print letters
輸出:

[(6, 14), (15, 25), (27, 35), (37, 46), (48, 56), (57, 67)]
得到每個字元開始和結束的列序號。

import hashlib
import time

count = 0
for letter in letters:
m = hashlib.md5()
im3 = im2.crop(( letter[0] , 0, letter[1],im2.size[1] ))
m.update("%s%s"%(time.time(),count))
im3.save("./%s.gif"%(m.hexdigest()))
count += 1
(接上面的程式碼)

對圖片進行切割,得到每個字元所在的那部分圖片。

AI 與向量空間影象識別

在這裡我們使用向量空間搜尋引擎來做字元識別,它具有很多優點:

不需要大量的訓練迭代
不會訓練過度
你可以隨時加入/移除錯誤的資料檢視效果
很容易理解和編寫成程式碼
提供分級結果,你可以檢視最接近的多個匹配
對於無法識別的東西只要加入到搜尋引擎中,馬上就能識別了。
當然它也有缺點,例如分類的速度比神經網路慢很多,它不能找到自己的方法解決問題等等。

向量空間搜尋引擎名字聽上去很高大上其實原理很簡單。拿文章裡的例子來說:

你有 3 篇文件,我們要怎麼計算它們之間的相似度呢?2 篇文件所使用的相同的單詞越多,那這兩篇文章就越相似!但是這單詞太多怎麼辦,就由我們來選擇幾個關鍵單詞,選擇的單詞又被稱作特徵,每一個特徵就好比空間中的一個維度(x,y,z 等),一組特徵就是一個向量,每一個文件我們都能得到這麼一個向量,只要計算向量之間的夾角就能得到文章的相似度了。

用 Python 類實現向量空間:

import math

class VectorCompare:
#計算向量大小
def magnitude(self,concordance):
total = 0
for word,count in concordance.iteritems():
total += count ** 2
return math.sqrt(total)

#計算向量之間的 cos 值
def relation(self,concordance1, concordance2):
    relevance = 0
    topvalue = 0
    for word, count in concordance1.iteritems():
        if concordance2.has_key(word):
            topvalue += count * concordance2[word]
    return topvalue / (self.magnitude(concordance1) * self.magnitude(concordance2))

它會比較兩個 python 字典型別並輸出它們的相似度(用 0~1 的數字表示)

將之前的內容放在一起

還有取大量驗證碼提取單個字元圖片作為訓練集合的工作,但只要是有好好讀上文的同學就一定知道這些工作要怎麼做,在這裡就略去了。可以直接使用提供的訓練集合來進行下面的操作。

iconset目錄下放的是我們的訓練集。

最後追加的內容:

#將圖片轉換為向量
def buildvector(im):
d1 = {}
count = 0
for i in im.getdata():
d1[count] = i
count += 1
return d1

v = VectorCompare()

iconset = [‘0’,‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’,‘0’,‘a’,‘b’,‘c’,‘d’,‘e’,‘f’,‘g’,‘h’,‘i’,‘j’,‘k’,‘l’,‘m’,‘n’,‘o’,‘p’,‘q’,‘r’,‘s’,‘t’,‘u’,‘v’,‘w’,‘x’,‘y’,‘z’]

#載入訓練集
imageset = []
for letter in iconset:
for img in os.listdir(’./iconset/%s/’%(letter)):
temp = []
if img != “Thumbs.db” and img != “.DS_Store”:
temp.append(buildvector(Image.open("./iconset/%s/%s"%(letter,img))))
imageset.append({letter:temp})

count = 0
#對驗證碼圖片進行切割
for letter in letters:
m = hashlib.md5()
im3 = im2.crop(( letter[0] , 0, letter[1],im2.size[1] ))

guess = []

#將切割得到的驗證碼小片段與每個訓練片段進行比較
for image in imageset:
    for x,y in image.iteritems():
        if len(y) != 0:
            guess.append( ( v.relation(y[0],buildvector(im3)),x) )

guess.sort(reverse=True)
print "",guess[0]
count += 1

得到結果

一切準備就緒,執行我們的程式碼試試:

python crack.py
輸出

(0.96376811594202894, ‘7’)
(0.96234028545977002, ‘s’)
(0.9286884286888929, ‘9’)
(0.98350370609844473, ‘t’)
(0.96751165072506273, ‘9’)
(0.96989711688772628, ‘j’)
是正解,幹得漂亮。

本作品在 知識共享許可協議3.0 下許可授權。