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

Time:07-06

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)

CodePudding user response:

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]]]

CodePudding user response:

You want to rotate 90 in the opposite direction of np.rot90, or equivalently rotate by 270 = 3 * 90 in the np.rot90 direction:

>>> np.rot90(foo, k=3, axes=(1, 2))
array([[[ 4,  1],
        [ 5,  2],
        [ 6,  3]],

       [[10,  7],
        [11,  8],
        [12,  9]]])

CodePudding user response:

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]]])
  • Related