I have an array of flat indices and I want to get the corresponding 3D indices. I want to avoid using a for-loop to convert each flat index to a 3D index one by one.
I tried to use the numpy's np.unravel_index() method to compute the 3D indices as shown below:
import numpy as np
# Column vector of flat indices
test_flat_indices = np.array([[3957], [8405], [9161], [11105], [969]])
# Shape of 3D array
num_rows = 51
num_cols = 51
num_frames = 8
# Convert flat indices to 3D indices
indices_3d = np.unravel_index(test_flat_indices, (num_rows, num_cols, num_frames))
# Format the result to [row, col, frame] format
indices_3d = np.column_stack(np.array(indices_3d))
print(indices_3d)
The above code produces the following output:
array([[ 9, 35, 5],
[20, 30, 5],
[22, 23, 1],
[27, 11, 1],
[ 2, 19, 1]], dtype=int64)
Problem: The above out seems wrong because if I try to convert the 3D indices above to flat indices back (for verification) then, the values does not match. For example, the output value [9, 35, 5] should represent 9th-row, 35th-column and 5th-frame, which would actually result in (5x51x51 + 9x51 + 35) = 13499, which is wrong (the correct value should be 3957).
NOTE: If I change the unravel_index() method arguments to np.unravel_index(test_flat_indices, (num_frames, num_rows, num_cols)) then, the output is correct, which is:
array([[ 1, 26, 30],
[ 3, 11, 41],
[ 3, 26, 32],
[ 4, 13, 38],
[ 0, 19, 0]], dtype=int64)
but why do I need to put the number of frames first?