如何将 .tif PIL 图像转换为火炬张量?

Posted

技术标签:

【中文标题】如何将 .tif PIL 图像转换为火炬张量?【英文标题】:How to convert a .tif PIL image to a torch tensor? 【发布时间】:2021-12-12 17:41:15 【问题描述】:

我有一些 .tif 图像,我正在将它们作为 PIL 图像读取。 我知道有一个ToPILimage 变换

但我找不到类似于from_numpy()from_PILimage()

现在我有这个丑陋的东西:

img = torch.from_numpy(np.array(Image.open('path/image.tif')))

你能告诉我一个更好的方法吗?

提前致谢!

【问题讨论】:

【参考方案1】:

类似于torchvision.transforms.ToPILImage(),可以直接使用torchvision.transforms.ToTensor()。 PyTorch 的示例docs

还有功能等效的torchvision.functional.to_tensor()

img = Image.open('someimg.png')

import torchvision.transforms.functional as TF
TF.to_tensor(img)

from torchvision import transforms
transforms.ToTensor()(img)

【讨论】:

非常感谢,愚蠢的我尝试了这个,之前将 img 作为参数传递,再次感谢!完美运行

以上是关于如何将 .tif PIL 图像转换为火炬张量?的主要内容,如果未能解决你的问题,请参考以下文章