1. 程式人生 > >Python實現簡單驗證碼的轉文字

Python實現簡單驗證碼的轉文字

宣告:本文章中的驗證碼爬取和識別僅用作試驗!

1.首先就是驗證碼的爬取,這裡我爬取的是學校oj的註冊驗證碼。背景基本沒有噪聲,容易處理。

2.在獲得驗證碼圖片的二進位制資料後,我們使用以下程式碼實現對圖片的本地儲存:

def save_img(content):
    '''
    os.getcwd()方法用於返回當前的工作目錄;
    md(content).hexdigest()根據圖片的二進位制程式碼產生md5碼;
    wb為寫入二進位制資料
    '''
    file_path = '{0}/{1}.{2}'.format(os.getcwd(), md5(content).hexdigest(), 'jpg')
    print(file_path)
    if not os.path.exists(file_path):
        with open(file_path, 'wb') as f:
            f.write(content)
            f.close()

3.使用BytesIO對二進位制檔案進行封裝,並用Image.open()開啟。

def picture_to_string(content):
	#使用BytesIO對二進位制進行封裝
	file_like = BytesIO(content)
	img = Image.open(file_like)
	return img

4.圖片轉文字

def get_string(img):
	#轉化為灰度
	gray = img.convert('L')
	#二值化演算法,閾值為140
	out = get_bin_table(gray,140)
	#儲存處理後的圖片
	out.save('example','png')
	#使用pytesseract.image_to_string()方法提取處理後圖片的文字
	word = pytesseract.image_to_string(out)
	ascii_word = ''.join(c for c in word if c in string.ascii_letters or c in string.digits)
	return ascii_word

5.效果