Adding a 2D array to a 3D array, expanding the third dimension

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

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

I tried np.append(A,B) , but it does not save the measurement, and the axis parameter raises ValueError: all the input arrays must have same number of dimensions .

+5
source share
1 answer

Use dstack :

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

This handles cases where arrays are of different sizes and stack arrays along the third axis.

Otherwise, to use append or concatenate , you need to make B three-dimensional on your own and specify the axis you want to join:

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

Source: https://habr.com/ru/post/1238641/


All Articles