如何使用PIL将四维张量转换为图像?

huangapple go评论67阅读模式
英文:

How to convert a four dimensional Tensor to image by PIL?

问题

例如,如果我的张量是:

t1 = torch.randn(1, 3, 256, 256)  # batch_size/ch/height/width

可以使用 squeeze() 轻松将其转换为一张图像:

import torchvision.transforms as T
transform = T.ToPILImage()
one_img = transform(t1.squeeze())
one_img.save("test1.jpg")

问题是,如果批处理大小大于一,我想知道是否有类似于以下的PyTorch函数:

t1 = torch.randn(5, 3, 256, 256)
print(t1.shape)
for i in range(t1.size(0)):
    one_tensor = t1[i]  #(3, 256, 256)
    one_img = transform(one_tensor)
    one_img.save(str(i) + ".jpg")
英文:

For example, if my tensor is

t1 = torch.randn(1,3,256,256) #batch_size/ch/height/width

it is easily to convert to one image by squeeze()

import torchvision.transforms as T
transform = T.ToPILImage()
one_img = transform(t1.squeeze())
one_img.save("test1.jpg")

The problem is if batch_size is is more than one, I was wondering if there is for function in pytorch like,

t1 = torch.randn(5,3,256,256)
print(t1.shape)
for i in range(t1[0]):
    one_tensor = t1[i]  #(3,256,256)
    one_img = transform(one_tensor)
    one_img.save(i + ".jpg")

答案1

得分: 0

只需执行以下操作:

for i in range(len(t1)):
    one_tensor = t1[i]
    one_img = transform(one_tensor)
    one_img.save(str(i) + ".jpg")
英文:

Just do this:

for i in range(len(t1)):
    one_tensor = t1[i]
    one_img = transform(one_tensor)
    one_img.save(str(i) + ".jpg")

huangapple
  • 本文由 发表于 2023年4月11日 10:44:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定