"ValueError:无法过滤调色板图像"在Pytesseract转换期间 [英] "ValueError: cannot filter palette images" during Pytesseract Conversion
问题描述
此错误代码与有关Pytesseract的以下代码有关,有麻烦. (Python 3.6.1,Mac OSX)
Having trouble with this error code regarding the following code for Pytesseract. (Python 3.6.1, Mac OSX)
导入pytesseract 汇入要求 从PIL导入图像 从PIL导入ImageFilter 从io导入StringIO,BytesIO
import pytesseract import requests from PIL import Image from PIL import ImageFilter from io import 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")
错误:
/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
看起来很简单,但是没有用.任何帮助将不胜感激.
Seems simple enough, but is not working. Any help would be greatly appreciated.
推荐答案
您拥有的图像是基于托盘的图像.您需要将其转换为完整的RGB
图片,才能使用PIL过滤器.
The image you have is a pallet-based image. You need to convert it to a full RGB
image in order to use the PIL filters.
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")
您还应该注意,.convert()
和.filter()
方法返回图像的副本,它们不会更改现有的图像对象.您需要将返回值分配给变量,如上面的代码所示.
You should also note that the the .convert()
and .filter()
methods return a copy of the image, they don't change the existing image object. You need to assign the return value to a variable as shown in the code above.
注意:我没有pytesseract,所以我无法检查process_image()
的最后一行.
NOTE: I don't have pytesseract, so I can't check the last line of process_image()
.
这篇关于"ValueError:无法过滤调色板图像"在Pytesseract转换期间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!