安装Python SDK
sudo pip3 install baidu-aip
调用API识别本地图片
from aip import AipOcr
"""定义常量"""
APP_ID = '19854954'
API_KEY = 'tloxML8vTIeuGsHuWZESGdYF'
SECRET_KEY = '*******'
"""初始化对象"""
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
"""读取图片"""
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('本地图片位置绝对路径')
"""调用通用文字识别接口, 识别本地图像"""
result = client.basicGeneral(image)
print(result)
# 打印每行文字
for item in res['words_result']:
print(item['words'])
# 将每行文字拼接成一个整体
string_text = ""
for item in result['words_result']:
string_text += item['words']
print('string_text:', string_text)
常用接口说明
通用文字识别 client.basicGeneral(image)
通用文字识别(含位置信息版)client.general(image)
通用文字识别(高精度版)client.basicAccurate(image)
通用文字识别(高精度含位置版)client.accurate(image)
通用文字识别(含生僻字版)client.enhancedGeneral(image)
网络图片文字识别 client.webImage(image)
实例化时的可选参数
# 如果有可选参数
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"
调用API识别url上的图片
from aip import AipOcr
"""定义常量"""
APP_ID = '19854954'
API_KEY = 'tloxML8vTIeuGsHuWZESGdYF'
SECRET_KEY = '*******'
"""初始化对象"""
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
""" 带参数调用通用文字识别, 图片参数为远程url图片 """
url = "http://xxxxxxxx"
# 如果有可选参数
options = {}
options["language_type"] = "CHN_ENG"
options["detect_direction"] = "true"
options["detect_language"] = "true"
options["probability"] = "true"
reusult = client.basicGeneralUrl(url, options)
print(result)
# 打印每行文字
for item in res['words_result']:
print(item['words'])