在我写的前面一篇博客中,是把tesseract-ocr添加到系统环境变量里,那么如果不使用系统环境变量,该如何使用pytesseract了?
1 自定义tesseract目录
我们在Python安装目录里找到我们安装的第三方模块pytesseract,如下目录里E:\Conda\envs\python36\Lib\site-packages\pytesseract
使用Notepad++打开文件pytesseract.py
找到tesseract_cmd = ‘tesseract’,我们可以发现,这行命令是调用tesseract这个执行程序来进行字符识别的,当我们把tesseract.exe的目录设置了环境变量,是可以直接调用这个程序。
我们在这里改成tesseract.exe的目录也是可以的
将tesseract_cmd改写成
tesseract_cmd = 'E:/Tesseract-OCR4.1/tesseract'
或者也可以加上后缀名.exe
tesseract_cmd = 'E:/Tesseract-OCR4.1/tesseract.exe'
保存关闭后就可以了。
2 自定义tessdata目录
在我电脑中tessdata的目录是E:\Tesseract-OCR4.1\tessdata
因此可以自定义tessdata目录
#自定义tessdata目录
tessdata_dir_config ='--tessdata-dir "E:/Tesseract-OCR4.1/tessdata"'
在Python中调用pytesseract进行识别的代码如下:
import pytesseract
from PIL import Image
img=Image.open('test.png')
#自定义tessdata目录
tessdata_dir_config ='--tessdata-dir "E:/Tesseract-OCR4.1/tessdata"'
code=pytesseract.image_to_string(img,config=tessdata_dir_config,lang='chi_sim+eng')
print(code)