Python3 爬蟲學習筆記 C12【驗證碼對抗系列 — 圖形驗證碼】


Python3 爬蟲學習筆記第十二章 —— 【驗證碼對抗系列 — 圖形驗證碼】


【12.1】關於普通圖形驗證碼

普通圖形驗證碼一般由四位純數字、純字母或者字母數字組合構成,是最常見的驗證碼,也是最簡單的驗證碼,利用 tesserocr 或者 pytesseract 庫即可識別此類驗證碼,前提是已經安裝好 Tesseract-OCR 軟件

01

【12.2】tesserocr 庫識別驗證碼

簡單示例:

import tesserocr
from PIL import Image

image = Image.open('code.png')
result = tesserocr.image_to_text(image)
print(result)

新建一個 Image 對象,調用 tesserocr 的 image_to_text() 方法,傳入 Image 對象即可完成識別,另一種方法:

import tesserocr
print(tesserocr.file_to_text('code.png'))

【12.3】pytesseract 庫識別驗證碼

簡單示例:

import pytesseract
from PIL import Image

img = Image.open('code.png')
img = img.convert('RGB')
img.show()
print(pytesseract.image_to_string(img))

pytesseract 的各種方法:

  • get_tesseract_version:返回 Tesseract 的版本信息;
  • image_to_string:將圖像上的 Tesseract OCR 運行結果返回到字符串;
  • image_to_boxes:返回包含已識別字符及其框邊界的結果;
  • image_to_data:返回包含框邊界,置信度和其他信息的結果。需要 Tesseract 3.05+;
  • image_to_osd:返回包含有關方向和腳本檢測的信息的結果。

有關參數:

image_to_data(image, lang='', config='', nice=0, output_type=Output.STRING)

  • image:圖像對象;
  • lang:Tesseract 語言代碼字符串;
  • config:任何其他配置爲字符串,例如:config=’–psm 6’;
  • nice:修改 Tesseract 運行的處理器優先級。Windows不支持。尼斯調整了類似 unix 的流程的優點;
  • output_type:類屬性,指定輸出的類型,默認爲string。

lang 參數,常見語言代碼如下:

  • chi_sim:簡體中文
  • chi_tra:繁體中文
  • eng:英文
  • rus:俄羅斯語
  • fra:法語
  • deu:德語
  • jpn:日語

【12.4】驗證碼處理

利用 Image 對象的 convert() 方法傳入不同參數可以對驗證碼做一些額外的處理,如轉灰度、二值化等操作,經過處理過後的驗證碼會更加容易被識別,識別準確度更高,各種參數及含義:

  • 1:1位像素,黑白,每字節一個像素存儲;
  • L:8位像素,黑白;
  • P:8位像素,使用調色板映射到任何其他模式;
  • RGB:3x8位像素,真彩色;
  • RGBA:4x8位像素,帶透明度掩模的真彩色;
  • CMYK:4x8位像素,分色;
  • YCbCr:3x8位像素,彩色視頻格式;
  • I:32位有符號整數像素;
  • F:32位浮點像素。

示例:

import pytesseract
from PIL import Image

image = Image.open('code.png')
image = image.convert('L')
image.show()
result = pytesseract.image_to_string(image)
print(result)

Image 對象的 convert() 方法參數傳入 L,即可將圖片轉化爲灰度圖像,轉換前後對比:

02

import pytesseract
from PIL import Image

image = Image.open('code.png')
image = image.convert('1')
image.show()
result = pytesseract.image_to_string(image)
print(result)

Image 對象的 convert() 方法參數傳入 1,即可將圖片進行二值化處理,處理前後對比:

03

【12.5】tesserocr 與 pytesserocr 相關資料

  • tesserocr GitHub:https://github.com/sirfz/tesserocr

  • tesserocr PyPI:https://pypi.python.org/pypi/tesserocr

  • pytesserocr GitHub:https://github.com/madmaze/pytesseract

  • pytesserocr PyPI:https://pypi.org/project/pytesseract/

  • Tesseract-OCR 下載地址:http://digi.bib.uni-mannheim.de/tesseract

  • tesseract GitHub:https://github.com/tesseract-ocr/tesseract

  • tesseract 語言包:https://github.com/tesseract-ocr/tessdata

  • tesseract 文檔:https://github.com/tesseract-ocr/tesseract/wiki/Documentation

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章