I have nifti file (.nii) with a shape of (112, 176, 112)
. I want to add another dimension to it so that it becomes (112, 176, 112, 3)
. When I try img2 = np.arange(img).reshape(112,176,112,3)
I get an error.
Is it possible to do this with np.reshape
or np.arange
or any other way?
Code:
import numpy as np
import nibabel as nib
filepath = 'test.nii'
img = nib.load(filepath)
img = img.get_fdata()
img = np.arange(img).reshape(112,176,112,3)
img = nib.Nifti1Image(img, np.eye(4))
img.get_data_dtype() == np.dtype(np.int16)
img.header.get_xyzt_units()
nib.save(img, 'test_add_channel.nii')
Error:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-16-f6f2a2d91a5d> in <module>
8 print(img.shape)
9
---> 10 img2 = np.arange(img).reshape(112,176,112,3)
11
12 img = nib.Nifti1Image(img, np.eye(4))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
You can do'it this way:
import numpy as np
img = np.random.rand(112, 176, 112) # Your image
new_img = img.reshape((112, 176, 112, -1)) # Shape: (112, 176, 112, 1)
new_img = np.concatenate([new_img, new_img, new_img], axis=3) # Shape: (112, 176, 112, 3)
Probably that is other better way to do'it, but the code above give you the output you want.