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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With