一、注册账号
地址:https://ai.baidu.com/tech/ocr/general?track=cp:aipinzhuan|pf:pc|pp:AIpingtai|pu:2-2||kw:10005804
二、搜索文字识别
三、点击进入文字识别后创建应用
四、随便输入应用名称、点击不需要、点击个人、随便输入应用描述,点击创建
五、创建成功后点击管理应用会显示AppID、API Key和Secret Key
六、点击左侧的技术文档
七、点击快速入门
八、快速入门有一个python版的demo,只需改一些配置就可以进行文字识别了
demo只能识别一张图片,我已经将demo改成了可以识别多张图片。
附代码:
# coding=utf-8import sysimport jsonimport base64import time# 保证兼容python2以及python3IS_PY3 = sys.version_info.major == 3if 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_pluselse: 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 sslssl._create_default_https_context = ssl._create_unverified_contextAPI_KEY = '改成自己的'SECRET_KEY = '改成自己的'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__': for num in range(1,6): # 获取access token token = fetch_token() # 拼接通用文字识别高精度url image_url = OCR_URL + "?access_token=" + token text = "" #这里改成自己的路径。关键帧是文件夹名,和本python文件同级,关键帧文件夹里面是图片 path="./关键帧/%d"%(num) jpg=".jpg"#图片是jpg格式,可以改成其他格式 a=path+jpg file_content = read_file(a) # 调用文字识别服务 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) #打印当前时间 (time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime())) #空行 print ("nnn")九、其他
我之前找了很多篇用百度OCR进行文字识别的文章,大部分文章都是有代码的,可惜没有一个能够运行。这些代码都是报同一种错误:KeyError: 'words_result'。百度上也鲜有解释,有人说这可能是用了别人的API Key和Secret Key导致的错误,要用自己的。但是我用了自己的依然出错,索性就将那些代码舍弃了,开始看官方文档,结果给了我一个大大的惊喜:有demo。我花了一些时间将识别单张图片的demo改成了识别多张图片。
像语音识别、人脸识别等技术都应该先看官方文档,一般都有demo,有了错误再看其他的一些文章。