社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
【标签】 OCR API Python
data:2018-10-19 author:怡宝2号
【总起】通过url对百度文字识别API进行调用,语言为python2
登陆百度云
百度百度云,可以用百度贴吧、百度云的账号登陆
创建应用
在百度云控制台的左侧,选择文字识别
获取access_token
相当于进行用户验证,具体可看百度官网的API文档
文字识别中获取access_token示例代码
import urllib, urllib2, sys
import ssl
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【官网获取的AK】&client_secret=【官网获取的SK】'
request = urllib2.Request(host)
request.add_header('Content-Type', 'application/json; charset=UTF-8')
response = urllib2.urlopen(request)
content = response.read()
if (content):
print(content)
注意修改1. 应用的url;2. client_id; 3. client_secret
读取自己的图片,调用API进行识别
阅读官网的API文档,改变示例代码中的相关参数
官网通用文字识别(含位置信息版)的示例代码
# coding:utf-8
import urllib, urllib2, base64
access_token = '#####调用鉴权接口获取的token#####'
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=' + access_token
# 二进制方式打开图文件
f = open(r'########本地文件#######', '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
百度云开放了API、SDK等调用方式,且每天都有一定量的免费使用次数,可以:
[1] 百度API文档中心
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!