简体   繁体   English

使用索引的二维张量访问 3D 张量(图像)

[英]Access 3D tensor (image) using a 2d tensor of indices

With the following 3D tensor representing an image用下面的 3D 张量代表一个图像
img.shape=[H,W,F]
And a tensor representing the indices to that img以及一个表示该 img 索引的张量
indices.shape=[N,2]
Eg if例如,如果
indices = [[0,1],[5,3],...]] I would like to create a new tensor of shape new.shape=[N,F] where indices = [[0,1],[5,3],...]]我想创建一个形状new.shape=[N,F]的新张量,其中
new[k] == img[indices[k][0],indices[k][1]] Currently to solve this I flatten both tensors: new[k] == img[indices[k][0],indices[k][1]]目前为了解决这个问题,我将两个张量都展平:

    idx_flattened = idx_flattened [:,0] * (idx_flattened [:,1].max()+1) + idx_flattened[:,1]
    img = img .reshape(-1,F)
    new = img[idx_flattened ]

But I'm certain there is a better way:)但我确信有更好的方法:)

Here's a full minimal example:这是一个完整的最小示例:

img = torch.arange(8*10*3).reshape(8,10,3)
indices = torch.tensor([[0,0],[3,0],[1,2]])
new = img[indices] <- This does not work
new = [[  0,   1,   2],[ 90,  91,  92],[ 36,  37,  38]]

Ideas?想法?

Slicing would work切片会起作用

img[indices[:,0], indices[:,1]]
tensor([[ 0,  1,  2],
        [90, 91, 92],
        [36, 37, 38]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM