【Python3-API】通用文字识别示例代码

时间:2022-04-28
本文章向大家介绍【Python3-API】通用文字识别示例代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Python3-urllib3-API通用OCR示例代码
  • AccessToken获取可以参考:http://ai.baidu.com/forum/topic/show/497663(Python3-urllib3示例)
  • Python安装

-----------------------------------------------------下面开始代码-----------------------------------------------------

  • Python3-API示例代码(通用文字识别)
'''
Created on 2018-1-25
通用文字识别-Python3 -API示例代码
@author: 小帅丶
'''
import urllib3,base64
from urllib.parse import urlencode
access_token='自己应用信息获取的access_token'
http=urllib3.PoolManager()
url='https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token='+access_token
f = open('F:/demo.jpg','rb')
#参数image:图像base64编码
img = base64.b64encode(f.read())
params={'image':img}
#对base64数据进行urlencode处理
params=urlencode(params)
request=http.request('POST', 
                      url,
                      body=params,
                      headers={'Content-Type':'application/x-www-form-urlencoded'})
#对返回的byte字节进行处理。Python3输出位串,而不是可读的字符串,需要进行转换
result = str(request.data,'utf-8')
print(result)
  • 返回的识别结果内容
{
    "log_id": 6101980364103585000, 
    "words_result_num": 1, 
    "words_result": [
        {
            "location": {
                "width": 146, 
                "top": 7, 
                "height": 17, 
                "left": 11
            }, 
            "words": "小帅开发者服务开发者"
        }
    ]
}
  • 原图文件

-----------------------------------------------------代码结束-----------------------------------------------------

确实发现Python简单。而且写的代码也很少。代码仅供参考。