1. 程式人生 > >【python 百度文字識別】通用文字識別(高精度版)

【python 百度文字識別】通用文字識別(高精度版)

效果展示:

效果非常好~~~~
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

建立應用
首先你需要登入百度AI,選擇文字識別,建立一個應用,會生成 應用名稱、AppID、API Key、Secret Key 這些東西,下面我們程式碼是需要用到API_Key 和 Secret_Key 生成access_token。

python程式碼:

# encoding: utf-8
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
time1 = time.time()
import urllib, urllib2, base64
import
json import re def get_token(API_Key,Secret_Key): # 獲取access_token host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+API_Key+'&client_secret='+Secret_Key request = urllib2.Request(host) request.add_header('Content-Type', 'application/json; charset=UTF-8'
) response = urllib2.urlopen(request) content = response.read() content_json=json.loads(content) access_token=content_json['access_token'] return access_token def recognition_word_high(filepath,filename,access_token): url='https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token='
+ access_token # 二進位制方式開啟圖檔案 f = open(filepath + filename, 'rb') # 二進位制方式開啟圖檔案 # 引數image:影象base64編碼 img = base64.b64encode(f.read()) params = {"image": img} params = urllib.urlencode(params) request = urllib2.Request(url, params) request.add_header('Content-Type', 'application/x-www-form-urlencoded') response = urllib2.urlopen(request) content = response.read() if (content): # print(content) world=re.findall('"words": "(.*?)"}',str(content),re.S) for each in world: print each if __name__ == '__main__': API_Key = "****************************" Secret_Key = "*****************************" filepath = "E:/ID/" filename="59.jpg" access_token=get_token(API_Key,Secret_Key) recognition_word_high=recognition_word_high(filepath,filename,access_token)