将图像的 3D numpy 数组堆栈重塑为矢量并返回 3D,保留图像结构

Reshape 3D numpy array stack of images to vectors and back to 3D, preserving image structure

我及时观察重复图像的变化。我有一个 3D numpy 数组,它应该表示一堆 2 张图像,每张 3x3 像素(为简单起见 - 形状:2×3×3):

x = np.array([
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ],
    [
        [10,11,12],
        [13,14,15],
        [16,17,18]
    ]
])

我转置并重塑它,现在我有了“时间像素向量”,如下所示:

y = x.transpose(2,1,0).reshape(-1, x.shape[0])

>>> array([[ 1, 10],
       [ 4, 13],
       [ 7, 16],
       [ 2, 11],
       [ 5, 14],
       [ 8, 17],
       [ 3, 12],
       [ 6, 15],
       [ 9, 18]])

我进行了一些科学计算,最后得到了每个像素向量的布尔值,评估了某些特征:

>>> array([[ True, False, True],
       [ True, True, True],
       [False, False, True],
       [False, False, False],
       [ True, False, True],
       [ True, False, True],
       [ True, False, True],
       [ True, True, True],
       [False, False, True]])

现在,我如何 reshape/transpose 这个数组的形状为(特征数)×3×3 并保持单个图像像素的逻辑顺序,如数组 x?

如有必要,我会尝试进一步澄清。 谢谢!

您可以使用 y(不是掩码)来验证您是否成功重建 x,但本质上,在重塑之前跟踪中间阵列的形状,然后重塑回该形状并再次转置:

y_t = x.transpose(2,1,0) # same as x.T
y = y_t.reshape(-1, x.shape[0])

y.reshape(y_t.shape).T
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]]])

否则你也可以只使用初始数组的形状作为参考:

y = x.transpose(2,1,0).reshape(-1, x.shape[0])
y.reshape(x.shape[::-1]).T
array([[[ 1,  2,  3],
        [ 4,  5,  6],
        [ 7,  8,  9]],

       [[10, 11, 12],
        [13, 14, 15],
        [16, 17, 18]]])