# encoding:utf-8
import requests
import base64
import json
'''
通用文字识别
'''
request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
# 二进制方式打开图片文件
#f = open('/home/cnliutz/微21.jpg', 'rb') 要识别的图片放这里。
f = open('/home/cnliutz/微信图片_20200724140210.jpg', 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = '24.d4c2ebf5af97dd3dde655eabf3a22e2f.2592000.1598160343.282335-215715one.seven' #生成的签名 利用百度智能云-文字识别-技术文档里的方法产生。
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
if response:
print (response.json())
results=response.json()
with open('shibiejieguo.txt',"w",encoding="utf-8") as f:
for i in results['words_result']:
f.write(i["words"]+"\n")
注意修改access_token内容,否则无法使用呢
参考网址:https://cloud.baidu.com/doc/OCR/s/dk3iqnq51
【只要10分钟 快速掌握文字识别】 教程
参考网址:https://ai.baidu.com/forum/topic/show/867951
#文字识别另一种调用方法
# 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 = 'dGgWcprUfQBHKM5UG2CdSzot'
SECRET_KEY = '3Gqe5MkzUdONgtppDceUutRGdpF7MVkU'
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('/home/cnliutz/微21.jpg')
# 调用文字识别服务
result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
# 解析返回结果
result_json = json.loads(result)
with open('shibiejieguo.txt',"a",encoding="utf-8") as f:
for words_result in result_json["words_result"]:
text = text + words_result["words"]
f.write(words_result["words"])
# 打印文字
print(text)