“ValueError: cannot filter palette images” during Pytesseract Conversion

☆樱花仙子☆ 提交于 2019-12-07 19:31:32

问题


Having trouble with this error code regarding the following code for Pytesseract. (Python 3.6.1, Mac OSX)

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")

Error:

/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.


回答1:


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")

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.

NOTE: I don't have pytesseract, so I can't check the last line of process_image().



来源:https://stackoverflow.com/questions/43267807/valueerror-cannot-filter-palette-images-during-pytesseract-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!