Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting two numpy array channels

Tags:

python

numpy

I have two numpy arrays, for example:

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[11,12,13],[14,15,16],[17,18,19]]

Which are channels of the same image. I would like to get the "connected" channels array in a as pythonic way as possible. wanted outcome:

c = [[[1,11],[2,12],[3,13]],
    [[4,14],[5,15],[6,16]],
    [[7,17],[8,18],[9,19]]]

What Iv'e tried: I created an array of the same size and looped over both the source array to connect them.

for x in range(len(a)):
    for y in range(len(a[x])):
        c[x][y] = [a[x][y],b[x][y]]

What I need: I would love to find a more efficient, modular and pythonic way of implementing this.

like image 678
idik Avatar asked Feb 24 '26 06:02

idik


1 Answers

You can use np.stack on the second axis:

>>> np.stack((a,b),axis=2)
array([[[ 1, 11],
        [ 2, 12],
        [ 3, 13]],

       [[ 4, 14],
        [ 5, 15],
        [ 6, 16]],

       [[ 7, 17],
        [ 8, 18],
        [ 9, 19]]])

Checking that it's the same as your c array:

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

>>> (c == np.stack((a,b),axis=2)).all()
True
like image 87
sacuL Avatar answered Feb 26 '26 20:02

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!