# -*- coding:UTF-8 -*-
# -*- encoding: utf-8 -*-
import base64
import requests
from urllib.parse import quote
headers = {
'Content-Type': "application/x-www-form-urlencoded",
'charset': "utf-8"
}
if __name__ == '__main__':
recognise_api_url = "https://aip.baidubce.com/rest/2.0/solution/v1/iocr/recognise"
access_token = "mytoken"
templateSign = "c405e86ebc3daa9b04ae9d57ddd68c09"
classifierId = "your_classifier_id"
# 测试数据路径
image_path = "w2.jpeg"
try:
with open(image_path, 'rb') as f:
image_data = f.read()
image_b64 = base64.b64encode(image_data).replace("\r", "")
# 请求模板的bodys
recognise_bodys = "access_token=" + access_token + "&templateSign=" + templateSign + \
"&image=" + quote(image_b64.encode("utf8"))
# 请求分类器的bodys
classifier_bodys = "access_token=" + access_token + "&classifierId=" + classifierId + \
"&image=" + quote(image_b64.encode("utf8"))
# 请求模板识别
response = requests.post(recognise_api_url, data=recognise_bodys, headers=headers)
# 请求分类器识别
# response = requests.post(recognise_api_url, data=classifier_bodys, headers=headers)
print(response.text)
except Exception as e:
测试报错:a bytes-like object is required, not 'str'
请各位大神帮看一下问题出在哪里,不是已经转换bytes了吗 怎么还报这个错,并且这代码是官方写好的示例
同学你好,已经修改了文档里的示例代码,现在能支持 py2 和 py3,文档地址:
https://ai.baidu.com/ai-doc/OCR/Ek3h7y961
感谢你的提问
示例是py2的版本,这可能也是原因之一,看下报错修改下即可运行。
image_b64 = base64.b64encode(image_data).replace("\r", "")
更换成这个,image_b64 = base64.b64encode(image_data).decode().replace("\r", "")
示例的image_b64编码后是bytes,但replace的对象必须是str
python版本是3.X