PIL 和 python 静态类型

PIL and python static typing

我有一个函数参数,它可以接受多种图像类型:

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

本例中的 PIL Image 抛出以下异常:

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

进一步检查图像对象后,这才有意义:

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

我将如何为 PIL 图像指定通用类型?它来自一个文件,它的格式应该无关紧要。

我手边没有IDE,但是你得到的错误是:

. . . Got <module 'PIL.Image'

建议您在试图引用模块中包含的 Image 对象时试图将模块本身用作类型。

我猜你有一个像

这样的导入
from PIL import Image

这使得 Image 引用模块,而不是对象。

你想要

from PIL.Image import Image

以便导入对象本身。

注意,现在 Image 指的是对象。如果你想在同一个文件中引用对象和模块,你可能需要做这样的事情:

from PIL import Image as img
from PIL.Image import Image

现在模块的别名是 img

与其他答案类似,您可以 def somefunc(img: Union[np.array, Image.Image, Path, str]): 直接调用模块的对象。在 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'>

类型随.convert("L")

正常变化