python - Pytorch 中对张量进行上采样并将其转换为 RGB 的最佳方法?

标签 python python-3.x deep-learning tensorboard pytorch

为了在 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/

相关文章:

python - Django session 过期?

python - 如何计算大矩阵的行列式而不会溢出?

r - 有没有办法在不同版本的 H2O 之间使用保存的模型?

python - 无法在 Flask websocket 中使用 Jsonify

python - 通过调用包含绘图命令的函数在同一个图上绘制几个随机生成的线图

Python 3 struct.pack() : char format requires a bytes object of length 1

python - Tensorflow训练模型速度

python - `,` 在索引框中做什么?

python - 在 Python 中测试私有(private)方法 : Unit Test or Functional Test?

tensorflow - 张量板标量看起来一团糟