当前位置:   article > 正文

Python 利用百度文字识别 API 识别并提取图片中文字_python调用百度api实现单张图片文字提取

python调用百度api实现单张图片文字提取

Python 利用百度文字识别 API 识别并提取图片中文字


利用百度 AI 开发平台的 OCR 文字识别 API 识别并提取图片中的文字。首先需注册获取 API 调用的 ID 和 key,步骤如下:

打开百度AI开放平台,进入控制台中的文字识别应用(需要有百度账号)。

创建一个应用,并进入管理应用,记下 AppID, API Key, Secrect Key,调用 API需用到。


最后安装 python 的百度ai接口的的库
pip install baidu-aip or pip3 install baidu-aip

以下是代码实现,需将所有识别的图片放进名为 picture 的文件夹。

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Jun 12 09:37:38 2018
  5. 利用百度api实现图片文本识别
  6. @author: XnCSD
  7. """
  8. import glob
  9. from os import path
  10. import os
  11. from aip import AipOcr
  12. from PIL import Image
  13. def convertimg(picfile, outdir):
  14. '''调整图片大小,对于过大的图片进行压缩
  15. picfile: 图片路径
  16. outdir: 图片输出路径
  17. '''
  18. img = Image.open(picfile)
  19. width, height = img.size
  20. while(width*height > 4000000): # 该数值压缩后的图片大约 两百多k
  21. width = width // 2
  22. height = height // 2
  23. new_img=img.resize((width, height),Image.BILINEAR)
  24. new_img.save(path.join(outdir,os.path.basename(picfile)))
  25. def baiduOCR(picfile, outfile):
  26. """利用百度api识别文本,并保存提取的文字
  27. picfile: 图片文件名
  28. outfile: 输出文件
  29. """
  30. filename = path.basename(picfile)
  31. APP_ID = '******' # 刚才获取的 ID,下同
  32. API_KEY = '******'
  33. SECRECT_KEY = '******'
  34. client = AipOcr(APP_ID, API_KEY, SECRECT_KEY)
  35. i = open(picfile, 'rb')
  36. img = i.read()
  37. print("正在识别图片:\t" + filename)
  38. message = client.basicGeneral(img) # 通用文字识别,每天 50 000 次免费
  39. #message = client.basicAccurate(img) # 通用文字高精度识别,每天 800 次免费
  40. print("识别成功!")
  41. i.close();
  42. with open(outfile, 'a+') as fo:
  43. fo.writelines("+" * 60 + '\n')
  44. fo.writelines("识别图片:\t" + filename + "\n" * 2)
  45. fo.writelines("文本内容:\n")
  46. # 输出文本内容
  47. for text in message.get('words_result'):
  48. fo.writelines(text.get('words') + '\n')
  49. fo.writelines('\n'*2)
  50. print("文本导出成功!")
  51. print()
  52. if __name__ == "__main__":
  53. outfile = 'export.txt'
  54. outdir = 'tmp'
  55. if path.exists(outfile):
  56. os.remove(outfile)
  57. if not path.exists(outdir):
  58. os.mkdir(outdir)
  59. print("压缩过大的图片...")
  60. # 首先对过大的图片进行压缩,以提高识别速度,将压缩的图片保存与临时文件夹中
  61. for picfile in glob.glob("picture/*"):
  62. convertimg(picfile, outdir)
  63. print("图片识别...")
  64. for picfile in glob.glob("tmp/*"):
  65. baiduOCR(picfile, outfile)
  66. os.remove(picfile)
  67. print('图片文本提取结束!文本输出结果位于 %s 文件中。' % outfile)
  68. os.removedirs(outdir)

 

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

闽ICP备14008679号