Very confused about imdata matrix index order

For an array (or matrix), the indexing is [row, col] for two dimensions, or [slice, row, col] for three dimensions.

Consider the following code, where a[1,0] means row=1, col=0:

>>> import numpy as np
>>> np.array([[1,2],[3,4]])
array([[1, 2],
       [3, 4]])
>>> a = np.array([[1,2],[3,4]])
>>> a[1,0]
3

Since arrays are indexed as [slice,row,col] and slice=z, row=y, col=x it is natural that, if the array stores an image, we index the array as follows:

>>> a[Z, Y, X] # 3D
>>> b[Y, X] # 2D

Here is the best way to think about it: the order of the indexes is according to the type of object the data is stored in. A numpy array has an ‘array-style’ interface, and is indexed by [row, col] or [slice, row, col]. A vtkImageData has an ‘image-style’ interface, and is indexed by (x, y) or (x, y, z). So that is how VTK works.


You have to be extra-careful when using python image libraries like nibabel, because they transpose the array in order to use image-style indexing with the arrays. In other words, they use ‘row=x’ and "col=y’ which seems unnatural to me.

3 Likes