脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 实现任意区域文字识别(OCR)操作

Python 实现任意区域文字识别(OCR)操作

2021-09-17 00:22FlameAlpha Python

这篇文章主要介绍了Python 实现任意区域文字识别(OCR)操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

本文的OCR当然不是自己从头开发的,是基于百度智能云提供的API(我感觉是百度在中国的人工智能领域值得称赞的一大贡献),其提供的API完全可以满足个人使用,相对来说简洁准确率高。

安装OCR Python SDK

OCR Python SDK目录结构

  1. ├── README.md
  2. ├── aip //SDK目录
  3. ├── __init__.py //导出类
  4. ├── base.py //aip基类
  5. ├── http.py //http请求
  6. └── ocr.py //OCR
  7. └── setup.py //setuptools安装

支持Python版本:2.7.+ ,3.+

安装使用Python SDK有如下方式:

如果已安装pip,执行pip install baidu-aip即可。

如果已安装setuptools,下载后执行python setup.py install即可。

代码实现

下面让我们来看一下代码实现。

主要使用的模块有

  1. import os # 操作系统相关
  2. import sys # 系统相关
  3. import time # 时间获取
  4. import signal # 系统信号
  5. import winsound # 提示音
  6. from aip import AipOcr # 百度OCR API
  7. from PIL import ImageGrab # 捕获剪切板中的图片
  8. import win32clipboard as wc # WINDOWS 剪切板操作
  9. import win32con # 这里用于获取 WINDOWS 剪贴板数据的标准格式

第一步 这里的APP_ID,API_KEY,SECRET_KEY是通过登陆百度智能云后自己在OCR板块申请的, 实现基本的OCR程序,可以通过图片获取文字。

  1. """ 你的 APPID AK SK """
  2. APP_ID = 'xxx'
  3. API_KEY = 'xxx'
  4. SECRET_KEY = 'xxx'
  5.  
  6. client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
  7.  
  8. """ 读取图片 """
  9. def get_file_content(filePath):
  10. with open(filePath, 'rb') as fp:
  11. return fp.read()
  12.  
  13. """ 从API的返回字典中获取文字 """
  14. def getOcrText(txt_dict):
  15. txt = ""
  16. if type(txt_dict) == dict:
  17. for i in txt_dict['words_result']:
  18. txt = txt + i["words"]
  19. if len(i["words"]) < 25: # 这里使用字符串长度决定了文本是否换行,读者可以根据自己的喜好控制回车符的输出,实现可控的文本显示形式
  20. txt = txt + "\n\n"
  21. return txt
  22.  
  23. """ 调用通用/高精度文字识别, 图片参数为本地图片 """
  24. def BaiduOcr(imageName,Accurate=True):
  25. image = get_file_content(imageName)
  26. if Accurate:
  27. return getOcrText(client.basicGeneral(image))
  28. else:
  29. return getOcrText(client.basicAccurate(image))
  30.  
  31. """ 带参数调用通用文字识别, 图片参数为远程url图片 """
  32. def BaiduOcrUrl(url):
  33. return getOcrText(client.basicGeneralUrl(url))

第二步,实现快捷键获取文字,将识别文字放入剪切板中,提示音提醒以及快捷键退出程序

  1. """ 剪切板操作函数 """
  2. def get_clipboard():
  3. wc.OpenClipboard()
  4. txt = wc.GetClipboardData(win32con.CF_UNICODETEXT)
  5. wc.CloseClipboard()
  6. return txt
  7.  
  8. def empty_clipboard():
  9. wc.OpenClipboard()
  10. wc.EmptyClipboard()
  11. wc.CloseClipboard()
  12.  
  13. def set_clipboard(txt):
  14. wc.OpenClipboard()
  15. wc.EmptyClipboard()
  16. wc.SetClipboardData(win32con.CF_UNICODETEXT, txt)
  17. wc.CloseClipboard()
  18.  
  19. """ 截图后,调用通用/高精度文字识别"""
  20. def BaiduOcrScreenshots(Accurate=True,path="./",ifauto=False):
  21. if not os.path.exists(path):
  22. os.makedirs(path)
  23. image = ImageGrab.grabclipboard()
  24. if image != None:
  25. print("\rThe image has been obtained. Please wait a moment!",end=" ")
  26. filename = str(time.time_ns())
  27. image.save(path+filename+".png")
  28. if Accurate:
  29. txt = getOcrText(client.basicAccurate(get_file_content(path+filename+".png")))
  30. else:
  31. txt = getOcrText(client.basicGeneral(get_file_content(path+filename+".png")))
  32. os.remove(path+filename+".png")
  33. # f = open(os.path.abspath(path)+"\\"+filename+".txt",'w')
  34. # f.write(txt)
  35. set_clipboard(txt)
  36. winsound.PlaySound('SystemAsterisk',winsound.SND_ASYNC)
  37. # os.startfile(os.path.abspath(path)+"\\"+filename+".txt")
  38. # empty_clipboard()
  39. return txt
  40. else :
  41. if not ifauto:
  42. print("Please get the screenshots by Shift+Win+S! ",end="")
  43. return ""
  44. else:
  45. print("\rPlease get the screenshots by Shift+Win+S ! ",end="")
  46.  
  47. def sig_handler(signum, frame):
  48. sys.exit(0)
  49.  
  50. def removeTempFile(file = [".txt",".png"],path="./"):
  51. if not os.path.exists(path):
  52. os.makedirs(path)
  53. pathDir = os.listdir(path)
  54. for i in pathDir:
  55. for j in file:
  56. if j in i:
  57. os.remove(path+i)
  58.  
  59. def AutoOcrFile(path="./",filetype=[".png",".jpg",".bmp"]):
  60. if not os.path.exists(path):
  61. os.makedirs(path)
  62. pathDir = os.listdir(path)
  63. for i in pathDir:
  64. for j in filetype:
  65. if j in i:
  66. f = open(os.path.abspath(path)+"\\"+str(time.time_ns())+".txt",'w')
  67. f.write(BaiduOcr(path+i))
  68. break
  69.  
  70. def AutoOcrScreenshots():
  71. signal.signal(signal.SIGINT, sig_handler)
  72. signal.signal(signal.SIGTERM, sig_handler)
  73. print("Waiting For Ctrl+C to exit ater removing all picture files and txt files!")
  74. print("Please get the screenshots by Shift+Win+S !",end="")
  75. while(1):
  76. try:
  77. BaiduOcrScreenshots(ifauto=True)
  78. time.sleep(0.1)
  79. except SystemExit:
  80. removeTempFile()
  81. break
  82. else :
  83. pass
  84. finally:
  85. pass

最终运行函数 AutoOcrScreenshots 函数便可以实现了:

  1. if __name__ == '__main__':
  2. AutoOcrScreenshots()

使用方法

使用 Windows 10 系统时,将以上代码放置在一个 .py 文件下,然后运行便可以使用Shift+Win+S快捷键实现任意区域截取,截取后图片将暂时存放在剪切板中,程序自动使用Windows API获取图片内容,之后使用百度的OCR API获取文字,并将文字放置在剪切版内存中后发出提示音。

使用者则可以在开启程序后,使用快捷键截图后静待提示音后使用Ctrl+V将文字内容放置在自己所需的位置。

补充:Python 中文OCR

有个需求,需要从一张图片中识别出中文,通过python来实现,这种这么高大上的黑科技我们普通人自然搞不了,去github找了一个似乎能满足需求的开源库-tesseract-ocr:

Tesseract的OCR引擎目前已作为开源项目发布在Google Project,其项目主页在这里查看https://github.com/tesseract-ocr,

它支持中文OCR,并提供了一个命令行工具。python中对应的包是pytesseract. 通过这个工具我们可以识别图片上的文字。

笔者的开发环境如下:

macosx

python 3.6

brew

安装tesseract

  1. brew install tesseract

安装python对应的包:pytesseract

  1. pip install pytesseract

Python 实现任意区域文字识别(OCR)操作

怎么用?

如果要识别中文需要下载对应的训练集:https://github.com/tesseract-ocr/tessdata,下载”chi_sim.traineddata”,然后copy到训练数据集的存放路径,如:

Python 实现任意区域文字识别(OCR)操作

Python 实现任意区域文字识别(OCR)操作

具体代码就几行:

  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import pytesseract
  5. from PIL import Image
  6.  
  7. # open image
  8. image = Image.open('test.png')
  9. code = pytesseract.image_to_string(image, lang='chi_sim')
  10. print(code)

OCR速度比较慢,大家可以拿一张包含中文的图片试验一下。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/Flame_alone/article/details/104076580

延伸 · 阅读

精彩推荐