从在线图像中提取文本



我已经根据web和一些youtube视频上的参考资料编写了代码,但它似乎不适合我,我不理解任何进一步的问题。

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

我得到这个错误

File "F:ProjectsFileExtractoruntitled3.py", line 16, in <module>
img = Image.open(io.BytesIO(r.content))
File "C:ProgramDataAnaconda3libsite-packagesPILImage.py", line 2943, in open
raise UnidentifiedImageError(
UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x000001E85C0BAA40>

请帮我解决这个问题。谢谢你

又想了一下。为什么不欺骗浏览器头,现在看来这是可行的。

import io
import requests
import pytesseract
from PIL import Image
url = 'http://www.teamjimmyjoe.com/wp-content/uploads/2014/09/Classic-Best-Funny-Text-Messages-earthquake-titties.jpg'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.get(url, headers=headers)
img = Image.open(io.BytesIO(r.content))
# # print( type(img) ) # <class 'PIL.JpegImagePlugin.JpegImageFile'>
text = pytesseract.image_to_string(img)
#
print(text)

反应是:

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

| Yes! We're all fine!
What did it rate.on the titty
scale?
| Well they only jiggled a |

little bit, so probably not
that high.
HAHAHAHAHAHA | LOVE
YOU
Richter scale. My phone is |
a 12 yr old boy.
—————————r

总是从最简单的修复开始,然后从那里开始。

import requests
# import pytesseract
# from PIL import Image
r = requests.get("http://www.teamjimmyjoe.com/wp-content/uploads/2014/09/Classic-Best-Funny-Text-Messages-earthquake-titties.jpg",stream=True)
print(r.text)

产生如下结果:

<head><title>Not Acceptable!</title></head><body><h1>Not Acceptable!</h1><p>An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security.</p></body></html>

问题是你没有下载图像,你被Mod_Security阻止了。你需要在获得图像和文本之前克服这个问题。

最新更新