安裝tesseract并添加到系統PATH
Python3 pytesseract識别簡單的驗證碼,JPEG格式,驗證碼樣式如下:
![]()
Python3 pytesseract識别簡單的驗證碼 ![]()
Python3 pytesseract識别簡單的驗證碼 ![]()
Python3 pytesseract識别簡單的驗證碼
此驗證碼比較簡單,是以簡單二值化處理,然後使用pytesseract識别即可達到不錯的識别率。
# -*- coding: utf-8 -*-
from PIL import Image
import pytesseract
class Captcha:
def __init__(self):
pass
# 識别圖檔驗證碼,并傳回驗證碼的字元串
def get_captcha_str(self, img_path):
"""
識别驗證碼
:param self:
:param img_path: 圖檔位址
"""
# 使用Image打開該圖檔
image = Image.open(img_path)
# 二值化處理,這個門檻值為R=18,G=16,B=18 低于閥值為黑色 否則為白色
pix = image.load() # 轉換為像素
for y in range(image.size[1]):
for x in range(image.size[0]):
if pix[x, y][0] < 18 or pix[x, y][1] < 16 \
or pix[x, y][2] < 18:
pix[x, y] = (0, 0, 0)
else:
pix[x, y] = (255, 255, 255)
# 顯示該圖檔,實際使用中請注釋
image.show()
# 開始識别
captcha_str = pytesseract.image_to_string(image)
# 去除空格
captcha_str = captcha_str.replace(' ', '')
# 去除非英文字元
captcha_str = filter(str.isalpha, captcha_str)
captcha_str = str(''.join(list(captcha_str)))
# 傳回前四個字元
return captcha_str[0:4]
captcha = Captcha()
captcha_str = captcha.get_captcha_str('./captcha.jpeg')
print(captcha_str)