python - 向数组添加维度
问题描述
如果我有一个从具有形状的 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
解决方案
@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)
推荐阅读
- r - 如何解决“找不到对象'sexe'”错误的问题?
- html - 为什么easy-in-out不适用于联系表格部分?
- hbase - Phoenix如何翻译IN子句?
- angular - 角垫诊断等待响应
- reactjs - 测试包装查询组件的问题
- wordpress - 运行新闻网站的 EC2 实例存在重大性能问题
- android - 通过 Android 应用程序将 PDF 文件发送到 WhatsApp 上未保存的联系人号码
- angular - angular ng-autocomplete 不适用于 [(ngModel)] 和一起命名
- javascript - 从网站向 Chrome 插件发送消息
- javascript - Sequelize 中的搜索运算符