Search code examples
arraysnumpy3dimaging

Is there a way in python to stack arrays of pixels of same size (such as a z-stack)?


I just want to sort of clarify for example could I somehow stack a few 2D arrays into an image?

array1=[[0,0,0,0,0]
        [0,7.6,7,7.2,0]
        [0,7.6,7,0,0]
        [0,0,0,0,0]]

array2=[[0,0,0,0,0]
        [0,7.6,7,7.2,0]
        [0,7.6,7,0,0]
        [0,0,0,0,0]]

And then see them in 3D space such as the cube example at link

I haven't really tried much other than trying to make other things using the geeks for geeks code. So any direction at all would be appreciated.


Solution

  • Assuming numpy arrays as input (not python lists), you can use numpy.dstack:

    out = np.dstack((array1, array2))
    

    output:

    array([[[0. , 0. ],
            [0. , 0. ],
            [0. , 0. ],
            [0. , 0. ],
            [0. , 0. ]],
    
           [[0. , 0. ],
            [7.6, 7.6],
            [7. , 7. ],
            [7.2, 7.2],
            [0. , 0. ]],
    
           [[0. , 0. ],
            [7.6, 7.6],
            [7. , 7. ],
            [0. , 0. ],
            [0. , 0. ]],
    
           [[0. , 0. ],
            [0. , 0. ],
            [0. , 0. ],
            [0. , 0. ],
            [0. , 0. ]]])
    

    Although, if you want to plot, it might be easier to have a list of the arrays and loop.