Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL and python static typing

I have a function argument which can accept several types for an image:

def somefunc(img: Union[np.array, Image, Path, str]):

The PIL Image in this case throws the following exception:

TypeError: Union[arg, ...]: each arg must be a type. Got <module 'PIL.Image' from ...

Which makes sense after inspecting an image object further:

print(type(Image.open('someimage.tiff')))
>>> <class 'PIL.TiffImagePlugin.TiffImageFile'>

How would I go about specifying a generalized type for a PIL image? It being from a file and it's format should be irrelevant.

like image 463
primitivist Avatar asked Oct 04 '19 12:10

primitivist


1 Answers

Similar to the other answers, you could do def somefunc(img: Union[np.array, Image.Image, Path, str]): to call the module's object directly. Tested in python 3.9.

from PIL import Image

img = Image.open('some_path.png')
print(type(img))  # <class 'PIL.PngImagePlugin.PngImageFile'>
def to_gray(img:Image.Image):
    return img.convert("L")
img = to_gray(img)
print(type(img))  # <class 'PIL.Image.Image'>

The type changes normally with .convert("L")

like image 73
user3474165 Avatar answered Sep 21 '22 06:09

user3474165