python利用百度API進行文字識別
阿新 • • 發佈:2019-02-09
首先需要在百度的AI中新建一個應用列表,獲取我們需要的API Key與Secret Key
按照百度官方API的demo,可以獲取到token_id
#client_id 為官網獲取的AK, client_secret 為官網獲取的SK host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ZCBYh4Ceho9BgOhovBNr7vO3&client_secret=*****************************' request = urllib.request.Request(host) request.add_header('Content-Type', 'application/json; charset=UTF-8') response = urllib.request.urlopen(request) content = response.read() if (content): print(content)
之後我們用python寫一個post請求,把我們的引數按照百度API的格式傳送給百度文字檢測的URL,就可以看到圖片中被檢測出的文字了
import urllib from urllib import parse import base64 import cv2 headers = { 'Content-Type': 'application/x-www-form-urlencoded', } postData = { 'image' : base64.b64encode(cv2.imencode('.jpg', cv2.imread('E:/pythonCode/175429.jpg'))[1]).decode(), #圖片 base64格式 'language_type': 'CHN_ENG', #中英雙語 'detect_direction': 'false', #文字方向 'detect_language': 'false', #語言 'probability': 'true', #判斷為目標文字的概率 } data = urllib.parse.urlencode(postData).encode('utf-8') req = urllib.request.Request(url='https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?' 'access_token=**********************', headers=headers, data = data) response = urllib.request.urlopen(req) # 通過get請求返回的文字值 print(response.read().decode('utf-8'))
返回結果如下: