当前位置:   article > 正文

百度OCR文字识别教程(有demo)_ocr baidu demo

ocr baidu demo

一、注册账号

地址: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改成了可以识别多张图片。

附代码:

  1. # coding=utf-8
  2. import sys
  3. import json
  4. import base64
  5. import time
  6. # 保证兼容python2以及python3
  7. IS_PY3 = sys.version_info.major == 3
  8. if IS_PY3:
  9.     from urllib.request import urlopen
  10.     from urllib.request import Request
  11.     from urllib.error import URLError
  12.     from urllib.parse import urlencode
  13.     from urllib.parse import quote_plus
  14. else:
  15.     import urllib2
  16.     from urllib import quote_plus
  17.     from urllib2 import urlopen
  18.     from urllib2 import Request
  19.     from urllib2 import URLError
  20.     from urllib import urlencode
  21. # 防止https证书校验不正确
  22. import ssl
  23. ssl._create_default_https_context = ssl._create_unverified_context
  24. API_KEY = '改成自己的'
  25. SECRET_KEY = '改成自己的'
  26. OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
  27. """  TOKEN start """
  28. TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'
  29. """
  30.     获取token
  31. """
  32. def fetch_token():
  33.     params = {'grant_type': 'client_credentials',
  34.               'client_id': API_KEY,
  35.               'client_secret': SECRET_KEY}
  36.     post_data = urlencode(params)
  37.     if (IS_PY3):
  38.         post_data = post_data.encode('utf-8')
  39.     req = Request(TOKEN_URL, post_data)
  40.     try:
  41.         f = urlopen(req, timeout=5)
  42.         result_str = f.read()
  43.     except URLError as err:
  44.         print(err)
  45.     if (IS_PY3):
  46.         result_str = result_str.decode()
  47.     result = json.loads(result_str)
  48.     if ('access_token' in result.keys() and 'scope' in result.keys()):
  49.         if not 'brain_all_scope' in result['scope'].split(' '):
  50.             print ('please ensure has check the  ability')
  51.             exit()
  52.         return result['access_token']
  53.     else:
  54.         print ('please overwrite the correct API_KEY and SECRET_KEY')
  55.         exit()
  56. """
  57.     读取文件
  58. """
  59. def read_file(image_path):
  60.     f = None
  61.     try:
  62.         f = open(image_path, 'rb')
  63.         return f.read()
  64.     except:
  65.         print('read image file fail')
  66.         return None
  67.     finally:
  68.         if f:
  69.             f.close()
  70. """
  71.     调用远程服务
  72. """
  73. def request(url, data):
  74.     req = Request(url, data.encode('utf-8'))
  75.     has_error = False
  76.     try:
  77.         f = urlopen(req)
  78.         result_str = f.read()
  79.         if (IS_PY3):
  80.             result_str = result_str.decode()
  81.         return result_str
  82.     except  URLError as err:
  83.         print(err)
  84. if __name__ == '__main__':
  85.     for num in range(1,6):
  86.         # 获取access token
  87.         token = fetch_token()
  88.         # 拼接通用文字识别高精度url
  89.         image_url = OCR_URL + "?access_token=" + token
  90.         text = ""
  91.     
  92.         
  93.        
  94. #这里改成自己的路径。关键帧是文件夹名,和本python文件同级,关键帧文件夹里面是图片
  95.         path="./关键帧/%d"%(num) 
  96.         jpg=".jpg"#图片是jpg格式,可以改成其他格式
  97.         a=path+jpg
  98.         file_content = read_file(a)
  99.         
  100.         # 调用文字识别服务
  101.         result = request(image_url, urlencode({'image': base64.b64encode(file_content)}))
  102.         # 解析返回结果
  103.         result_json = json.loads(result)
  104.         for words_result in result_json["words_result"]:
  105.             text = text + words_result["words"]
  106.         # 打印识别出来的文字
  107.         print(text)
  108.         #打印当前时间
  109.         (time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime()))
  110. #空行
  111.         print ("\n\n\n")        

九、其他

        我之前找了很多篇用百度OCR进行文字识别的文章,大部分文章都是有代码的,可惜没有一个能够运行。这些代码都是报同一种错误:KeyError: 'words_result'。百度上也鲜有解释,有人说这可能是用了别人的API Key和Secret Key导致的错误,要用自己的。但是我用了自己的依然出错,索性就将那些代码舍弃了,开始看官方文档,结果给了我一个大大的惊喜:有demo。我花了一些时间将识别单张图片的demo改成了识别多张图片。

        像语音识别、人脸识别等技术都应该先看官方文档,一般都有demo,有了错误再看其他的一些文章。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/487531
推荐阅读
相关标签
  

闽ICP备14008679号