識別驗證碼之百度通用識別接口


在識別驗證碼的時候,可以調用百度的通用文字識別接口。

步驟

Step1 獲取access_token的值。

① 登陸 https://ai.baidu.com/ ,找到通用文字識別,點擊立即使用。

② 點擊創建應用后,會得到API KeySecret Key

③ 將API Key 和Secret Key寫入如下代碼中,得到 access_token 的值。

1 # encoding:utf-8
2 import requests 
3 
4 # client_id 為官網獲取的AK, client_secret 為官網獲取的SK
5 host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官網獲取的AK】&client_secret=【官網獲取的SK】'
6 response = requests.get(host)
7 if response:
8     print(response.json())

 

Step2 調用通用文字識別接口

  將得到的 access_token 值下載到本地的驗證碼圖片名寫入如下代碼中,就可以獲取識別結果。

 1 # encoding:utf-8
 2 
 3 import requests
 4 import base64
 5 
 6 '''
 7 通用文字識別
 8 '''
 9 
10 request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
11 # 二進制方式打開圖片文件
12 f = open('[本地文件]', 'rb')
13 img = base64.b64encode(f.read())
14 
15 params = {"image":img}
16 access_token = '[調用鑒權接口獲取的token]'
17 request_url = request_url + "?access_token=" + access_token
18 headers = {'content-type': 'application/x-www-form-urlencoded'}
19 response = requests.post(request_url, data=params, headers=headers)
20 if response:
21     print (response.json())

 

完整代碼如下

 1 def identify_Verification_code(API_Key,Secret_Key,Verification_code):
 2     #獲取Access Token官方代碼,必須要有API Key和Secret Key兩個參數才能獲取。
 3     import requests
 4 
 5     host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ API_Key + '&client_secret=' + Secret_Key
 6     response = requests.get(host)
 7     access_token = response.json()['access_token']
 8 
 9     #通用文字識別官方代碼
10     import base64
11     request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
12     # 二進制方式打開圖片文件,Verification_code是要識別的驗證碼的名字
13     f = open(Verification_code, 'rb')
14     img = base64.b64encode(f.read())
15 
16     params = {"image":img}
17     access_token = access_token
18     request_url = request_url + "?access_token=" + access_token
19     headers = {'content-type': 'application/x-www-form-urlencoded'}
20     response = requests.post(request_url, data=params, headers=headers)
21     shibie_result = response.json()['words_result'][0]['words']
22     print(shibie_result)
23 
24 if __name__ == '__main__':
25     API_Key = '***'
26     Secret_Key = '***'
27     Verification_code = '驗證碼.png'
28     identify_Verification_code(API_Key,Secret_Key,Verification_code)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM