进入百度识图网站百度识图
记住这两个Key
将要处理的图片转码
import base64
f=open("填写你的图片完整名称 例如:1.png","rb")
img = base64.b64encode(f.read())
下面通过上面的两个Key获取access_token,通过access_token就能调用Api啦
获取access_koken的链接
https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=你的API Key&client_secret=你的secret Key
完整代码
import requests
client_id='你的API Key'
client_secret='你的secret Key'
url= f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}'
response = requests.get(url)
if response:
access_token=(response.json()['access_token'])
访问识图的链接
https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=你的access_token
构造请求头
headers={
'Content-Type':'application/x-www-form-urlencoded'
}
因为要发送post请求所以要构造form-data
data={
'image':img
}
发送post请求
res = requests.post(url=host,headers=headers,data=data)
附上完整代码
import base64
import requests
f=open("1.png","rb")#将1.png改为你自己的图片名字
img = base64.b64encode(f.read())
client_id='你的API Key'
client_secret='你的secret Key'
url= f'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}'#构造URL
response = requests.get(url)
if response:
#返回是json类型的,类似于python的字典,可以直接通过key来获取value
access_token=(response.json()['access_token'])
host = f'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token={access_token}'
headers={
'Content-Type':'application/x-www-form-urlencoded'
}
data={
'image':img
}
res = requests.post(url=host,headers=headers,data=data)
list=res.json()['words_result']
for i in list:
print(i['words'])
新手上路,必然会有考虑不周的地方,望大佬斧正