1. 程式人生 > >百度OCR驗證碼識別連線

百度OCR驗證碼識別連線

百度OCR驗證碼識別連線
+
簡單的圖片灰度化處理

#

from aip import AipOcr
from PIL import Image

""" 你的 APPID AK SK """
APP_ID = 'xxxxx'
API_KEY = 'xxxxxxxxxx'
SECRET_KEY = 'xxxxxxxxxxxxxx '

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 讀取圖片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

#定義引數變數
options = {
    "recognize_granularity" :"big",
    "detect_direction": "true",
}


image = Image.open(r'C:\Users\Administrator\Desktop\7708.jfif')
# image=PIL.Image.open(r"C:\Users\Administrator\Desktop\5107.jfif")

# 灰度化
image = image.convert('L')
# 雜點清除掉。只保留黑的和白的。返回畫素物件
data = image.load()
w, h = image.size
for i in range(w):
    for j in range(h):
        if data[i, j] > 125:
            data[i, j] = 255  # 純白
        else:
            data[i, j] = 0  # 純黑
image.save('clean_captcha.png')

# image2 = get_file_content(r'C:\Users\Administrator\Desktop\7708.jfif')
image2 = get_file_content('clean_captcha.png')
# print(image2)

""" 呼叫數字識別 """
result= client.numbers(image2)


# for key in result:
#     print(key,result[key])

print(result["words_result"][0]["words"])
""" 如果有可選引數 """
# options = {}
# options["recognize_granularity"] = "big"

# options["detect_direction"] = "true"

""" 帶引數呼叫數字識別 """
client.numbers(image2, options)