# Nibabel - How can we rescale a 3d image

Hi everyone !

I’m new to the nibabel library, and i still don’t understand if there is a easy way to rescale an image.
For example i have a 260*311*260 image (nifti) and i would like to resize it to the double so : 520*622*520.

For now i have try the resample_to_output method but i don’t think this give me expected result.

This could look as a dummy question, but i’m stuck in here, any idea ?

Hi @J-b, welcome to this community.

First, I’d like to point out that you don’t want to rescale your image, you want to regrid or upsample (more generally, resample) your data.

Currently, you can’t do that with nibabel alone (the library currently does not interpolate -in general-, for you). I would suggest to use nilearn for this.

There are two factors here. One is the sampling matrix, which you have already specified (data is currently on a 260 x 311 x 260 grid, and you want to resample it to 520 x 622 x 520.

The second factor is the location of data in physical coordinates w.r.t. some coordinate system (typically scanner coordinates). This information is encoded in the affine matrix corresponding to the image. Nibabel provides it very nicely:

``````import nibabel as nb
print(nii.affine)
``````

You’ll need to build a corresponding affine matrix that has double resolution (half pixel size) and covers almost exactly the same physical extent (i.e. you need to calculate a new origin).

Then, you can use nilearn.resample_img setting the arguments `target_affine=newaffine` and `target_shape=(520, 622, 520)`.

Hi !
Alright so I look on what you told me but, I still don’t get it.
how can I build a new affine matrix ?
Do i need to take the old one and divide [0][0], [1][1], [2][2] by 2 ?
or should I make a new one ?

In my case the affine is :
[[ -0.69999999 0. 0. 90. ]
[ 0. 0.69999999 0. -126. ]
[ 0. 0. 0.69999999 -72. ]
[ 0. 0. 0. 1. ]]

I didn’t understand what are the 90, -126, -72, is that the origin you talk about, if not where can I find it and how can I change it ?

I try few thing but this still didn’t work as expected.

Hi @J-b, you may want to look at nipy/nibabel#670 for a discussion of rescaling an affine matrix.

1 Like

@effigies : I am trying to figure what will be the new translation values in case of scaling. Lets say we have new scale and old scale. I was going thru @ellisdg’s code and he has used something like this (3DUnetCNN/affine.py at master · ellisdg/3DUnetCNN · GitHub)

def calculate_origin_offset(new_spacing, old_spacing):
return np.divide(np.subtract(new_spacing, old_spacing)/2, old_spacing)

Another question is leveraging other libraries like skimage and torchio. How resize/transform in skimage/ torchio approach is different from scaling affine first and then using resample_img from nilearn