# Trilinear interpolation in python?

Hello! I have a nifti volume, let’s say it’s size is 100^3.
I’d like to get the sample value at floating-point coordinates, for example, (10.3, 70.9, 50.4). At the moment I use a trilinear interpolation function I wrote on the side, but I was wondering if that functionality is already implemented in some of the popular python neuroimaging packages? Ideally, I’d like a function where I pass a nifti volume, a list of query coordinates, and I get a vector with the values trilinearly sampled from the MRI.
Thank you!

here’s the function I’m currently using, but I’m happier when I don’t have to use my own code

``````def trilinear(xyz, data):
'''
xyz: array with coordinates inside data
data: 3d volume
returns: interpolated data values at coordinates
'''
ijk = xyz.astype(np.int32)
i, j, k = ijk[:,0], ijk[:,1], ijk[:,2]
V000 = data[ i   , j   ,  k   ].astype(np.int32)
V100 = data[(i+1), j   ,  k   ].astype(np.int32)
V010 = data[ i   ,(j+1),  k   ].astype(np.int32)
V001 = data[ i   , j   , (k+1)].astype(np.int32)
V101 = data[(i+1), j   , (k+1)].astype(np.int32)
V011 = data[ i   ,(j+1), (k+1)].astype(np.int32)
V110 = data[(i+1),(j+1),  k   ].astype(np.int32)
V111 = data[(i+1),(j+1), (k+1)].astype(np.int32)
xyz = xyz - ijk
x, y, z = xyz[:,0], xyz[:,1], xyz[:,2]
Vxyz = (V000 * (1 - x)*(1 - y)*(1 - z)
+ V100 * x * (1 - y) * (1 - z) +
+ V010 * (1 - x) * y * (1 - z) +
+ V001 * (1 - x) * (1 - y) * z +
+ V101 * x * (1 - y) * z +
+ V011 * (1 - x) * y * z +
+ V110 * x * y * (1 - z) +
+ V111 * x * y * z)
return Vxyz
``````
1 Like

awesome! thank you