从tesseract导入image_to_string时的Python错误

14 投票
5 回答
31794 浏览
提问于 2025-04-17 14:24

我最近在用Python调用tesseract OCR的时候,试图从tesseract导入image_to_string时总是出错。

导致问题的代码:

# Perform OCR using tesseract-ocr library
from tesseract import image_to_string
image = Image.open('input-NEAREST.tif')
print image_to_string(image)

上面代码引发的错误:

Traceback (most recent call last):  
file "./captcha.py", line 52, in <module>  
from tesseract import image_to_string  
ImportError: cannot import name image_to_string

我已经确认tesseract模块是安装好的:

digital_alchemy@roaming-gnome /home $ pydoc modules | grep 'tesseract'
Hdf5StubImagePlugin _tesseract          gzip                sipconfig
ORBit               cairo               mako                tesseract

我觉得我已经安装了所有需要的包,但不幸的是我现在卡在这里。看起来这个函数在模块里找不到。

非常感谢任何帮助。

5 个回答

1

对于Windows系统,请按照以下步骤操作:

pip3 install pytesseract 
pip3 install pillow

还需要安装tesseract-ocr这个软件,具体可以参考这个链接:https://github.com/tesseract-ocr/tesseract/wiki,否则你会遇到一个错误,提示“Tessract不在路径中”。

下面是Python代码:

from PIL import Image
from pytesseract import image_to_string

print ( image_to_string(Image.open('test.tif'),lang='eng')  )
1

你安装的模块语法正确吗?那个 image_to_string 函数看起来是来自 PyTesser,具体可以参考这个页面上的使用示例:https://code.google.com/p/pytesser/

而你导入的看起来是 python-tesseract,它的使用示例要复杂一些,可以查看这里:https://code.google.com/p/python-tesseract/

9

还有一种可能性对我来说有效,那就是修改pytesseract,让它用的是“from PIL import Image”而不是“import Image”。

在修改了pytesseract后,在PyCharm中可以正常工作的代码:

from pytesseract import image_to_string
from PIL import Image

im = Image.open(r'C:\Users\<user>\Downloads\dashboard-test.jpeg')
print(im)

print(image_to_string(im))

我是在PyCharm自带的包管理工具里安装的Pytesseract。

撰写回答