将2D数组附加到3D数组,扩展第三维

时间:2021-09-21 19:54:40

I have an array A that has shape (480, 640, 3), and an array B with shape (480, 640).

我的阵列A有形状(480,640,3),阵列B有形状(480,640)。

How can I append these two as one array with shape (480, 640, 4)?

如何将这两个作为一个形状(480,640,4)的数组附加?

I tried np.append(A,B) but it doesn't keep the dimension, while the axis option causes the ValueError: all the input arrays must have same number of dimensions.

我尝试了np.append(A,B),但它不保留维度,而axis选项导致ValueError:所有输入数组必须具有相同数量的维度。

1 个解决方案

#1


13  

Use dstack:

使用dstack:

>>> np.dstack((A, B)).shape
(480, 640, 4)

This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.

这将处理数组具有不同维数的情况,并沿第三轴堆叠数组。

Otherwise, to use append or concatenate, you'll have to make B three dimensional yourself and specify the axis you want to join them on:

否则,要使用追加或连接,您必须自己制作三维B并指定要加入它们的轴:

>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)

#1


13  

Use dstack:

使用dstack:

>>> np.dstack((A, B)).shape
(480, 640, 4)

This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.

这将处理数组具有不同维数的情况,并沿第三轴堆叠数组。

Otherwise, to use append or concatenate, you'll have to make B three dimensional yourself and specify the axis you want to join them on:

否则,要使用追加或连接,您必须自己制作三维B并指定要加入它们的轴:

>>> np.append(A, np.atleast_3d(B), axis=2).shape
(480, 640, 4)