如何结合图像张量(4D)和深度张量(4D)在 PyTorch 中创建 5D 张量 [batch size, channels, depth, height, width]?

左六

在训练期间,我加载图像和视差数据。图像张量的形状为:[2, 3, 256, 256],视差/深度张量的形状为:[2, 1, 256, 256](批量大小、通道、高度、宽度)。我想使用Conv3D,所以我需要将这两个张量结合起来,创建一个新的形状张量:[2, 3, 256, 256, 256](批量大小,通道,深度,高度,宽度)。深度值的范围为 0-400,可以将其划分为多个区间,例如 4 个 100 的区间。我希望生成的张量看起来像一个体素,类似于本文中使用的技术。迭代数据的训练循环如下:

 for batch_id, sample in enumerate(train_loader):
        
        sample = {name: tensor.cuda() for name, tensor in sample.items()}

        # image tensor [2, 3, 256, 256]
        rgb_image = transforms.Lambda(lambda x: x.mul(255))(sample["frame"]) 
        
        # translate disparity to depth
        depth_from_disparity_frame = 132.28 / sample["disparity_frame"]
        # depth tensor [2, 1, 256, 256]
        depth_image = depth_from_disparity_frame.unsqueeze(1) 
飞涨

从您链接的文章中:

我们创建一个 3D 体素表示,其高度和宽度与原始图像相同,深度由图像中发现的最大和最小深度值之间的差异决定。然后将图像的每个 RGB-D 像素放置在体素网格中的相同位置,但位于其相应的深度。

这或多或少是伊万建议的。如果您知道您的深度将始终为 0-400,并且我想您可以跳过“由最大和最小深度值之间的差异确定的深度”的第一部分。这总是可以事先或以后标准化。

使用虚拟数据的代码:

import torch
import torch.nn.functional as F

# Declarations (dummy tensors)
rgb_im = torch.randint(0, 255, [1, 3, 256, 256])
depth = torch.randint(0, 400, [1, 1, 256, 256])

# Calculations
depth_ohe = F.one_hot(depth, num_classes=400)       # of shape (batch, channel, height, width, binary)
bchwd_tensor = rgb_im.unsqueeze(-1)*depth_ohe       # of shape (batch, channel, height, width, depth)
bcdhw_tensor = bchwd_tensor.permute(0, 1, 4, 2, 3)  # of shape (batch, channel, depth, height, width)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章