向 nifti 文件添加维度
Add a dimension to a nifti file
我有 (112, 176, 112)
形状的 nifti 文件 (.nii)。我想给它加一个维度,让它变成(112, 176, 112, 3)
。当我尝试 img2 = np.arange(img).reshape(112,176,112,3)
时出现错误。
是否可以使用 np.reshape
或 np.arange
或任何其他方式来做到这一点?
代码:
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')
错误:
---------------------------------------------------------------------------
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()
你可以这样做:
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)
可能这是其他更好的方法,但上面的代码给了你想要的输出。
我有 (112, 176, 112)
形状的 nifti 文件 (.nii)。我想给它加一个维度,让它变成(112, 176, 112, 3)
。当我尝试 img2 = np.arange(img).reshape(112,176,112,3)
时出现错误。
是否可以使用 np.reshape
或 np.arange
或任何其他方式来做到这一点?
代码:
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')
错误:
---------------------------------------------------------------------------
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()
你可以这样做:
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)
可能这是其他更好的方法,但上面的代码给了你想要的输出。