为了在 Tensorboard 中获得良好的输出,我想在网格中显示一批输入图像、相应的目标蒙版和输出蒙版。 输入图像的大小与蒙版不同。此外,图像显然是 RGB 的。 来自一批例如32 或 64 我只想显示前 4 张图像。
经过一番摆弄后,我想出了以下示例代码。好消息:它有效。 但我真的不确定我是否错过了 Pytorch 中的某些东西。它看起来比我预期的要长得多。尤其是上采样和 RGB 转换看起来很疯狂。但我发现的其他转换不适用于整个批处理。
import torch
from torch.autograd import Variable
import torch.nn.functional as FN
import torchvision.utils as vutils
from tensorboardX import SummaryWriter
import time
batch = 32
i_size = 192
o_size = 112
nr_imgs = 4
# Tensorboard init
writer = SummaryWriter('runs/' + time.strftime('%Y%m%d_%H%M%S'))
input_image=Variable(torch.rand(batch,3,i_size,i_size))
target_mask=Variable(torch.rand(batch,o_size,o_size))
output_mask=Variable(torch.rand(batch,o_size,o_size))
# upsample target_mask, add dim to have gray2rgb
tm = FN.upsample(target_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear')
tm = torch.cat( (tm,tm,tm), dim=1) # grayscale plane to rgb
# upsample target_mask, add dim to have gray2rgb
om = FN.upsample(output_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear')
om = torch.cat( (om,om,om), dim=1) # grayscale plane to rgb
# add up all images and make grid
imgs = torch.cat( ( input_image[:nr_imgs].data, tm.data, om.data ) )
x = vutils.make_grid(imgs, nrow=nr_imgs, normalize=True, scale_each=True)
# Tensorboard img output
writer.add_image('Image', x, 0)
编辑:找到this在 Pytorchs 问题列表中。它是关于对 Transform 的批量支持
。似乎 future 没有添加批量转换的计划。那么我当前的代码可能是目前最好的解决方案,无论如何?
最佳答案
也许你可以将张量转换为 numpy 数组 (.data.cpu().numpy() ) 并使用 opencv 进行上采样? OpenCV 的实现应该相当快。
关于python - Pytorch 中对张量进行上采样并将其转换为 RGB 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521393/