tesseract 是一個(gè) OCR(Optical Character Recognition,光學(xué)字符識(shí)別)引擎榄融,能夠識(shí)別圖片中字符,利用這個(gè)可以用來(lái)解析一些簡(jiǎn)單的圖片驗(yàn)證碼
Github 地址:https://github.com/tesseract-ocr/tesseract
Windows 平臺(tái) v3.05.01 版本下載地址:http://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-setup-3.05.01.exe
一開(kāi)始弄這個(gè)是因?yàn)閷W(xué)校網(wǎng)絡(luò)要上網(wǎng)每次都要在網(wǎng)頁(yè)驗(yàn)證救湖,就想能不能寫(xiě)個(gè)程序自動(dòng)驗(yàn)證免去手動(dòng)驗(yàn)證過(guò)程愧杯。但這需要驗(yàn)證碼,為了解決這個(gè)問(wèn)題鞋既,就上網(wǎng)搜了一下力九,就看到有用 tesseract 的。
有人用 Python 實(shí)現(xiàn)了一個(gè)工具:https://github.com/madmaze/pytesseract
拿來(lái)試了一下邑闺,Windows 上使用總是有問(wèn)題
我就把目光轉(zhuǎn)向了 tesseract 本身跌前,這是它的使用說(shuō)明
C:\Program Files\Tesseract-OCR>tesseract
Usage:
tesseract --help | --help-psm | --version
tesseract --list-langs [--tessdata-dir PATH]
tesseract --print-parameters [options...] [configfile...]
tesseract imagename|stdin outputbase|stdout [options...] [configfile...]
OCR options:
--tessdata-dir PATH Specify the location of tessdata path.
--user-words PATH Specify the location of user words file.
--user-patterns PATH Specify the location of user patterns file.
-l LANG[+LANG] Specify language(s) used for OCR.
-c VAR=VALUE Set value for config variables.
Multiple -c arguments are allowed.
-psm NUM Specify page segmentation mode.
NOTE: These options must occur before any configfile.
Page segmentation modes:
0 Orientation and script detection (OSD) only.
1 Automatic page segmentation with OSD.
2 Automatic page segmentation, but no OSD, or OCR.
3 Fully automatic page segmentation, but no OSD. (Default)
4 Assume a single column of text of variable sizes.
5 Assume a single uniform block of vertically aligned text.
6 Assume a single uniform block of text.
7 Treat the image as a single text line.
8 Treat the image as a single word.
9 Treat the image as a single word in a circle.
10 Treat the image as a single character.
Single options:
-h, --help Show this help message.
--help-psm Show page segmentation modes.
-v, --version Show version information.
--list-langs List available languages for tesseract engine.
--print-parameters Print tesseract parameters to stdout.
最后就決定自己實(shí)現(xiàn)一個(gè)簡(jiǎn)單的接口
使用方法
ocr = Ocr(r'C:\Program Files\Tesseract-OCR')
# 本地圖片
result = ocr.exec(img_path=r"e:\python\pyocr\images\1.png")
# 網(wǎng)絡(luò)圖片
result = ocr.exec(img_url="http://oog4yfyu0.bkt.clouddn.com/2.jpg")
print(result)
對(duì)參數(shù)解釋一下
def __init__(self, ocr_path, out_path=None, mode=3, delete=True):
"""
ocr_path:
tesseract 引擎的安裝路徑,例如我的 r'C:\Program Files\Tesseract-OCR'
out_path:
輸出文件路徑陡舅,如果只是簡(jiǎn)單為了獲取解析出來(lái)的數(shù)字抵乓,可不管,默認(rèn)地址為 r"D:\result.txt"
mode:
圖片的切割模式靶衍,參見(jiàn) tesseract 使用方法灾炭,默認(rèn)為 3
delete:
是否保留生成的文本文件,默認(rèn)不保存
"""
def exec(self, *, img_path="", img_url=None):
""" 執(zhí)行命令
img_path:
本地圖片路徑颅眶,如 r"e:\python\pyocr\images\1.png"
img_url:
網(wǎng)絡(luò)圖片地址蜈出,如 "http://oog4yfyu0.bkt.clouddn.com/2.jpg"
"""
具體思路
本地圖片的,先判斷該文件是否存在涛酗;網(wǎng)絡(luò)圖片的铡原,下載到本地,默認(rèn)的保存路徑是 r"D:\img.jpg" (保存在哪不重要商叹,只是暫存而已燕刻,解析完會(huì)自動(dòng)刪除的)
img = r"D:\img.jpg"
if os.path.exists(img_path):
img = img_path
else:
try:
request.urlretrieve(img_url, img)
except Exception as e:
print(e)
接下來(lái)是一些非必要參數(shù)
# 默認(rèn)的文本文件存放路徑為 r"D:\result"(這個(gè)也不重要,程序結(jié)束也會(huì)自動(dòng)刪除)
if self._outpath is None:
self._outpath = r"D:\result"
# tesseract 在執(zhí)行的時(shí)候剖笙,輸出文件路徑不需要帶 .txt 后綴酌儒,它自己會(huì)生成的。
elif self._outpath.endswith(".txt"):
self._outpath = self._outpath[:-4]
# 這個(gè)是模式選擇枯途,如果模式非法設(shè)置為默認(rèn)的 3
if self._mode > 10 or self._mode < 0:
self._mode = 3
接下來(lái)就是執(zhí)行命令
# 當(dāng)前目錄切換到引擎安裝路徑
os.chdir(self._ocrpath)
# 拼裝命令
cmd = r'tesseract.exe {img} {out} -psm {mode}'.\
format(img=img, out=self._outpath, mode=self._mode)
# 執(zhí)行命令
os.system(cmd)
# 讀取解析結(jié)果
try:
with open(self._outpath + ".txt", "r") as f:
result = f.read().strip()
# 刪除臨時(shí)存儲(chǔ)文件
if self._delete:
os.remove(self._outpath + ".txt")
os.remove(r"D:\img.jpg")
# 將結(jié)果返回
return result
except IOError:
print("無(wú)法找到該文件!")
return None
至于為什么只是數(shù)字忌怎,是因?yàn)橛⑽牡目偸遣荒芡耆馕龀鰜?lái),修改了 -l 參數(shù)也是沒(méi)用酪夷,使用其自帶的 tessdata 也沒(méi)用榴啸,中文的話(huà)解析出來(lái)的內(nèi)容完全看不懂... (或許是我打開(kāi)方式不對(duì)?)
效果
C:\Users\54186\Anaconda3\python.exe E:/Python/pyocr/ocr.py
Tesseract Open Source OCR Engine v3.05.00dev with Leptonica
5108
C:\Users\54186\Anaconda3\python.exe E:/Python/pyocr/ocr.py
Tesseract Open Source OCR Engine v3.05.00dev with Leptonica
4893
C:\Users\54186\Anaconda3\python.exe E:/Python/pyocr/ocr.py
Tesseract Open Source OCR Engine v3.05.00dev with Leptonica
130768
溫馨提示:不能保證百分百正確晚岭,也不能保證百分百解析得出來(lái)鸥印。所以項(xiàng)目?jī)H供參考!!库说!要有保證的話(huà)還是找打碼平臺(tái)吧
具體代碼參見(jiàn) Github:https://github.com/chenjiandongx/pyocr