1. 程式人生 > >爬蟲 - 用ocr來識別驗證碼

爬蟲 - 用ocr來識別驗證碼

open roc pen bre ocr mage 灰度 mode 證明

用OCR來識別
直接識別效果不好,因為驗證碼內的多余線條幹擾了圖片的識別。先轉為灰度圖像,再二值化。經實踐證明,該方法不是100%正確。

# 獲取圖片
curl -X GET http://my.cnki.net/elibregister/CheckCode.aspx

import tesserocr
from PIL import Image

image = Image.open(‘1.png‘)
# 轉為灰度圖像
image = image.convert(‘L‘)

threshold = 127
table = []

# 二值化
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
# mode=‘1‘默認的閥值為127
image = image.point(table, ‘1‘)
image.show()
result = tesserocr.image_to_text(image)
print(result)

爬蟲 - 用ocr來識別驗證碼