找回密码
 立即注册

推荐阅读

  • 便民服务
  • 关注我们
  • 社区新手

通过百度文字识别的API来实现把图片内容写入到txt文件

[复制链接]
本帖最后由 icestick8586 于 2018-11-30 12:06 编辑

1、首先去百度注册一个账户,然后选择对应的识别类型创建对应的应用,获取AppID,APIKey,SecretKey,请参考百度官方接入文档http://ai.baidu.com/docs#/Begin/top
2、官方使用文档http://ai.baidu.com/docs#/OCR-Python-SDK/top
  1. #-*- coding: UTF-8 -*-
  2. #前提是python已安装aip库--》pip install baidu-aip

  3. import os
  4. from aip import AipOcr
  5. APP_ID = '你注册账号创建应用后得到的APPID'
  6. API_KEY = '你注册账号创建应用后得到的API_KEY'
  7. SECRET_KEY = '你注册账号创建应用后得到的SECRET_KEY '
  8. aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
  9. os.chdir("E:\\office\\src_pic")  #你需要转换的图片目录
  10. dirs = os.listdir()
  11. def get_file_content(filePath):
  12.     with open(filePath, 'rb') as fp:
  13.         return fp.read()
  14. options = {}
  15. options["language_type"] = "CHN_ENG"
  16. options["detect_direction"] = "true"
  17. options["detect_language"] = "true"
  18. options["probability"] = "true"

  19. print('开始处理,共'+str(len(dirs))+"张图片。")
  20. flag=0
  21. T = 0 #统计处理图片成功的数量
  22. for filePath in dirs:
  23.     if filePath.split('.')[-1]=='txt':continue
  24.     flag+=1
  25.     print('正在处理第'+str(flag)+'张图片')
  26.     try:
  27.         result = aipOcr.basicGeneral(get_file_content(filePath), options)
  28.     except BaseException as e:
  29.         print(e)
  30.     else:
  31.         try:
  32.             with open(filePath.split('.')[0]+'.txt','w',encoding='utf-8') as f:
  33.                 for i in result['words_result']:
  34.                         f.write(i['words']+'\n')
  35.                 T += 1
  36.         except BaseException as e :
  37.             print(e)
  38.         else:
  39.             print('处理完成')
  40. print('{}全部处理完成!{}'.format("="*30,"="*30))
  41. print('处理成功的图片有{}张,处理失败的图片有{}张'.format(T,len(dirs)-T))
复制代码
分享至 : QQ空间
收藏

0 个回复

您需要登录后才可以回帖 登录 | 立即注册