向数组添加维度

问题描述 投票:0回答:1

[如果我有一个从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
python numpy concatenation reshape nifti
1个回答
0
投票

@@ 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)
© www.soinside.com 2019 - 2024. All rights reserved.