tonglin0325的个人主页

Python爬虫学习——光学字符识别

用homebrew 在电脑上安装tesseract库
 

1
brew install tesseract

用pip安装支持python的tesseract 接口

1
2
pip install pytesseract

  

使用pytesseract库图片文件(jpg、png、bmp等)进行识别,把图片转换成字符串输出。

1
2
3
4
5
6
import pytesseract
from PIL import Image

img = Image.open('1.gif')
print(pytesseract.image_to_string(img))

 实际测试效果:

输入图片,输出,结果:成功

输入图片,输出:为空,结果:失败

输入图片,输出:为空,结果:失败

输入图片,输出:,结果:错误

 

如果需要支持中文,请下载下面的文件到目录 /usr/local/Cellar/tesseract/5.1.0/share/tessdata

1
2
https://github.com/tesseract-ocr/tessdata/blob/main/chi_sim.traineddata

然后

1
2
print(pytesseract.image_to_string(img, lang='chi_sim'))