简体   繁体   English

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

[英]Append 2D array to 3D array, extending third dimension

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: all the input arrays must have same number of dimensions

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: 否则,要使用appendconcatenate ,您必须自己制作三维B并指定要加入它们的轴:

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

使用np.stack应该可以工作,但问题是两个数组都应该是 2D 形式。

np.stack([A,B])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM