在python中更改4D数组的形状

2024-04-28 03:47:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这个函数来重新索引4d矩阵

def insideout(ndimage):
    len_outrow = len(ndimage)
    len_outcol = len(ndimage[0])
    len_inrow = len(ndimage[0][0])
    len_incol = len(ndimage[0][0][0])

    reversed_image = np.empty((len_inrow,len_incol,len_outrow,len_outcol))
    for outrow in range(len_outrow):
        for outcol in range(len_outcol):
            for inrow in range(len_inrow):
                for incol in range(len_incol):     
                    #reverse the indices
                    reversed_image[inrow][incol][outrow][outcol]=image[outrow][outcol][inrow][incol]
    return reversed_image

这对于326x326x43x25矩阵很有效。它成功地将矩阵的形状更改为(43,25236236)

我在矩阵上应用了一些计算,它不会改变它的形状,现在我想用同样的函数把它还原回来

然而,这次我收到了以下错误

--------------------------------------------------------------------------- IndexError                                Traceback (most recent call
last) <ipython-input-18-da92ca90d937> in <module>
----> 1 insideout(reversed_image)

<ipython-input-17-4edf23c1ed04> in insideout(ndimage)
     17                 for incol in range(len_incol):
     18                     #reverse the indices
---> 19                     reversed_image[inrow][incol][outrow][outcol]=image[outrow][outcol][inrow][incol]
     20     return reversed_image

IndexError: index 25 is out of bounds for axis 0 with size 25

我不明白错误是从哪里来的!为什么会有索引25(因为我已经在for循环中使用了range())

输入矩阵是一个4D数组


Tags: 函数inimageforlenrange矩阵reverse
1条回答
网友
1楼 · 发布于 2024-04-28 03:47:08

您的代码中有一个输入错误

reversed_image[inrow][incol][outrow][outcol]=image[outrow][outcol][inrow][incol]

您使用的不是ndimage,而是函数外部的另一个变量。 应该是这样

reversed_image[inrow][incol][outrow][outcol]=ndimage[outrow][outcol][inrow][incol]

相关问题 更多 >