基于百度AI的文字识别(Python语言)



简 介:百度大脑是百度 AI 核心技术引擎,包括视觉、语音、自然语言处理、知识图谱、深度学习等AI核心技术和AI开放平台。本文介绍百度 AI 核心技术中文字识别功能的使用方法。

关键词 百度AI、文字识别、Python

§00 方文档


  若想详细学习百度 AI 核心技术引擎,可参考下述链接:

§01 装使用Python SDK


  • 如果已安装pip,执行pip install baidu-aip即可。
  • 如果已安装setuptools,执行python setup.py install即可。
▲ 图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_KEYSECRET_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

  解决方法:

  出现此错误说明要自己去 免费测试额度领取地址 领取免费的测试额度了!!!(或者你在你原来那个调用的那个项目里也可以找到免费领取测试额度,见下图)

▲ 图4.1 领取测试额度

  领取完之后,还是用原来项目的appIDapiKeysecretKey即可,然后等领取额度到账后,重新运行就行了。

§05 用举例


一、识别图片中的文字

  在CSDN上写文章时,有时需要将图片中的文字提取出来,此例可实现此功能。

1、导入相关函数库

from aip import AipOcr
import pyautogui
import clipboard
import requests

2、百度Aip初始配置

def AipOcrInitSet():
	APP_ID = '你的 App ID'
	API_KEY = '你的 Api Key'
	SECRET_KEY = '你的 Secret Key'
    return AipOcr(APPID, APPKEY, SECRETKEY)

   APP_IDAPI_KEYSECRET_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')
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43964993

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值