Python3-圖片驗(yàn)證碼轉(zhuǎn)換為文字

一、使用pytesseract轉(zhuǎn)換

安裝方法:

pip install pytesseract

示例如下:
pytesseract.image_to_string(這里傳驗(yàn)證碼圖片)

二、使用tesseract_ocr轉(zhuǎn)換

安裝方法:

pip install tesseract_ocr

示例如下:
tesseract_ocr.text_for_filename(這里傳驗(yàn)證碼圖片)

三、使用tesseract轉(zhuǎn)換

安裝方法:

brew install tesseract

示例如下:

from selenium import webdriver
from PIL import Image
from PIL import ImageOps
import subprocess

try:
    path = '/Users/dawei/Downloads/captcha.png' # 驗(yàn)證碼圖片路徑
    resultTxtPath = '"/Users/dawei/Downloads/captcha"' # 識(shí)別后的圖片驗(yàn)證碼內(nèi)容路徑(不包含擴(kuò)展名)

    wd = webdriver.Firefox()  # 創(chuàng)建火狐
    wd.get('http://www.bycoming.com/hrd/hrd_login.do') # 打開(kāi)登錄頁(yè)
    wd.save_screenshot(path) # 保存截圖

    # 從截圖中裁剪驗(yàn)證碼圖片
    img = Image.open(path)
    loc = wd.find_element_by_id('img_code').location # 獲取驗(yàn)證碼圖片的位置
    size = wd.find_element_by_id('img_code').size # 獲取驗(yàn)證碼圖片的大小
    box = (loc['x'], loc['y'], float(loc['x']) + float(size['width']), float(loc['y']) + float(size['height']))
    img = img.crop(box) # 裁剪出驗(yàn)證碼圖片
    img.save(path) # 保存驗(yàn)證碼圖片

    img = img.point(lambda x: 0 if x < 143 else 255)  # 處理圖片上的每個(gè)像素點(diǎn),使圖片上每個(gè)點(diǎn)“非黑即白”
    borderImage = ImageOps.expand(img, border=20, fill='white')
    borderImage.save(path)


    p = subprocess.Popen(["tesseract", path, resultTxtPath], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.wait()
    f = open("/Users/dawei/Downloads/captcha.txt", "rb")
    b = f.read()
    s = b.decode()
    print('識(shí)別結(jié)果:', s.replace('\n', '').replace(' ', ''))
except:
    print('except!')
finally:
    print('finally!')
    wd.quit()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容