pythonarraysmultidimensional-arraycoordinate-systemsnibabel

Is it possible to turn a 3D array to coordinate system?


Is it possible to take a 3D array and and turn it into a coordinate system? My array consists of 0s and 1s. If the value is 1 I want to take the xyz coordinate. In the end I want to output all coordinates to a csv file.

import nibabel as nib

coord = []
img = nib.load('test.nii').get_fdata().astype(int)

test.nii array:

[[[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 1 ... 1 1 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 1 1 1]
  [0 1 0 ... 0 0 0]]

 [[1 0 0 ... 0 0 0]
  [0 0 1 ... 0 0 0]
  [0 1 0 ... 0 0 0]
  ...
  [0 1 0 ... 0 0 0]
  [0 1 0 ... 0 0 0]
  [0 0 0 ... 1 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 1 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 1 0 ... 0 1 1]]

 ...

 [[0 0 0 ... 1 0 0]
  [0 0 1 ... 0 0 0]
  [0 0 1 ... 0 0 0]
  ...
  [0 0 0 ... 1 0 0]
  [0 0 0 ... 1 0 0]
  [0 0 0 ... 1 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 1]
  ...
  [0 1 0 ... 0 0 0]
  [1 0 0 ... 0 0 0]
  [1 0 0 ... 0 0 0]]

 [[0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 0 0]
  ...
  [0 0 0 ... 0 0 0]
  [0 0 0 ... 0 1 0]
  [0 1 0 ... 0 0 0]]]

Solution

  • That might not necessarily be the best solution, but let's keep it simple (would be great if framework did that for us, but...well):

    data = [[[0, 0, 0, 0, 0, 0],
             [0, 0, 0, 0, 0, 0],
             [0, 0, 1, 1, 1, 0],
             [0, 0, 0, 0, 0, 0],
             [0, 0, 0, 1, 1, 1],
             [0, 1, 0, 0, 0, 0]],
            [[1, 0, 0, 0, 0, 0],
             [0, 0, 1, 0, 0, 0],
             [0, 1, 0, 0, 0, 0],
             [0, 1, 0, 0, 0, 0],
             [0, 1, 0, 0, 0, 0],
             [0, 0, 0, 1, 0, 0]]]
    
    for x in range(len(data)):
        for y in range(len(data[x])):
            for z in range(len(data[x][y])):
                if data[x][y][z] == 1:
                    print(f"{x} {y} {z}")
    

    yields:

    0 2 2
    0 2 3
    0 2 4
    0 4 3
    0 4 4
    0 4 5
    0 5 1
    1 0 0
    1 1 2
    1 2 1
    1 3 1
    1 4 1
    1 5 3