【Python3.8+pytesseract+Tesseract-OCR5.0图片文字识别】

1.环境
python版本:3.8.x
操作系统:windows 10系统
2.工具安装和配置
1.下载安装 tesseract-ocr 下载最新的x64版本,跟自己系统版本对应的一个:官网地址 https://digi.bib.uni-mannheim.de/tesseract/
2.下载安装Pycharm(下载地址:http://www.jetbrains.com/pycharm/download/#section=windows)
3.添加环境变量64位系统:TESSDATA_PREFIX = C:\Program Files\Tesseract-OCR\tessdata
4.编辑文件:C:\Python38\Lib\site-packages\pytesseract\pytesseract.py
tesseract_cmd = ‘tesseract’
#改为:
tesseract_cmd = ‘C:\Program Files\Tesseract-OCR\tesseract.exe’

1.使tesseract-ocr与python关联,从而使python能够调用Tesseract-OCR程序识别验证码/文字,否则会处问题报错:
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

  1. 注意:一定要注意/与\的区 分,window系统和linux系统对斜杠的区别

3.再安装相关python包
到C:\Python38\Scripts目录下,按住shift+鼠标右键,在此处打开命令,window10是Power Shell,进行安装执行,如果需要升级pip命令的话先升级,再执行

pip install Pillow
pip install pytesseract

4.使用
导入包,开始测试代码
from PIL import Image
import pytesseract

识别的图像的字符串

print(pytesseract.image_to_string(Image.open(‘test.png’)))

指定语言识别图像字符串,eng为英语

print(pytesseract.image_to_string(Image.open(‘test.png’), lang=‘eng’))

image = r’E:\pythonScript\Model\code\10000.jpg’
text = pytesseract.image_to_string(Image.open(image)).strip() # 使用image_to_string识别验证码
text1 = pytesseract.image_to_string(image,lang=‘eng’,config=’–psm 6 --oem 3 -c tessedit_char_whitelist=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’).strip() # 使用image_to_string识别验证码
print(‘读取到的验证码为: %s’ % text)
print(‘读取到的验证码为: %s’ % text1)

new_pic_file = ‘./newcode.png’
img.save(new_pic_file)

img.show()

使用image_to_string识别验证码

text = pytesseract.image_to_string(Image.open(new_pic_file), lang=‘eng’).strip() # 使用image_to_string识别验证码
#log.info(“读取到的验证码为: %s” % text)
new_text = text.replace(’ ', ‘’).replace("\n", “”) # 替换空行及空格
print(‘读取到的验证码为: %s’ % new_text)
os.remove(new_pic_file)
在此需要告诉新手的其中test.png是存放在py脚本的目录下,lang='chi_sim’代表中文识别,如果不加无法识别中文

5.运行脚本可以看到结果
虽然可以识别验证码了,但是这工具识别很不准确,除非没有什么干扰的验证图片才好些。只能识别还是不那么好啊。
特别提醒:如果步骤完全正确,但是运行报错,请卸载pytesseract重新安装问题就会解决
卸载命令:
pip uninstall pytesseract

GitHub 加速计划 / te / tesseract
24
3
下载
tesseract-ocr/tesseract: 是一个开源的光学字符识别(OCR)引擎,适用于从图像中提取和识别文本。特点是可以识别多种语言,具有较高的识别准确率,并且支持命令行和API调用。
最近提交(Master分支:7 个月前 )
014b9d00 - 3 个月前
13c966b7 - 3 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐