Search code examples
pythonpytorchtensortorch

Pytorch tensor representing a 3D grid with color values


Given a list of density values (scalars) that represent the density of an X,Y,Z coordinate on a 3D grid, how would I create a single tensor that can store this information?

i.e. a tensor that has dimensions of 1x20x20x20 for example would represent a 20x20x20 grid such that:

print(tensor[:,x1,y1,z1])
0.6

print(tensor[:,x2,y2,z2])
0.4

Solution

  • Based on your comments, you would like to turn a (2000) 1D-tensor into a (1x20x20x20) 4D-tensor.

    Assuiming you have your initial tensor layed out as something like:

    X = torch.tensor([111,112,113,121,122,123,131,132,133,211,212,213,221,222,223,231,232,233,311,312,313,321,322,323,331,332,333])
    

    This is as simple as using view on it:

    xyz = X.view(3, 3, 3, 1)
    

    And, X[0, 1, 2] will give you [123] as expected.