将 2D 数组附加到 3D 数组,扩展第三维 [英] Append 2D array to 3D array, extending third dimension

查看:42
本文介绍了将 2D 数组附加到 3D 数组,扩展第三维的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为 (480, 640, 3) 的数组 A 和一个形状为 (480, 640).

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

我尝试了 np.append(A,B) 但它没有保留维度,而 axis 选项导致 ValueError: all input数组必须具有相同的维数.

解决方案

使用 dstack:

<预><代码>>>>np.dstack((A, B)).shape(480, 640, 4)

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

否则,要使用appendconcatenate,您必须自己制作B 三维并指定要连接的轴他们在:

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

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

How can I append these two as one array with shape (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.

解决方案

Use 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:

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

这篇关于将 2D 数组附加到 3D 数组,扩展第三维的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆