简 介:百度大脑是百度 AI 核心技术引擎,包括视觉、语音、自然语言处理、知识图谱、深度学习等AI核心技术和AI开放平台。本文介绍百度 AI 核心技术中文字识别功能的使用方法。
关键词
: 百度AI、文字识别、Python
§00 官方文档
若想详细学习百度 AI 核心技术引擎
,可参考下述链接:
§01 安装使用Python SDK
- 如果已安装pip,执行
pip install baidu-aip
即可。 - 如果已安装setuptools,执行
python setup.py install
即可。
![](https://img-blog.csdnimg.cn/0f52bc4461e24c2a9ad18bfb33719697.png#pic_center)
▲ 图1.1 安装baidu-aip
§02 AipOcr
一、新建AipOcr
AipOcr是OCR的Python SDK客户端,为使用OCR的开发人员提供了一系列的交互方法。
参考如下代码新建一个AipOcr:
from aip import AipOcr
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
在上面代码中,常量APP_ID
在百度智能云控制台中创建,常量API_KEY
与SECRET_KEY
是在创建完毕应用后,系统分配给用户的,均为字符串,用于标识用户,为访问做签名验证,可在AI服务控制台中的应用列表中查看。具体操作请查看 百度大脑|新手指南。
注意:如您以前是百度智能云的老用户,其中API_KEY
对应百度智能云的“Access Key ID”,SECRET_KEY
对应百度智能云的“Access Key Secret”。
二、配置AipOcr
如果用户需要配置AipOcr的网络请求参数(一般不需要配置),可以在构造AipOcr之后调用接口设置参数,目前只支持以下参数:
接口 | 说明 |
---|---|
setConnectionTimeoutInMillis | 建立连接的超时时间(单位:毫秒) |
setSocketTimeoutInMillis | 通过打开的连接传输数据的超时时间(单位:毫秒) |
§03 接口说明
详细介绍请查看文字识别接口说明,此处只对一些常用的功能(我用过的功能)简要介绍。
§04 问题汇总
一、识别失败
错误如下:Open api qps request limit reached
解决方法:
出现此错误说明要自己去 免费测试额度领取地址 领取免费的测试额度了!!!(或者你在你原来那个调用的那个项目里也可以找到免费领取测试额度,见下图)
![](https://img-blog.csdnimg.cn/aff9fbd6d3064030bac3967052038675.png#pic_center)
▲ 图4.1 领取测试额度
领取完之后,还是用原来项目的appID
,apiKey
,secretKey
即可,然后等领取额度到账后,重新运行就行了。
§05 应用举例
一、识别图片中的文字
在CSDN上写文章时,有时需要将图片中的文字提取出来,此例可实现此功能。
1、导入相关函数库
from aip import AipOcr
import pyautogui
import clipboard
import requests
aip
:即本文中所介绍的百度AI库,baidu-aip
pyautogui
:Python自动化控制鼠标和键盘操作—— PyAutoGUIclipboard
:Python的跨平台剪贴板操作库requests
:一个常用的用于http请求的模块,本例用其进行网络图片的爬取,从而实现网络图片文字识别。此库的具体用法见 Requests: HTTP for Humans™
2、百度Aip初始配置
def AipOcrInitSet():
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
return AipOcr(APPID, APPKEY, SECRETKEY)
APP_ID
,API_KEY
,SECRET_KEY
获取途径请查看 百度大脑|新手指南。
3、本地图片解析(用于本地图片文字识别)
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
4、网络图片解析(用于网络图片文字识别)
def getHTMLResponse(url):
#import urllib3
headers = {'User -Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3314.0 Safari/537.36 SE 2.X MetaSr 1.0'}
#proxy ={'http': '58.249.55.222:9797'} #proxies=proxy 代理
try:
#urllib3.disable_warnings()
r = requests.get(url, headers=headers, verify=False)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r
except:
return ""
5、文字识别相关函数
# 通用文字识别(本地图片)
def basicGeneral(filePath, options={}):
words = ''
image = get_file_content(filePath)
client = AipOcrInitSet()
message = client.basicGeneral(image,options);
for result in message['words_result']:
words += result['words'] + '\n'
return words
# 通用文字识别(网络图片)
def basicGeneralUrl(Url, options={}):
words = ''
image = getHTMLResponse(Url).content
client = AipOcrInitSet()
message = client.basicGeneral(image,options);
for result in message['words_result']:
words += result['words'] + '\n'
return words
# 通用文字识别(高精度版)(本地图片)
def basicAccurate(filePath, mode='w', options={}):
words = ''
image = get_file_content(filePath)
client = AipOcrInitSet()
message = client.basicAccurate(image,options);
for result in message['words_result']:
words += result['words'] + '\n'
return words
# 通用文字识别(高精度版)(网络图片)
def basicAccurateUrl(Url, mode='w', options={}):
words = ''
image = getHTMLResponse(Url).content
client = AipOcrInitSet()
message = client.basicAccurate(image,options);
for result in message['words_result']:
words += result['words'] + '\n'
return words
6、主程序
# 获取剪切板内容
clipboardstr = clipboard.paste()
# 剪切板内容解析
if '![在这里插入图片描述](https:' in clipboardstr.strip():
clipboardstr = clipboardstr.split('![在这里插入图片描述](')[1]
clipboardstr = clipboardstr.split('.png')[0] + '.png'
clipboardstr = 'u ' + clipboardstr
# 命令、文本分离
clipboardstr = clipboardstr.strip()
cmdstr = clipboardstr.split()[0] # 命令行(决定输出格式)
txtstr = " ".join(clipboardstr.split()[1:]) # 文本
# 百度aip初始配置
options = {}
options["language_type"] = "CHN_ENG"
# 根据相应命令调用对应的百度aip
if cmdstr == 'u':
Url = txtstr
word = basicAccurateUrl(Url, options = options)
elif cmdstr == 'f':
PicPath = txtstr
word = basicAccurate(PicPath, options = options)
else:
word = clipboardstr
# 输出
clipboard.copy(word)
pyautogui.hotkey('alt', 'tab')
pyautogui.hotkey('ctrl', 'v')