使用PIL从URL打开图像文件以进行使用pytesseract进行文本识别

6

我面临一个令人困惑的问题,试图下载图像并使用BytesIO打开它,以便使用PIL和pytesseract从中提取文本。

>>> response = requests.get('http://abc/images/im.jpg')
>>> img = Image.open(BytesIO(response.content))
>>> img
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=217x16 at 0x7FDAD185CB38>
>>> text = pytesseract.image_to_string(img)
>>> text
''

这里会返回一个空字符串。

但是如果我保存图像,然后再使用pytesseract打开,它就会给出正确的结果。

>>> img.save('im1.jpg')
>>> im = Image.open('im1.jpg')
>>> pytesseract.image_to_string(im)
'The right text'

确认一下,两个给出的大小是相同的。

>>> im.size
(217, 16)
>>> img.size
(217, 16)

什么可能是问题?是需要保存图片还是我做错了什么?

我提供的答案怎么样,可以给点反馈吗? - Claudio
2个回答

11

你似乎有一个问题,但我无法重现。为了诊断你的问题(如果有的话),需要更多详细信息,但是我不会要求提供这些细节,相反,我假设(以我的整体经验),在提供细节的过程中,你的问题将消失并且无法再现。通过这种方式,这个回答是解决你的问题的方法。

如果这不是解决方案,请让我知道您是否需要进一步的帮助。至少你可以确定,因为你经历过并没有明显的错误。

以下是完整代码(你的问题缺少必须的模块提示),并且图片实际上在线上,所以任何人都可以测试代码是否有效(你没有在问题中提供在线存在的图片):

import io
import requests
import pytesseract
from PIL import Image
response = requests.get("http://www.teamjimmyjoe.com/wp-content/uploads/2014/09/Classic-Best-Funny-Text-Messages-earthquake-titties.jpg")
# print( type(response) ) # <class 'requests.models.Response'>
img = Image.open(io.BytesIO(response.content))
# print( type(img) ) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
text = pytesseract.image_to_string(img)
print( text )

这里是pytesseract的输出:

Hey! I just saw on CNN
there was an earthquake
near you. Are you ok?






‘ Yes! We‘re all line!

What did it rate on the titty
scale?
‘ Well they only jiggled a

little bit, so probably not

that high.
HAHAHAHAHAHA I LOVE
YOU
Richter scale. My phone is l
a 12 yr old boy.

我的系统: Linux Mint 18.1,使用 Python 3.6


0

尝试在调用pytesseract之前添加tesseract的路径

from PIL import Image
from pytesseract import pytesseract
import requests
from io import BytesIO
def ImageToText(ImageURl):
    response = requests.get(ImageURl)
    #add path to tesseract
    path_to_tesseract = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
    img = Image.open(BytesIO(response.content))
    pytesseract.tesseract_cmd = path_to_tesseract
    text = pytesseract.image_to_string(img)
    return text

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接