詳解利用Python破解驗證碼執行個體代碼

來源:互聯網
上載者:User
一、前言
本實驗將通過一個簡單的例子來講解破解http://www.php.cn/code/6832.html" target="_blank">驗證碼的原理,將學習和實踐以下知識點:
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 Imageim = 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 625212 365220 186219 135169 132227 116213 115234 21205 18184 15


我們得到了圖片中最多的10種顏色,其中 220 與 227 才是我們需要的紅色和灰色,可以通過這一訊息構造一種黑白二值圖片。

#-*- coding:utf8 -*-from PIL import Imageim = 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 = Falsefoundletter=Falsestart = 0end = 0letters = []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=Falseprint letters


輸出:

[(6, 14), (15, 25), (27, 35), (37, 46), (48, 56), (57, 67)]


得到每個字元開始和結束的列序號。

import hashlibimport timecount = 0for 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 與向量空間Image Recognition
在這裡我們使用向量空間搜尋引擎來做字元識別,它具有很多優點:
不需要大量的訓練迭代
不會訓練過度
你可以隨時加入/移除錯誤的資料查看效果
很容易理解和編寫成代碼
提供分級結果,你可以查看最接近的多個匹配
對於無法識別的東西只要加入到搜尋引擎中,馬上就能識別了。
當然它也有缺點,例如分類的速度比神經網路慢很多,它不能找到自己的方法解決問題等等。
向量空間搜尋引擎名字聽上去很高大上其實原理很簡單。拿文章裡的例子來說:
你有 3 篇文檔,我們要怎麼計算它們之間的相似性呢?2 篇文檔所使用的相同的單詞越多,那這兩篇文章就越相似!但是這單詞太多怎麼辦,就由我們來選擇幾個關鍵單詞,選擇的單詞又被稱作特徵,每一個特徵就好比空間中的一個維度(x,y,z 等),一組特徵就是一個向量,每一個文檔我們都能得到這麼一個向量,只要計算向量之間的夾角就能得到文章的相似性了。
用 Python 類實現向量空間:

import mathclass 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 d1v = 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')

是正解,幹得漂亮。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.