gmo*_*onz 2 python ocr tesseract typeerror pytesser
遇到有关 Pytesseract 的以下代码的此错误代码的问题。(Python 3.6.1,Mac OSX)
从 PIL 导入 pytesseract 导入请求 从 PIL 导入图像 从 io 导入 ImageFilter 导入 StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
Run Code Online (Sandbox Code Playgroud)
错误:
/usr/local/Cellar/python3/3.6.0_1/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/g/pyfo/reddit/ocr.py
Traceback (most recent call last):
File "/Users/g/pyfo/reddit/ocr.py", line 20, in <module>
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
File "/Users/g/pyfo/reddit/ocr.py", line 10, in process_image
image.filter(ImageFilter.SHARPEN)
File "/usr/local/lib/python3.6/site-packages/PIL/Image.py", line 1094, in filter
return self._new(filter.filter(self.im))
File "/usr/local/lib/python3.6/site-packages/PIL/ImageFilter.py", line 53, in filter
raise ValueError("cannot filter palette images")
ValueError: cannot filter palette images
Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)
看起来很简单,但不起作用。任何帮助将不胜感激。
您拥有的图像是基于托盘的图像。您需要将其转换为完整RGB图像才能使用 PIL 过滤器。
import pytesseract
import requests
from PIL import Image, ImageFilter
from io import StringIO, BytesIO
def process_image(url):
image = _get_image(url)
image = image.convert('RGB')
image = image.filter(ImageFilter.SHARPEN)
return pytesseract.image_to_string(image)
def _get_image(url):
r = requests.get(url)
s = BytesIO(r.content)
img = Image.open(s)
return img
process_image("https://www.prepressure.com/images/fonts_sample_ocra_medium.png")
Run Code Online (Sandbox Code Playgroud)
您还应该注意.convert()和.filter()方法返回图像的副本,它们不会更改现有的图像对象。您需要将返回值分配给一个变量,如上面的代码所示。
注意:我没有 pytesseract,所以我无法检查process_image().