首先需要在百度的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'))
返回结果如下: