Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate 90 deg of 2D array inside 3D array?

I have a 3D array consist of 2D arrays, I want to rotate only the 2D arrays inside the 3D array without changing the order, so it will become a 3D array consist of rotated 3D arrays.

For example, I have a 3D array like this.

foo = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(foo)
>>> array([[[ 1,  2,  3],
            [ 4,  5,  6]],

           [[ 7,  8,  9],
            [10, 11, 12]]])
foo.shape
>>> (2, 2, 3)

I want to rotate it into this.

rotated_foo = np.array([[[4, 1], [5, 2], [6, 3]], [[10, 7], [11, 8], [12, 9]]])
print(rotated_foo)
>>> array([[[ 4,  1],
            [ 5,  2],
            [ 6,  3]],

           [[10,  7],
            [11,  8],
            [12,  9]]])
rotated_foo.shape
>>> (2, 3, 2)

I've tried it using numpy's rot90 but I got something like this.

rotated_foo = np.rot90(foo)
print(rotated_foo)
>>> array([[[ 4,  5,  6],
            [10, 11, 12]],

           [[ 1,  2,  3],
            [ 7,  8,  9]]])
rotated_foo.shape
>>> (2, 2, 3)
like image 590
A'S Avatar asked Oct 25 '25 10:10

A'S


2 Answers

You can use numpy.rot90 by setting axes that you want to rotate.

foo = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
rotated_foo  = np.rot90(foo, axes=(2,1))
print(rotated_foo)

Output:

array([[[ 4,  1],
        [ 5,  2],
        [ 6,  3]],

       [[10,  7],
        [11,  8],
        [12,  9]]])
like image 157
I'mahdi Avatar answered Oct 27 '25 23:10

I'mahdi


Try np.transpose and np.flip:

print(np.flip(np.transpose(foo, (0, 2, 1)), axis=2))

Prints:

[[[ 4  1]
  [ 5  2]
  [ 6  3]]

 [[10  7]
  [11  8]
  [12  9]]]
like image 22
Andrej Kesely Avatar answered Oct 27 '25 23:10

Andrej Kesely



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!