農林漁牧網

您現在的位置是:首頁 > 農業

圖形驗證碼識別技術

2022-04-11由 指示牌標識標牌設計 發表于 農業

圖形驗證碼怎麼輸入求解

阻礙我們爬蟲的。有時候正是在登入或者請求一些資料時候的圖形驗證碼。因此這裡我們講解一種能將圖片翻譯成文字的技術。將圖片翻譯成文字一般被成為光學文字識別(Optical Character Recognition),簡寫為

OCR

。實現

OCR

的庫不是很多,特別是開源的。因為這塊存在一定的技術壁壘(需要大量的資料、演算法、機器學習、深度學習知識等),並且如果做好了具有很高的商業價值。因此開源的比較少。這裡介紹一個比較優秀的影象識別開源庫:Tesseract。

圖形驗證碼識別技術

Tesseract:

Tesseract是一個OCR庫,目前由谷歌贊助。Tesseract是目前公認最優秀、最準確的開源OCR庫。Tesseract具有很高的識別度,也具有很高的靈活性,他可以透過訓練識別任何字型。

安裝:

Windows系統:

在以下連結下載可執行檔案,然後一頓點選下一步安裝即可(放在不需要許可權的純英文路徑下):

https://github。com/tesseract-ocr/

Linux系統:

可以在以下連結下載原始碼自行編譯。

https://github。com/tesseract-ocr/tesseract/wiki/Compiling

Pycharm啟用碼教程使用更多解釋請見:

https://vrg123。com

或者在

ubuntu

下透過以下命令進行安裝:

sudo apt install tesseract-ocr

Mac系統:

Homebrew

即可方便安裝:

brew install tesseract

設定環境變數:

安裝完成後,如果想要在命令列中使用

Tesseract

,那麼應該設定環境變數。

Mac

Linux

在安裝的時候就預設已經設定好了。在

Windows

下把

tesseract。exe

所在的路徑新增到

PATH

環境變數中。

還有一個環境變數需要設定的是,要把訓練的資料檔案路徑也放到環境變數中。

在環境變數中,新增一個

TESSDATA_PREFIX=C:\path_to_tesseractdata\teseractdata

在命令列中使用tesseract識別影象:

如果想要在

cmd

下能夠使用

tesseract

命令,那麼需要把

tesseract。exe

所在的目錄放到

PATH

環境變數中。然後使用命令:

tesseract 圖片路徑 檔案路徑

示例:

tesseract a。png a

那麼就會識別出

a。png

中的圖片,並且把文字寫入到

a。txt

中。如果不想寫入檔案直接想顯示在終端,那麼不要加檔名就可以了。

在程式碼中使用tesseract識別影象:

Python

程式碼中操作

tesseract

。需要安裝一個庫,叫做

pytesseract

。透過

pip

的方式即可安裝:

pip install pytesseract

並且,需要讀取圖片,需要藉助一個第三方庫叫做

PIL

。透過

pip list

看下是否安裝。如果沒有安裝,透過

pip

的方式安裝:

pip install PIL

使用

pytesseract

將圖片上的文字轉換為文字文字的示例程式碼如下:

# 匯入pytesseract庫 import pytesseract # 匯入Image庫 from PIL import Image # 指定tesseract。exe所在的路徑 pytesseract。pytesseract。tesseract_cmd = r‘D:\ProgramApp\TesseractOCR\tesseract。exe’ # 開啟圖片 image = Image。open(“a。png”) # 呼叫image_to_string將圖片轉換為文字 text = pytesseract。image_to_string(image) print(text)

pytesseract

處理拉勾網圖形驗證碼:

import pytesseract from urllib import request from PIL import Image import time pytesseract。pytesseract。tesseract_cmd = r“D:\ProgramApp\TesseractOCR\tesseract。exe” while True: captchaUrl = “https://passport。lagou。com/vcode/create?from=register&refresh=1513081451891” request。urlretrieve(captchaUrl,‘captcha。png’) image = Image。open(‘captcha。png’) text = pytesseract。image_to_string(image,lang=‘eng’) print(text) time。sleep(2)