使用百度云识别图片中的文字(二):获取图片中的文字
上一篇文章中提到怎样获取access_token。此篇文章就是通过access_token来识别图片中的文字。
先来看看:官方的介绍吧:
本文档主要针对API开发者,描述百度OCR文字识别接口服务的相关技术内容。如果您对文档内容有任何疑问,可以通过以下几种方式联系我们:
在百度云控制台内提交工单,咨询问题类型请选择人工智能-文字识别;
关注公众号“百度OCR文字识别”(同时能及时获取接口升级等信息)
百度AI社区–文字识别官方版块:http://ai.baidu.com/forum/topic/list/164
具有免费调用额度的接口,超过每天的免费额度后会返回错误码:17,错误信息:Open api daily request limit reached(每天流量超限额);
所有图片均需要base64编码、去掉编码头后再进行urlencode。
请注意:上传的图片使用JPG格式可以一定程度上提高识别准确率!
强烈建议:如果您使用OCR的服务,请从文字识别的控制台进入并创建应用
注意!请拒绝使用任何第三方插件使用百度OCR服务
使用第三方非法插件会导致您的AK SK泄露,导致别人可以盗用您的账户进行任意消费! 切勿使用任何第三方插件! 因此导致的账号泄露、恶意消费,请用户自行承担责任。如果您已经使用了相关的插件,建议您立即删除对应appid、更换账户密码、更新所有appid的token,或更换账号!
接口能力
接口名称 接口能力简要描述
通用文字识别 对各类通用场景、文件的识别接口,按行返回识别结果
详情请看:https://ai.baidu.com/docs#/OCR-API/e1bd77f3
coding
需要识别的图片:
代码如下:
import urllib3,base64
from urllib.parse import urlencode
import json
access_token='你的access_token'
#需要一个PoolManager实例来生成请求,由该实例对象处理与线程池的连接以及线程安全的所有细节,不需要任何人为操作:
http=urllib3.PoolManager()
url='https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token='+access_token
f = open('test001.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')
#对结果进行格式化,方便查看
result = json.dumps(json.loads(result), indent=4, sort_keys=False, ensure_ascii=False)
print(result)
结果如下:
{
"log_id": 6445553406230491283,
"words_result_num": 12,
"words_result": [
{
"location": {
"width": 125,
"top": 3,
"left": 17,
"height": 25
},
"words": "百度智能云"
},
{
"location": {
"width": 28,
"top": 58,
"left": 33,
"height": 14
},
"words": "总览"
},
{
"location": {
"width": 53,
"top": 104,
"left": 6,
"height": 15
},
"words": "产品服务"
},
{
"location": {
"width": 133,
"top": 142,
"left": 6,
"height": 20
},
"words": "百度机器学习BML"
},
{
"location": {
"width": 81,
"top": 182,
"left": 7,
"height": 19
},
"words": "9语音技术"
},
{
"location": {
"width": 78,
"top": 222,
"left": 7,
"height": 19
},
"words": "⊕人脸识别"
},
{
"location": {
"width": 84,
"top": 262,
"left": 4,
"height": 19
},
"words": "人体分析"
},
{
"location": {
"width": 79,
"top": 303,
"left": 9,
"height": 16
},
"words": "文字识别"
},
{
"location": {
"width": 83,
"top": 344,
"left": 5,
"height": 17
},
"words": "图像识别"
},
{
"location": {
"width": 80,
"top": 381,
"left": 6,
"height": 20
},
"words": "图像搜索"
},
{
"location": {
"width": 106,
"top": 421,
"left": 5,
"height": 21
},
"words": "e图像效果增强"
},
{
"location": {
"width": 105,
"top": 461,
"left": 5,
"height": 21
},
"words": "②自然语言处理"
}
]
}
对比结果,可知虽然有部分错误,但是基本全部识别出来了。
注意:
通过我的经验可知对于各种正常的文字字体基本上都可以正常识别,但是对于手写的识别就差强人意了。(公正的手写字体除外)