gpt4 book ai didi

python - PIL 和 python 静态类型

转载 作者:行者123 更新时间:2023-12-04 11:20:05 25 4
gpt4 key购买 nike

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

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 .

关于python - PIL 和 python 静态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58236138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com