文字识别ocr-奇异果体育app竞彩官网下载
更新时间:2021-12-31
如何使用代码调用文字识别服务 api
本文提供了通过代码快速调用 ocr 通用文字识别(高精度版)api 的样例,帮助您通过简单的编码编写快速熟悉并使用文字识别服务。视频教程请参见。
1. 准备开发环境
我们选择用 python 来快速搭建一个原型,关于如何安装 python。可以参考下表列出的不同操作系统的安装方法进行安装。
python的官方下载地址:
windows 快速测试包
windows 平台的用户如果对上述的 python 安装感到困难,您可以下载我们的一键测试包,下载地址:。
解压 zip 文件后,双击 run.bat 即可测试。
2. 编写代码
新建一个 main.py
粘贴以下内容,不要忘记替换您的 api_key 以及 secret_key:
# coding=utf-8
import sys
import json
import base64
# 保证兼容python2以及python3
is_py3 = sys.version_info.major == 3
if is_py3:
from urllib.request import urlopen
from urllib.request import request
from urllib.error import urlerror
from urllib.parse import urlencode
from urllib.parse import quote_plus
else:
import urllib2
from urllib import quote_plus
from urllib2 import urlopen
from urllib2 import request
from urllib2 import urlerror
from urllib import urlencode
# 防止https证书校验不正确
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
api_key = 'gmhc18evp1fo1ecx911dtozw'
secret_key = 'pq2uko4aec2ptsgqu9ukiekyciavlzk8'
ocr_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
""" token start """
token_url = 'https://aip.baidubce.com/oauth/2.0/token'
"""
获取token
"""
def fetch_token():
params = {'grant_type': 'client_credentials',
'client_id': api_key,
'client_secret': secret_key}
post_data = urlencode(params)
if (is_py3):
post_data = post_data.encode('utf-8')
req = request(token_url, post_data)
try:
f = urlopen(req, timeout=5)
result_str = f.read()
except urlerror as err:
print(err)
if (is_py3):
result_str = result_str.decode()
result = json.loads(result_str)
if ('access_token' in result.keys() and 'scope' in result.keys()):
if not 'brain_all_scope' in result['scope'].split(' '):
print ('please ensure has check the ability')
exit()
return result['access_token']
else:
print ('please overwrite the correct api_key and secret_key')
exit()
"""
读取文件
"""
def read_file(image_path):
f = none
try:
f = open(image_path, 'rb')
return f.read()
except:
print('read image file fail')
return none
finally:
if f:
f.close()
"""
调用远程服务
"""
def request(url, data):
req = request(url, data.encode('utf-8'))
has_error = false
try:
f = urlopen(req)
result_str = f.read()
if (is_py3):
result_str = result_str.decode()
return result_str
except urlerror as err:
print(err)
if __name__ == '__main__':
# 获取access token
token = fetch_token()
# 拼接通用文字识别高精度url
image_url = ocr_url "?access_token=" token
text = ""
# 读取测试图片
file_content = read_file('./text.jpg')
# 调用文字识别服务
result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
# 解析返回结果
result_json = json.loads(result)
for words_result in result_json["words_result"]:
text = text words_result["words"]
# 打印文字
print(text)
3. 运行代码
在命令行中运行python main.py
4. 获取识别结果
代码正确运行后,命令行界面上会显示出如下运行结果:
返回的数据包含了图片中所有文字,详细的接口返回可以查看文档 。