1. 程式人生 > >Python呼叫百度手寫識別API,將手寫筆記圖片轉換成文字

Python呼叫百度手寫識別API,將手寫筆記圖片轉換成文字

  • 事件起因

家裡人有十幾頁手寫筆記想要轉成文字格式。網上搜了一下發現了百度有手寫文字圖片識別的api,於是拿來試試。
雖然最終效果並不理想,還是當做一次測試記錄一下。
手裡有手寫筆記想要識別一下,也可以直接參考下面程式碼試試。

  • 程式碼

程式碼部分沒什麼好解釋的
get_file_content()讀取圖片
get_access_token()你的百度開發者訪問token
recognise_handwriting_pic()呼叫百度圖片識別API,識別手寫文字
最下面的for迴圈實際上就是逐個圖片上傳識別,輸出結果。

import requests
import
json import base64 def get_file_content(filePath): """ 讀取圖片base64 """ with open(filePath, 'rb') as fp: return base64.b64encode(fp.read()) def get_access_token(): # API_Key,Secret_Key 需要在 https://console.bce.baidu.com/ai/?fromai=1#/ai/ocr/app/list 建立應用才能獲得 API_Key = '你的API_Key' Secret_Key = '你的Secret_Key'
r = requests.post('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_Key+'&client_secret='+Secret_Key) print(r.text) j = json.loads(r.text) print(j.get('access_token')) def recognise_handwriting_pic(access_token,image_path): image = get_file_content(image_path)
r = requests.post( url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting?access_token='+access_token, headers={"Content-Type":"application/x-www-form-urlencoded"}, data = {'image':image}) #print(r.text) j = json.loads(r.text) words_result = j.get('words_result') for i in words_result: print(i.get('words')) access_token = get_access_token() # 獲取一次儲存下來就夠了,一般1個月有效期 print(access_token) for p in range(1,25): print('\n\n%s\n\n第%d頁'%(' *'*20,p)) recognise_handwriting_pic(access_token,image_path='C:/Users/kindle/Desktop/wzsb/'+str(p)+'.jpg')
  • 手寫圖片示例

手寫圖片示例

  • 識別結果

品種是工藝害.花色變化了
造型
巖物
無裝飾設計先花敵”,是說不通紙,彩鷗無花你是鄙7
  • 結論

上面挑出來這張圖,已經算是本次測試十幾張圖片中識別的不錯的了,
總體而言,很可能你花在校對的時間會比你純手打一遍還要長。
看來如果寫的不是很標準,識別的出來的效果比較一般。
還有很多需要改進的地方。
嘛,這個功能也是剛剛上線測試,就不過多評論了。

PS:家人手中十幾頁手稿,因冷懶得打字。給其找了個語言錄入APP,朗讀了一遍,然後校對一下,結束。