买了一些刷题的软件,不允许直接复制题目文本,于是想试试可不可以用脚本将软件截图转化为文本保存起来,方便整理回顾
同样的技术也可以用来实现图片验证码的识别
工具安装
首先需要安装Tesseract-OCR,这是一个光学字符识别工具,可以通过扫描字符,识别其形状将其翻译成电子文本。
Mac可以直接使用brew安装
···
brew install tesseract
···
Windows的话可以在https://digi.bib.uni-mannheim.de/tesseract/下载安装包
之后我们需要为Python安装图形处理工具和pytesseract对接库,pytesseract将会依赖于系统上的pytesseract进行字符识别
···
pip3 install pallow
pip3 install pytesseract
···
编写代码
···
import os
import pytesseract
from PIL import Image
dirPrefix = os.getcwd()
dirName = "image"
inputPath = dirPrefix+"/"+dirName
outputPath = dirPrefix + "/" + "output.txt"
with open(outputPath, 'a') as output:
for root, dirs, files in os.walk(inputPath):
for f in files:
extension = f[-4:]
if extension == '.png' or extension == '.jpg':
# print(os.path.join(root, f))
filepath = os.path.join(root, f)
# 读取图片
image = Image.open(filepath)
# 识别文字
text = pytesseract.image_to_string(image)
# 导出至文档
output.write(text)
···
网友评论