2 最簡單的驗證碼生成

  1. 想要識別驗證碼,就得知道驗證碼是怎麼生成的。下面從最基本的驗證碼講起。
  2. 思路:隨機生成4個數字或者字母,然後把他們畫在圖片的固定位置。最早的驗證碼就是這樣生成的。
  3. 代碼

# coding=utf-8Created on 2016年10月17日程序作用:最基本的驗證碼,不帶任何干擾from __future__ import divisionfrom __future__ import unicode_literalsimport sysreload(sys)sys.setdefaultencoding(utf-8) # @UndefinedVariablefrom PIL import Image,ImageFont,ImageDrawimport random # 返回隨機字母def charRandom(): return chr((random.randint(65,90))) # 返回隨機數字def numRandom(): return chr(random.randint(48,57))# 返回隨機字母或者數字def textRandom(): # 0-1的隨機數 if random.random()>0.7: return numRandom() else: return charRandom() # 隨機顏色def colorRandom1(): return (random.randint(64,255),random.randint(64,255),random.randint(64,255)) # 隨機長生顏色2def colorRandom2(): return (random.randint(32,127),random.randint(32,127),random.randint(32,127)) def create_security_img(): width = 60 * 4 height = 60 # 創建一個全白的圖片 image = Image.new(RGB, (width,height), (255,255,255)); # 創建draw對象 draw = ImageDraw.Draw(image) # 創建font對象 注意這裡網上大部分資料都有問題 這裡應該自己去python對應的目錄找字體文件的路徑 font = ImageFont.truetype(rC:Python27Libsite-packagesmatplotlibmpl-datafonts tfcmr10.ttf,36); # 輸出文字 for t in range(4): # 起始位置 要寫的字母 字體 顏色 draw.text((60*t+10,10), textRandom(),font=font, fill=colorRandom2()) return imageif __name__ == __main__: img=create_security_img() img.show()

生成的圖片大概是這個樣子的

下一期介紹,常見驗證碼的變種。

版權聲明:本文為原創文章,未經允許不得轉載。

推薦閱讀:

scikit-learn實戰
嘗試克服一下小夥伴對神經網路的恐懼No.26

TAG:機器學習 | 數據挖掘 | 驗證碼 |