# encoding:utf-8# !/usr/local/bin/python3# 百度云:文字识别服务# 应用名称:文字识别练习项目import urllib3from urllib.parse import urlencodeimport urllibimport urllib.requestimport sysimport sslimport base64import json'''# 调用API前必须获取Access Token# client_id 为官网获取的AK, client_secret 为官网获取的SK# access_token: 要获取的Access Token;# expires_in: Access Token的有效期(秒为单位,一般为1个月);'''APPId = 17165172ApiKey = 'uck9A45flml7ITBQ8VaLUojf'SecretKey = 'p19Nl1Rz1DGGMKepK3lNDWk8TogqankG'host = '/oauth/2.0/token?grant_type=client_credentials&client_id='+ApiKey+'&client_secret='+SecretKeyrequest = 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) # 打印获取到的信息# 通过decode将bytes字节串转换为字符串strcontent = content.decode('utf-8')contentDict = json.loads(content)# 借助json函数将str转换为dictrefresh_token = contentDict["refresh_token"] # 直接读取dict字典内需要的数据expires_in = contentDict["expires_in"]session_key = contentDict["session_key"]access_token = contentDict["access_token"]scope = contentDict["scope"]session_secret = contentDict["session_secret"]#print(access_token)'''手写文字识别# 所有图片均需要base64编码、去掉编码头后再进行urlencode。'''request_url = "/rest/2.0/ocr/v1/handwriting" #手写文字识别接口imagePath = '/Users/zhaojichao/Desktop/ocrtest.jpg' # 测试100001f = open(imagePath, 'rb')# img为bytes类型img = base64.b64encode(f.read())# img为str类型img = img.decode('utf-8')params = {"image": img}#"recognize_granularity": "BASE64",#"words_type": "16_219"}# 对base64数据进行urlencode处理编码之后格式为strparams = urllib.parse.urlencode(params)# str转为可以提交的bytesparams = params.encode('utf-8')access_token = access_tokenrequest_url = request_url + "?access_token=" + access_tokenrequest = urllib.request.Request(url=request_url, data=params)request.add_header('Content-Type', 'application/x-www-form-urlencoded')response = urllib.request.urlopen(request)content = response.read()if content:# 返回数据为bytes,需要转换为strcontent = content.decode('utf-8')print(content)
如果觉得《【Python】调用百度云API文字识别服务 OCR》对你有帮助,请点赞、收藏,并留下你的观点哦!