首页 > 解决方案 > 向数组添加维度

问题描述

如果我有一个从具有形状的 nifti 文件加载的数组,(112, 176, 112)并且我想添加第四维但不限于形状(112, 176, 112, 3)

为什么这段代码允许我在我想要的第 4 维中添加许多层:

data = np.ones((112, 176, 112, 20), dtype=np.int16)
print(data.shape)
    >>>(112, 176, 112, 20)

但是当我尝试向文件的第四维添加更高的层数时,我得到一个错误。代码仅在axis = 3. 如果axis = 2形状是(112, 176, 336, 1)

filepath = '3channel.nii'  
img = nib.load(filepath)
img = img.get_fdata()
print(img.shape)
    >>>(112, 176, 112)
img2 = img.reshape((112, 176, 112, -1))
img2 = np.concatenate([img2, img2, img2], axis = 20)

错误:

AxisError: axis 20 is out of bounds for array of dimension 4

标签: pythonnumpyconcatenationreshapenifti

解决方案


@hpaulj 知道了,我正在查找这个,这说明了问题;注意数组的形状。我修改了原始数组,以便您可以看到正在添加的内容...

import numpy as np

data = np.ones((112, 176, 115, 20), dtype=np.int16)

data2=np.ones((112, 176, 115), dtype=np.int16)

data2a = data2.reshape((112, 176, 115, -1))
print(data2a.shape)

print("concatenate...")
img2 = np.concatenate([data2a, data2a, data2a],axis=0)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=1)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=2)
print(img2.shape)

img2 = np.concatenate([data2a, data2a, data2a],axis=3)
print(img2.shape)

# This throws the error
img2 = np.concatenate([data2a, data2a, data2a],axis=4)
print(img2.shape)

推荐阅读