加载在python中分析7.5格式的图像

The*_*dus 6 python arrays numpy image

我正在做一些工作,我必须以一种称为Analyze 7.5文件格式的格式加载操纵CT图像.

这种操作的一部分 - 大型图像绝对老化 - 将原始二进制数据加载到numpy数组并将其重新整形为正确的尺寸.这是一个例子:

headshape = (512,512,245) # The shape the image should be
headdata = np.fromfile("Analyze_CT_Head.img", dtype=np.int16) # loads the image as a flat array, 64225280 long. For testing, a large array of random numbers would do

head_shaped = np.zeros(shape=headshape) # Array to hold the reshaped data

# This set of loops is the problem
for ux in range(0, headshape[0]):
    for uy in range(0, headshape[1]):
        for uz in range(0, headshape[2]):
            head_shaped[ux][uy][uz] = headdata[ux + headshape[0]*uy + (headshape[0]*headshape[1])*uz] # Note the weird indexing of the flat array - this is the pixel ordering I have to work with
Run Code Online (Sandbox Code Playgroud)

我知道numpy可以快速重组数组,但我无法弄清楚复制嵌套循环效果所需的正确转换组合.

有没有办法用numpy.reshape/numpy.ravel等组合复制那个奇怪的索引?

plo*_*ser 0

您可以将 reshape 与 swapaxes 结合使用

headshape = (2,3,4) 
headdata = rand(2*3*4)

head_shaped_short = headdata.reshape(headshape[::-1]).swapaxes(0,2)
Run Code Online (Sandbox Code Playgroud)

在我的例子中效果很好。